From 2ee68c01ca48d705c2820627c158664946104643 Mon Sep 17 00:00:00 2001 From: "jinzheng.architect" Date: Fri, 16 Oct 2026 16:44:57 +0800 Subject: [PATCH] feat(cli): use the credential site login saved for every site command After `ptctl site login SITE`, every site command for that site works without a credential flag. `site login` keeps the TJUPT session cookie it issues, and now also saves an M-Team API key (typed hidden, or piped with --api-key-stdin) or a browser cookie (--cookie-stdin) once one status read accepts it. Status, account, search, detail, bonus catalog and review, metafile fetch, and bonus exchange submit read the saved file when no stdin flag is given; an explicit flag still wins. The saved file lives at ptctl/sessions/SITE.cookie or SITE.api-key under the user config directory, 0600 in a 0700 directory. It is refused without disclosure when it is a symlink or not a regular file, grants group or other access (outside Windows), changes while opened, or is not exactly one valid credential line. It is located after every other usage check and read where stdin would have been read, so the preflight order is unchanged. A saved credential never replaces an acknowledgement flag, and account and downloader passwords are never saved. `ptctl site logout SITE` deletes the saved files. Bonus exchange submit on a password-confirmed site (TJUPT) with the saved cookie asks for the account password with echo off before its timeout starts. Error messages that named a cookie or API-key path are reworded so the redactor no longer swallows their tail. Tests isolate HOME, XDG_CONFIG_HOME, and AppData so they never read real saved credentials; fixtures are synthetic canaries. Co-Authored-By: Claude Opus 5.5 --- README.md | 36 +- docs/ADDING_A_SITE.md | 7 +- docs/ARCHITECTURE.md | 28 +- docs/AUTOMATION.md | 48 ++- docs/FEATURES.md | 11 +- docs/MTEAM_ADAPTER.md | 50 ++- docs/THREAT_MODEL.md | 44 +- docs/TJUPT_ADAPTER.md | 38 +- docs/guide/metafiles.md | 18 +- docs/guide/sites.md | 142 ++++--- internal/cli/help.go | 9 +- internal/cli/main_test.go | 26 ++ internal/cli/output.go | 2 + internal/cli/run.go | 22 +- internal/cli/saved_credentials.go | 186 +++++++++ internal/cli/saved_credentials_test.go | 489 +++++++++++++++++++++++ internal/cli/site.go | 34 +- internal/cli/site_api_key_test.go | 18 +- internal/cli/site_bonus.go | 15 +- internal/cli/site_bonus_exchange.go | 59 ++- internal/cli/site_bonus_exchange_test.go | 5 +- internal/cli/site_detail.go | 21 +- internal/cli/site_login.go | 287 +++++++++++-- internal/cli/site_login_test.go | 2 +- internal/cli/site_metafile.go | 26 +- internal/cli/site_metafile_test.go | 8 +- 26 files changed, 1385 insertions(+), 246 deletions(-) create mode 100644 internal/cli/main_test.go create mode 100644 internal/cli/saved_credentials.go create mode 100644 internal/cli/saved_credentials_test.go diff --git a/README.md b/README.md index a6d462b..a8a0425 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,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; on M-Team, a token POST and the signed-link GET, plus at most one redirect hop), `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 saved only to an owner-only file or a pipe | +| Tracker-visible | `site metafile fetch` (one GET; on M-Team, a token POST and the signed-link GET, plus at most one redirect hop), `site bonus exchange submit` (at most one POST), `site login` (TJUPT: one POST and one verifying GET; an API key: one status read) | `--acknowledge-site-effect`, `--acknowledge-bonus-exchange`; `site login` is the command itself, with the credential saved only to an owner-only file or a pipe. A saved credential never stands in for an acknowledgement flag. | | 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` | @@ -124,28 +124,32 @@ ptctl site list ptctl site capabilities tjupt ``` -Check a site session. The complete `Cookie` header value is read only from -stdin; interactive TTY input is refused, and the cookie is never persisted: +Sign in to a site once. After that, every site command uses the saved +credential, so no credential flag is needed: ```bash -printf '%s' "$TJUPT_COOKIE" | ptctl site status --cookie-stdin tjupt +ptctl site login tjupt # username, hidden password, and two-step code +ptctl site login mteam # paste the API key (hidden) +ptctl site status tjupt +ptctl site search mteam "Ubuntu" +ptctl site detail mteam REMOTE_ID ``` -For TJUPT, `ptctl site login tjupt` can issue that cookie instead: it prompts -for the username, the hidden password, and the two-step code, then saves the -cookie to an owner-only file and prints its path. Scripts and agents use -`--credential-bundle-stdin`; see `ptctl help login` and -[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: +TJUPT's login sends one sign-in request and saves the session cookie it +issues; the password is never saved. M-Team uses an API key from +控制台 → 实验室 → 建立存取令牌; `site login mteam` checks it with one status read +before saving it. Both are saved in plaintext to an owner-only file under the +user config directory, and `ptctl site logout SITE` deletes it. Scripts and +agents can still pipe a credential for a single command instead, which always +takes precedence over the saved one: ```bash +printf '%s' "$TJUPT_COOKIE" | ptctl site status --cookie-stdin tjupt printf '%s' "$MTEAM_API_KEY" | ptctl site account --api-key-stdin mteam -printf '%s' "$MTEAM_API_KEY" | ptctl site search --api-key-stdin mteam "Ubuntu" -printf '%s' "$MTEAM_API_KEY" | ptctl site detail --api-key-stdin mteam REMOTE_ID ``` +See `ptctl help login` and [Site reads and bonus exchange](docs/guide/sites.md). + From there, the [command guide](docs/guide/README.md) walks through storing metafiles, proving content, materializing a layout, handing it to a downloader, and reconciling the result. @@ -172,7 +176,9 @@ A private `.torrent` is secret-bearing because its announce URL often contains a personal passkey. Site cookies, site API keys, and downloader credentials are also secrets, while filesystem reads can update atime, hydrate cloud placeholders, or incur -network cost. `ptctl` keeps credentials in memory, rejects secret arguments, +network cost. `ptctl` rejects secret arguments, keeps credentials in memory +except the one site credential `site login` saves owner-only (and `site +logout` deletes), never saves account or downloader passwords, emits no request bodies, blocks cross-origin/downgrade redirects, never retries site reads, bounds network and filesystem work, hides private store/object and discovery/reconciliation absolute paths by default, never exposes materialize diff --git a/docs/ADDING_A_SITE.md b/docs/ADDING_A_SITE.md index 00dd71a..d15f73e 100644 --- a/docs/ADDING_A_SITE.md +++ b/docs/ADDING_A_SITE.md @@ -40,8 +40,11 @@ flowchart LR `internal/site/sites` is the only place the CLI learns which sites exist. For each command, the CLI looks up the adapter by site ID, checks that the descriptor declares the capability and the auth method, asserts the typed port, -and only then reads the credential from stdin. Adapters never see filesystem -handles, stores, or downloader state. +and only then reads the credential, from stdin when a flag names it or else +from the file `site login` saved (`internal/cli/saved_credentials.go`). A new +site gets both sources and `site login --cookie-stdin|--api-key-stdin` without +CLI changes. Adapters never see filesystem handles, stores, or downloader +state. ## Step by step diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3cb0b30..ccdf1f0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -359,9 +359,20 @@ Capabilities are small and explicit: password and optional one-time code, typed at hidden terminal prompts or read from one stdin bundle, and returns a verified cookie credential. The CLI saves it to an owner-only file, by default under the user config directory, or -writes it to a non-terminal stdout, and never reads it back on its own. It -sends one login request and at most one verifying read, never retries, and -reports a refusal only by a fixed stop reason. +writes it to a non-terminal stdout. It sends one login request and at most one +verifying read, never retries, and reports a refusal only by a fixed stop +reason. For any site, `site login --cookie-stdin` or `--api-key-stdin` (and the +interactive default of an API-key site) instead checks a supplied credential +with one status read and saves it only if the read accepts it. + +`internal/cli/saved_credentials.go` resolves where each `site` command gets +its credential: an explicit stdin flag wins, otherwise the command reads the +owner-only file `site login` saved for the site's default auth method +(`ptctl/sessions/SITE.cookie` or `SITE.api-key`). The file is located after +every usage check and read at the same point stdin would have been, so the +preflight order is unchanged, and an unsafe or malformed file is refused +without disclosure. `site logout` deletes the files. Adapters still receive +only a `site.Credential` and cannot tell which source supplied it. 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 @@ -405,8 +416,10 @@ non-authoritative. `bonus.exchange.submit_effectful` workflow. A site that confirms each exchange with the account password, as TJUPT does, implements `site.PasswordConfirmedBonusExchangeWriter`: `submit` then reads the cookie and -password together from one strict `ptctl.credentials/v1` stdin bundle, refuses -`--cookie-stdin`, and the adapter adds the password to its single POST. +password together from one strict `ptctl.credentials/v1` stdin bundle, or uses +the saved cookie and asks for the password with echo off on the terminal before +its timeout starts. It refuses `--cookie-stdin`, never saves the password, and +the adapter adds the password to its single POST. `prepare` stores one canonical private intent containing a random operation ID, the exact reviewed semantic ID, canonical site/option/origin/route identifiers, and fixed review/submit @@ -699,10 +712,11 @@ uninitialized staging entries are not counted as committed artifacts. metafile artifact: ```text -site metafile fetch (--cookie-stdin | --api-key-stdin) --acknowledge-site-effect +site metafile fetch [--cookie-stdin | --api-key-stdin] --acknowledge-site-effect --metafile-store DIR SITE REMOTE_ID -> validate one site, one remote ID, limits, capability, auth method, and store - -> read the credential only after that zero-write preflight succeeds + -> read the credential, from stdin or the saved file, only after that + zero-write preflight succeeds -> linked routes only: request a site-issued link, bounded by MaxLinkRequests -> send one bounded metafile GET, with no automatic redirect and no retry -> strictly validate the complete exact response diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 9d58f0d..61f7f72 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -95,6 +95,16 @@ Per-command details are in ## Secrets +`ptctl site login SITE` saves the site credential once: the TJUPT session +cookie it issues, or the M-Team API key after one status read accepts it. +Every later `site` command for that site, including `site metafile fetch` and +`site bonus exchange submit`, then uses the saved credential without a flag. +An agent saves one without a terminal by piping it, +`site login --cookie-stdin SITE` or `site login --api-key-stdin SITE`, and +`ptctl site logout SITE` deletes it. An explicit stdin flag below always takes +precedence over the saved credential, and a saved credential never stands in +for an acknowledgement flag. + | Flag | Used by | Stdin content | |---|---|---| | `--cookie-stdin` | `site` reads, `site bonus exchange submit` for cookie-only sites, `site metafile fetch` for cookie sites (TJUPT) | The complete `Cookie` header value | @@ -104,26 +114,40 @@ Per-command details are in | `--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 | +| `--cookie-stdin`, `--api-key-stdin` | `site login` | The credential to save; one status read checks it first and nothing is saved when it fails | - An interactive terminal on stdin is refused; the secret must be piped. The - exception is `site login` without `--credential-bundle-stdin`, which is for - people: it prompts on the terminal with the password and code hidden, and - exits `2` when stdin is not a terminal. Agents always pass the bundle. + exception is `site login` without a stdin flag, which is for people: it + prompts on the terminal with the password, code, or API key hidden, and + exits `2` when stdin is not a terminal. Agents pass the bundle, + `--cookie-stdin`, or `--api-key-stdin`. `site bonus exchange submit` with + the saved cookie on a site that confirms with the account password (TJUPT) + asks for that password the same way, before its timeout starts; agents pass + the bundle instead. - 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. The one exception is the session cookie `site login` issues. - With `--cookie-file PATH` it is saved to that owner-only file, and - `--output json` then reports a `site.login` object with `cookie_file` and - `session_expires_at` but not the cookie. With the bundle and no - `--cookie-file`, it is written to stdout, which must be a pipe or an - owner-only file. Without the bundle, it is saved under the user config - directory. `ptctl help login` documents every flag. +- Credentials stay in memory. They are never printed or forwarded in error + text, and the only one persisted is the site credential `site login` saves. + Without the bundle, or with `--cookie-stdin` or `--api-key-stdin`, it goes + to `ptctl/sessions/SITE.cookie` or `SITE.api-key` under the user config + directory, a plaintext file readable only by its owner. With + `--cookie-file PATH` the session cookie is saved to that owner-only file + instead, and `--output json` then reports a `site.login` object with + `cookie_file` and `session_expires_at` but not the cookie; an API key save + reports `api_key_file`. With the bundle and no `--cookie-file`, the cookie + is written to stdout, which must be a pipe or an owner-only file, and is not + saved. Account and downloader passwords are never saved. + `ptctl help login` documents every flag. +- A saved credential is refused, without being shown, when it is not a + regular file, when other users can read it (outside Windows), or when it is + not exactly one valid credential line. Sign in again or run + `ptctl site logout SITE` to clear it. - `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. + `--api-key-stdin`. With neither a flag nor a saved credential the command + exits `2` and names both the `site login` command and the flag. - A failed ordinary site read prints `site CMD failed`. Adapters that opt in (currently M-Team) append one fixed cause after a colon: the credential has the wrong format, the site rejected the credential, the site rate limited diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 7bbccb4..8940148 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -103,12 +103,19 @@ deliberately does not. For step-by-step usage, see the one verifying read that must name the same account before the new session cookie is saved to an owner-only file or written to a pipe or owner-only stdout, with an optional `site.login` JSON report; +- saved site credentials: `site login SITE` keeps the TJUPT session cookie, or + an M-Team API key once one status read accepts it, in an owner-only file + under the user config directory, so later `site` commands, metafile fetch, + and bonus exchange submit need no credential flag; an explicit stdin flag + takes precedence, an unsafe or malformed file is refused without being + shown, acknowledgement flags are still required, account passwords are never + saved, and `site logout SITE` deletes the file; - an experimental M-Team session check, account snapshot (username, uploaded and downloaded bytes, ratio, and bonus), first-page torrent search with seeders, leechers, promotion factors, and category names, and torrent detail for one remote ID, through one read-only POST per invocation to the official - JSON API, authenticated by a site-issued API key read only from stdin, with - no redirect, proxy, or retry; + JSON API, authenticated by a site-issued API key saved by `site login` or + piped on stdin, with no redirect, proxy, or retry; - an explicitly acknowledged M-Team metafile fetch for one remote ID: one token POST for a signed download link, one credential-free GET of that link, and at most one further GET only for a redirect to an M-Team HTTPS host, with diff --git a/docs/MTEAM_ADAPTER.md b/docs/MTEAM_ADAPTER.md index 01e5f78..246a014 100644 --- a/docs/MTEAM_ADAPTER.md +++ b/docs/MTEAM_ADAPTER.md @@ -34,26 +34,44 @@ leaks. ## Usage -The key is read only from stdin. Interactive terminal input is refused, the key -is never accepted as an argument, and it is never written to disk or printed: +Save the key once. `site login mteam` asks for it with echo off, checks it with +one status read (`POST /api/member/profile`), and saves it only if the API +accepts it: ```bash -printf '%s' "$MTEAM_API_KEY" | ptctl site status --api-key-stdin mteam -printf '%s' "$MTEAM_API_KEY" | ptctl site account --api-key-stdin mteam -printf '%s' "$MTEAM_API_KEY" | ptctl site search --api-key-stdin mteam "Ubuntu" -printf '%s' "$MTEAM_API_KEY" | ptctl site search --api-key-stdin --output json mteam "Ubuntu" -printf '%s' "$MTEAM_API_KEY" | ptctl site detail --api-key-stdin mteam REMOTE_ID -printf '%s' "$MTEAM_API_KEY" | ptctl site metafile fetch --api-key-stdin \ - --acknowledge-site-effect --metafile-store "$PTCTL_STORE" mteam REMOTE_ID +ptctl site login mteam ``` -To keep the key out of shell history and your environment, pipe it from a -password manager instead, for example `op read op://Private/M-Team/api-key | -ptctl site account --api-key-stdin mteam`. +After that, every M-Team command uses the saved key: -Without `--api-key-stdin`, every M-Team command fails with a usage error before -anything is read; `--cookie-stdin` is refused because the adapter does not -accept cookies. +```bash +ptctl site status mteam +ptctl site account mteam +ptctl site search mteam "Ubuntu" +ptctl site search --output json mteam "Ubuntu" +ptctl site detail mteam REMOTE_ID +ptctl site metafile fetch --acknowledge-site-effect --metafile-store "$PTCTL_STORE" mteam REMOTE_ID +``` + +The key is saved in plaintext to `/ptctl/sessions/mteam.api-key` +(on macOS `~/Library/Application Support`, on Linux `$XDG_CONFIG_HOME` or +`~/.config`, on Windows `%AppData%`). The file is owner-only, in an owner-only +directory, and ptctl refuses to use it if group or other users can read it or +if it is a symlink. `ptctl site logout mteam` deletes it; revoke the key on the +M-Team page as well if it may have leaked. The key is never accepted as an +argument and never printed. + +Scripts and agents can save the key without a terminal, or skip saving and pipe +it to one command. A piped key always takes precedence over the saved one: + +```bash +ptctl site login --api-key-stdin --output json mteam < "$API_KEY_FILE" +op read op://Private/M-Team/api-key | ptctl site account --api-key-stdin mteam +``` + +Without a saved key and without `--api-key-stdin`, an M-Team command fails with +a usage error that names `ptctl site login mteam`, before anything is read or +sent. `--cookie-stdin` is refused because the adapter does not accept cookies. ## Requests @@ -151,6 +169,8 @@ These lines name the cause instead: |---|---|---| | `site CMD failed: the credential read from stdin does not have the format this site uses` | The key contains spaces, non-ASCII characters, or is too long. | Copy the token again. Leading and trailing whitespace is already trimmed. | | `site CMD failed: the site rejected the credential` | The API refused the key (`account` and `search`; `status` reports `unauthenticated` instead). | Check that the token is current, or create a new one. | +| `site login stopped: login_credentials_rejected` | `site login mteam` checked the key and the API did not accept it. Nothing was saved. | Copy the token again, or create a new one. | +| `refusing to use saved API key PATH because other users can access it; ...` | The saved key file is readable by group or other users. | Run `chmod 600 PATH`, or sign in again with `ptctl site login mteam`. | | `site CMD failed: the site rate limited the request; ...` | HTTP 429 or API code `4`. | Wait before trying again. ptctl never retries. | | `site CMD failed: the site host resolved only to private or reserved addresses, ...` | DNS returned only blocked addresses, typically from a proxy using fake-IP DNS (`198.18.0.0/15`, as in Clash or Mihomo fake-IP mode). | Exclude `api2.m-team.cc` from fake-IP (for example with `fake-ip-filter`) or use a resolver that returns real addresses. ptctl never uses a proxy. | | `site CMD timed out: context deadline exceeded` | The 45-second deadline passed. | Check connectivity. | diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 5de71cb..5baab1e 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -145,8 +145,39 @@ Without a cookie file it goes only to a pipe or an owner-only stdout file. The interactive default reads the password and one-time code from the terminal with echo turned off before each prompt appears (input typed ahead of a prompt can still be echoed), restores echo if interrupted, and saves the cookie under the -user config directory, which no command reads back implicitly; a terminal is -accepted only there, never with `--credential-bundle-stdin`. +user config directory; a terminal is accepted only there, never with +`--credential-bundle-stdin`. `site login --cookie-stdin` or +`--api-key-stdin` saves a piped credential to the same place, and the +interactive default for an API-key site (M-Team) reads the key with echo off; +either way one status read must accept the credential before it replaces an +earlier one. See [Saved site credentials](#saved-site-credentials). + +### Saved site credentials + +So that one sign-in serves every later command, `site login` keeps the site +credential at rest: `ptctl/sessions/SITE.cookie` or `SITE.api-key` under the +user config directory, a plaintext file of mode `0600` in a `0700` directory, +written through an owner-only temporary file and renamed into place. Every +`site` command for that site, including metafile fetch and bonus exchange +submit, reads it when no stdin credential flag is given; an explicit flag +always wins. This is a deliberate trade: anyone who can read the file as the +user, or any process the user runs, can act as the user on that site until the +session expires or the key is revoked. An M-Team API key does not expire on its +own, so its file is worth more than a TJUPT session cookie. + +The read side refuses, without showing the content, a path that is a symlink +or not a regular file, a file whose mode grants any group or other access +(outside Windows, where the user profile's ACL governs), a file that changes +between open and stat, and content that is not exactly one valid credential +line within the single-secret limit. The location and all other usage checks +are settled before the file is read, so a missing file is a usage error that +contacts no site. A saved credential never stands in for an acknowledgement +flag. `ptctl site logout SITE` deletes the saved files for the site, removing a +symlink rather than its target and refusing a directory; it does not end the +session or revoke the key on the site. Account and downloader passwords are +never saved. The file is not encrypted; an OS keyring or credential helper +remains future work (see +[Known gaps](#known-gaps-before-broader-mutation-support)). The M-Team adapter's reads send at most one bounded POST per command to one of three read-only JSON API endpoints (`member/profile`, `torrent/search`, and `torrent/detail`), with a non-replayable body of at most 16 KiB, and never @@ -191,9 +222,12 @@ and is never used to justify another automatic request. A site that confirms exchanges with the account password (TJUPT) widens the secret surface to that password, so its handling is narrower than the cookie's. -It is read only from the strict stdin bundle after every local check, never -from argv or a terminal, and lives in a type whose formatting is -`[REDACTED]`. The adapter appends it as one `passwd` field to the single POST; +It is never saved and never read from argv. With `--credential-bundle-stdin` +it is read from the strict bundle after every local check. With the saved +cookie and stdin on a terminal, it is read with echo off after the usage and +acknowledgement checks and before the timeout starts; without a terminal, the +command exits `2` before any request and names the bundle. Either way it +lives in a type whose formatting is `[REDACTED]`. The adapter appends it as one `passwd` field to the single POST; the encoded body is never logged, and receipts count only the reviewed form's bytes so the password length is not disclosed. A fresh form that already carries a `passwd` control is refused before the attempt marker rather than diff --git a/docs/TJUPT_ADAPTER.md b/docs/TJUPT_ADAPTER.md index 16da662..7977c15 100644 --- a/docs/TJUPT_ADAPTER.md +++ b/docs/TJUPT_ADAPTER.md @@ -183,18 +183,21 @@ states the price and asks for the password; the balance does not change. The same POST with `passwd` completes the exchange in one step. The adapter is therefore a `site.PasswordConfirmedBonusExchangeWriter`. -`site bonus exchange submit ... tjupt OPTION` requires -`--credential-bundle-stdin` with strict JSON on stdin: +`site bonus exchange submit ... tjupt OPTION` uses the cookie `site login` +saved and asks for the account password with echo off on the terminal, before +the timeout starts. Scripts and agents pass `--credential-bundle-stdin` with +strict JSON on stdin instead: ```json {"schema":"ptctl.credentials/v1","site_cookie":"...","site_password":"..."} ``` `--cookie-stdin` is refused as usage for TJUPT before the store or stdin is -touched, and a cookie-only session cannot be opened. The password must be valid -UTF-8 without control characters and at most 1024 bytes. It stays in memory as -an `AccountPassword`, which formats as `[REDACTED]`; it is never placed in argv, -persisted, or printed. +touched, as is the saved cookie when stdin is not a terminal, and a cookie-only +session cannot be opened. The password must be valid UTF-8 without control +characters and at most 1024 bytes. It stays in memory as an `AccountPassword`, +which formats as `[REDACTED]`; it is never placed in argv, persisted, or +printed. The workflow is otherwise the generic one: a fresh review GET, an exact-option rebind against the review ID, a durable attempt marker, and at most one POST. @@ -241,23 +244,30 @@ The generic workflow is described in ## Authentication 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)): +It receives the complete Cookie header value from the CLI, which takes it from +the cookie `site login` saved ([below](#login)) or, with `--cookie-stdin`, from +stdin for one process: ```bash +ptctl site login tjupt +ptctl site status tjupt printf '%s' "$TJUPT_COOKIE" | ptctl site status --cookie-stdin tjupt ``` -The value is held in memory and not persisted. Direct interactive terminal -input is refused to avoid echoing secrets; callers must use a pipe. A future credential provider -must use an OS keyring or an audited pipe-based helper; plaintext fallback will -not be automatic. +A browser cookie can be saved the same way with +`printf '%s' "$TJUPT_COOKIE" | ptctl site login --cookie-stdin tjupt`, which +saves it only after one status read accepts it. The saved cookie is a +plaintext owner-only file under the user config directory, refused when it is +not a regular owner-only file holding one valid cookie line, and deleted by +`ptctl site logout tjupt`; see the +[threat model](THREAT_MODEL.md#saved-site-credentials). Direct interactive +terminal input to `--cookie-stdin` is refused to avoid echoing secrets; it +takes a pipe. For ordinary `site status`, `site account`, `site search`, and `site bonus-catalog`, the CLI validates output mode, the selected adapter's capability and cookie authentication declaration, the corresponding typed -port, and a nonblank search query where relevant before it reads stdin. +port, and a nonblank search query where relevant before it reads the credential. 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. diff --git a/docs/guide/metafiles.md b/docs/guide/metafiles.md index 2cff785..7935823 100644 --- a/docs/guide/metafiles.md +++ b/docs/guide/metafiles.md @@ -26,11 +26,12 @@ ptctl metafile store inspect \ Fetch one exact private metafile directly into that initialized store. This is an effectful operation: the tracker may record the GET, so the acknowledgement must be explicit. All usage, the single remote ID, limits, capability, and -store assurances are checked before the credential is read from stdin: +store assurances are checked before the credential is read. The command uses +the credential `ptctl site login` saved for the site; a saved credential never +stands in for `--acknowledge-site-effect`: ```bash -printf '%s' "$TJUPT_COOKIE" | ptctl site metafile fetch \ - --cookie-stdin \ +ptctl site metafile fetch \ --acknowledge-site-effect \ --metafile-store "D:\Private\ptctl-metafiles" \ tjupt REMOTE_ID @@ -42,13 +43,20 @@ link requests are counted separately (see [MTEAM_ADAPTER.md](../MTEAM_ADAPTER.md#metafile-download)): ```bash -printf '%s' "$MTEAM_API_KEY" | ptctl site metafile fetch \ - --api-key-stdin \ +ptctl site metafile fetch \ --acknowledge-site-effect \ --metafile-store "D:\Private\ptctl-metafiles" \ mteam REMOTE_ID ``` +A script that does not keep a saved credential pipes it to this one command +instead, with `--cookie-stdin` for TJUPT or `--api-key-stdin` for M-Team: + +```bash +printf '%s' "$TJUPT_COOKIE" | ptctl site metafile fetch --cookie-stdin \ + --acknowledge-site-effect --metafile-store "D:\Private\ptctl-metafiles" tjupt REMOTE_ID +``` + The command performs no torrent-detail lookup and sends at most one metafile GET. It follows no redirect on its own, performs no retry, and offers no raw stdout or arbitrary destination. The validated response goes through the ordinary exact-byte, diff --git a/docs/guide/sites.md b/docs/guide/sites.md index 4667ce9..16720d0 100644 --- a/docs/guide/sites.md +++ b/docs/guide/sites.md @@ -4,25 +4,37 @@ > Fetching an exact private metafile from a site (`site metafile fetch`) and auditing its sealed bindings are described with the private store in [metafiles.md](metafiles.md). The page-level TJUPT contract is in [TJUPT_ADAPTER.md](../TJUPT_ADAPTER.md), and M-Team is covered in [MTEAM_ADAPTER.md](../MTEAM_ADAPTER.md). -Read TJUPT without putting a cookie in shell history. Stdin must contain the -complete `Cookie` header value from a session you control. Interactive TTY -secret input is refused. Do not paste the value into issues, logs, or chat. -For ordinary `status`, `account`, `search`, and `bonus-catalog` reads, output -mode, site/capability/authentication support, the declared typed port, and a -nonblank search query where applicable are all validated before stdin is read. -Runtime adapter failures are reduced to fixed public diagnostics; cancellation -and deadlines remain distinguishable, but cookie or response text is never -forwarded. +Sign in once with `site login`, then run site commands without any credential +flag. Each command uses the credential `site login` saved for that site: + +```bash +ptctl site login tjupt +ptctl site status tjupt +ptctl site account tjupt +ptctl site search tjupt "Ubuntu" +ptctl site detail tjupt REMOTE_ID +ptctl site bonus-catalog tjupt +ptctl site bonus review tjupt OPTION +``` + +Scripts and agents can instead pipe the complete `Cookie` header value from a +session they control on stdin with `--cookie-stdin`; an explicit flag always +takes precedence over the saved credential. Interactive TTY input is refused +for `--cookie-stdin`. Do not paste the value into issues, logs, or chat: ```bash printf '%s' "$TJUPT_COOKIE" | ptctl site status --cookie-stdin tjupt -printf '%s' "$TJUPT_COOKIE" | ptctl site account --cookie-stdin tjupt -printf '%s' "$TJUPT_COOKIE" | ptctl site search --cookie-stdin tjupt "Ubuntu" -printf '%s' "$TJUPT_COOKIE" | ptctl site detail --cookie-stdin tjupt REMOTE_ID -printf '%s' "$TJUPT_COOKIE" | ptctl site bonus-catalog --cookie-stdin tjupt -printf '%s' "$TJUPT_COOKIE" | ptctl site bonus review --cookie-stdin tjupt OPTION ``` +For ordinary `status`, `account`, `search`, and `bonus-catalog` reads, output +mode, site/capability/authentication support, the declared typed port, and a +nonblank search query where applicable are all validated before a credential +is read. Without a saved credential and without a flag, a command exits `2` +with `no saved session cookie for site "tjupt"; run 'ptctl site login tjupt' +first, or pipe one with --cookie-stdin`. Runtime adapter failures are reduced +to fixed public diagnostics; cancellation and deadlines remain +distinguishable, but cookie or response text is never forwarded. + Each read-only TJUPT command above performs at most one bounded GET and never retries. Do not loop or parallelize site reads. `site detail` also refuses redirects and sends only `details.php?id=REMOTE_ID`: it does not send `hit=1`, follow the download @@ -34,9 +46,8 @@ 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 save a new session cookie for the commands above. -Run it in a terminal and answer the prompts: +`site login tjupt` signs in with the account password and saves a new session +cookie for the commands above. Run it in a terminal and answer the prompts: ```console $ ptctl site login tjupt @@ -46,19 +57,32 @@ Password (hidden): Two-step code (hidden; press Enter if none): site login succeeded: site=tjupt username=alice session_expires=2026-10-23T08:00:00Z requests=2 session cookie saved to /home/alice/.config/ptctl/sessions/tjupt.cookie (owner-only) -use it with: ptctl site status --cookie-stdin tjupt < '/home/alice/.config/ptctl/sessions/tjupt.cookie' +site commands now use it when no --cookie-stdin is given, for example: ptctl site status tjupt ``` -The password and the two-step code are not echoed. Press Enter at the code -prompt when the account has no two-step verification; spaces inside a code are -ignored. Ctrl+C at a prompt quits without sending anything. The cookie is saved -to `ptctl/sessions/SITE.cookie` under the user config directory (`~/.config` on -Linux, `~/Library/Application Support` on macOS, `%AppData%` on Windows), -readable only by you, and replaced atomically by the next login. No command -reads it automatically; pass it on stdin as the last line shows. -`--cookie-file PATH` saves it somewhere else, and `--session-days` picks the -session length the site offers (TJUPT: 1, 7, 14, 30, or 90; default 7). -`ptctl help login` describes every flag. +The password and the two-step code are not echoed, and the password is never +saved. Press Enter at the code prompt when the account has no two-step +verification; spaces inside a code are ignored. Ctrl+C at a prompt quits +without sending anything. The cookie is saved in plaintext to +`ptctl/sessions/SITE.cookie` under the user config directory (`~/.config` or +`$XDG_CONFIG_HOME` on Linux, `~/Library/Application Support` on macOS, +`%AppData%` on Windows), in an owner-only file inside an owner-only directory, +and replaced atomically by the next login. Site commands refuse to use the +saved file if group or other users can read it, if it is a symlink or not a +regular file, or if its content is not one canonical value. `ptctl site logout +tjupt` deletes it without contacting the site; the session stays valid on the +site until it expires. + +`--cookie-file PATH` saves the cookie somewhere else instead, and then prints +how to pipe it with `--cookie-stdin`; commands do not read a file saved there +automatically. `--session-days` picks the session length the site offers +(TJUPT: 1, 7, 14, 30, or 90; default 7). `ptctl help login` describes every +flag. + +A cookie copied from a browser can be saved the same way. `site login +--cookie-stdin SITE` (or, at a terminal, `site login SITE` for a site without a +password login) checks it with one `site status` read and saves it only if that +read shows a signed-in account. Scripts and agents pass the credentials instead with `--credential-bundle-stdin`, as one strict `ptctl.credentials/v1` bundle on stdin: `site_username`, @@ -123,21 +147,32 @@ attempts left before it blocks this IP)`. Fix the input before trying again, and never loop `site login`. Usage errors exit `2` before any prompt or stdin read. A failed login leaves an earlier cookie file untouched. -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`, -`search`, and `detail` each send one read-only POST to M-Team's JSON API and -never retry; search results add seeders, leechers, promotion, and category-name -columns. `site metafile fetch --api-key-stdin` downloads one `.torrent` into the +When `site login` saves a cookie or API key you already have, its one check +read uses the same reasons: `login_credentials_rejected` when the site reports +the credential is not signed in, and `login_session_unverified` when the read +cannot tell. Nothing is saved after either, and an earlier saved credential is +kept. + +M-Team uses a site-issued API key instead of a cookie. `site login mteam` asks +for it with echo off, checks it with one status read, and saves it to +`ptctl/sessions/mteam.api-key` with the same owner-only rules; nothing is saved +if the API does not accept it. Scripts save it with `site login --api-key-stdin +mteam`, or pipe it to a single command with `--api-key-stdin`. `status`, +`account`, `search`, and `detail` each send one read-only POST to M-Team's JSON +API and never retry; search results add seeders, leechers, promotion, and +category-name columns. `site metafile fetch` downloads one `.torrent` into the private store through M-Team's signed link, as described in [metafiles.md](metafiles.md). Bonus commands are not available for M-Team yet, and `reconcile` reads live site detail with a cookie only. Setup, results, and error lines are in [MTEAM_ADAPTER.md](../MTEAM_ADAPTER.md): ```bash +ptctl site login mteam +ptctl site status mteam +ptctl site account mteam +ptctl site search mteam "Ubuntu" +ptctl site detail mteam REMOTE_ID printf '%s' "$MTEAM_API_KEY" | ptctl site status --api-key-stdin mteam -printf '%s' "$MTEAM_API_KEY" | ptctl site account --api-key-stdin mteam -printf '%s' "$MTEAM_API_KEY" | ptctl site search --api-key-stdin mteam "Ubuntu" -printf '%s' "$MTEAM_API_KEY" | ptctl site detail --api-key-stdin mteam REMOTE_ID ``` `site account` reads the authenticated `mybonus.php` page and reports the @@ -163,10 +198,14 @@ deliberately non-authoritative; the separate exchange workflow therefore fetches a fresh page, reproduces the reviewed semantics, and crosses an explicit acknowledgement and recovery boundary. -TJUPT confirms each exchange with the account password, so its `submit` takes -the cookie and password together as one strict JSON bundle on stdin -(`--credential-bundle-stdin`) and refuses `--cookie-stdin`; see the TJUPT -example below. A site that needs only the cookie takes `--cookie-stdin`. +TJUPT confirms each exchange with the account password. Without a credential +flag, its `submit` uses the saved session cookie and asks for the password on +the terminal with echo off; the password is used for that one exchange and +never saved. Scripts pass the cookie and password together as one strict JSON +bundle on stdin (`--credential-bundle-stdin`), and `--cookie-stdin` is refused; +see the TJUPT example below. A site that needs only the cookie uses the saved +cookie, or takes `--cookie-stdin`. A saved credential never stands in for +`--acknowledge-bonus-exchange`. To cross that boundary, first initialize a private state store (the same versioned owner-only store format used by metafile artifacts), review the exact @@ -175,8 +214,7 @@ option, and prepare a local intent from the review ID: ```bash ptctl metafile store init --store "$PTCTL_STATE" -printf '%s' "$SITE_COOKIE" | \ - ptctl site bonus review --cookie-stdin --output json SITE OPTION +ptctl site bonus review --output json SITE OPTION ptctl site bonus exchange prepare \ --state-store "$PTCTL_STATE" \ @@ -189,14 +227,12 @@ Submitting requires that exact record, the same site/option/review selectors, and a separate acknowledgement: ```bash -printf '%s' "$SITE_COOKIE" | \ - ptctl site bonus exchange submit \ - --state-store "$PTCTL_STATE" \ - --intent-record INTENT_RECORD_ID \ - --expect-review-id REVIEW_ID \ - --cookie-stdin \ - --acknowledge-bonus-exchange \ - SITE OPTION +ptctl site bonus exchange submit \ + --state-store "$PTCTL_STATE" \ + --intent-record INTENT_RECORD_ID \ + --expect-review-id REVIEW_ID \ + --acknowledge-bonus-exchange \ + SITE OPTION ptctl site bonus exchange status \ --state-store "$PTCTL_STATE" \ @@ -218,9 +254,9 @@ ptctl site bonus exchange forget \ --acknowledge-history-forget ``` -For TJUPT, replace the `submit` stdin and flag with the bundle. One way to -build it without putting either secret in argv, assuming each is kept in its -own owner-only file: +At a terminal, TJUPT's `submit` then asks for the account password. A script +replaces that prompt with the bundle. One way to build it without putting +either secret in argv, assuming each is kept in its own owner-only file: ```bash jq -n --rawfile cookie "$COOKIE_FILE" --rawfile password "$PASSWORD_FILE" \ diff --git a/internal/cli/help.go b/internal/cli/help.go index f9913ed..9a121e1 100644 --- a/internal/cli/help.go +++ b/internal/cli/help.go @@ -20,9 +20,10 @@ func (a *app) helpTopic(args []string) error { pt cli does not search your home/project directories for configuration or credentials. There is no --config file or saved downloader-login profile. The one thing -saved by default is the session cookie from an interactive 'pt site login', -under the user config directory; no command reads it back automatically -(see 'pt help login'). +saved is the site credential from 'pt site login': a session cookie or API key +in an owner-only file under the user config directory. Site commands use it +when no --cookie-stdin or --api-key-stdin flag is given, and 'pt site logout' +deletes it (see 'pt help login'). Downloader reads: --driver qbittorrent|transmission (default: qbittorrent) @@ -77,6 +78,8 @@ Details: pt help reconcile report | pt help config `) case "login", "site login": fmt.Fprint(a.stdout, siteLoginHelp) + case "logout", "site logout": + fmt.Fprint(a.stdout, siteLogoutHelp) case "version": return a.version([]string{"--help"}) case "torrent inspect": diff --git a/internal/cli/main_test.go b/internal/cli/main_test.go new file mode 100644 index 0000000..63559f0 --- /dev/null +++ b/internal/cli/main_test.go @@ -0,0 +1,26 @@ +package cli + +import ( + "fmt" + "os" + "testing" +) + +// TestMain points the user config directory at an empty temporary one, so no +// test ever reads or sends a credential 'site login' saved for the real user. +func TestMain(m *testing.M) { + home, err := os.MkdirTemp("", "ptctl-cli-test-home-") + if err != nil { + fmt.Fprintln(os.Stderr, "create test home:", err) + os.Exit(1) + } + for _, name := range []string{"HOME", "XDG_CONFIG_HOME", "AppData"} { + if err := os.Setenv(name, home); err != nil { + fmt.Fprintln(os.Stderr, "isolate test home:", err) + os.Exit(1) + } + } + code := m.Run() + _ = os.RemoveAll(home) + os.Exit(code) +} diff --git a/internal/cli/output.go b/internal/cli/output.go index f45dbc6..454fe06 100644 --- a/internal/cli/output.go +++ b/internal/cli/output.go @@ -59,6 +59,8 @@ func jsonKind(data any) string { return "site.bonus.catalog" case siteLoginReport: return "site.login" + case siteLogoutReport: + return "site.logout" case *metafile.MetaInfo: return "metafile.manifest" case metafileStoreReport: diff --git a/internal/cli/run.go b/internal/cli/run.go index f1625a5..15c3747 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -135,19 +135,21 @@ Usage: ptctl site capabilities [--output table|json] [SITE] ptctl site login [--cookie-file PATH] [--session-days N] [--output table|json] SITE ptctl site login --credential-bundle-stdin [--cookie-file PATH] [--session-days N] [--output table|json] 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... - ptctl site detail (--cookie-stdin | --api-key-stdin) [--output table|json] SITE REMOTE_ID - ptctl site bonus-catalog --cookie-stdin [--output table|json] SITE - ptctl site bonus review --cookie-stdin [--output table|json] SITE OPTION + ptctl site login (--cookie-stdin | --api-key-stdin) [--output table|json] SITE + ptctl site logout [--output table|json] 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... + ptctl site detail [--cookie-stdin | --api-key-stdin] [--output table|json] SITE REMOTE_ID + ptctl site bonus-catalog [--cookie-stdin] [--output table|json] SITE + ptctl site bonus review [--cookie-stdin] [--output table|json] SITE OPTION ptctl site bonus exchange prepare --state-store DIR --expect-review-id ID [--output table|json] SITE OPTION - ptctl site bonus exchange submit --state-store DIR --intent-record RECORD_ID --expect-review-id ID (--cookie-stdin | --credential-bundle-stdin) --acknowledge-bonus-exchange [--output table|json] SITE OPTION + ptctl site bonus exchange submit --state-store DIR --intent-record RECORD_ID --expect-review-id ID [--cookie-stdin | --credential-bundle-stdin] --acknowledge-bonus-exchange [--output table|json] SITE OPTION ptctl site bonus exchange status --state-store DIR --intent-record RECORD_ID [--output table|json] ptctl site bonus exchange list --state-store DIR [--max-operations N] [--output table|json] ptctl site bonus exchange prune --state-store DIR --intent-record RECORD_ID --operation-id ID --acknowledge-state-prune [--output table|json] ptctl site bonus exchange forget --state-store DIR --retention-record RECORD_ID --operation-id ID --acknowledge-history-forget [--output table|json] - ptctl site metafile fetch (--cookie-stdin | --api-key-stdin) --acknowledge-site-effect --metafile-store DIR [--output table|json] SITE REMOTE_ID + ptctl site metafile fetch [--cookie-stdin | --api-key-stdin] --acknowledge-site-effect --metafile-store DIR [--output table|json] SITE REMOTE_ID ptctl site metafile binding list --metafile-store DIR [--output table|json] ptctl site metafile binding inspect --metafile-store DIR [--output table|json] RECORD_ID @@ -221,8 +223,8 @@ 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; the one exception is the cookie site login obtains, which it saves where it says. - * Site login prompts on the terminal with the password and one-time code hidden, or reads them from stdin with --credential-bundle-stdin; it sends one login request plus one verifying read, never retries, and saves the new session cookie only to an owner-only file or a non-terminal stdout. See 'pt help login'. + * Credentials are never accepted in argv. Site commands use the session cookie or API key that site login saved for the site, in an owner-only file under the user config directory, unless --cookie-stdin or --api-key-stdin pipes one in; site logout deletes the saved file. Downloader passwords and account passwords are never saved. + * Site login prompts on the terminal with every secret hidden, or reads from stdin with --credential-bundle-stdin, --cookie-stdin, or --api-key-stdin; it sends one login request plus one verifying read (or only the verifying read for a cookie or API key), never retries, and saves only after that read succeeds. See 'pt help login'. * .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/saved_credentials.go b/internal/cli/saved_credentials.go new file mode 100644 index 0000000..2326967 --- /dev/null +++ b/internal/cli/saved_credentials.go @@ -0,0 +1,186 @@ +package cli + +import ( + "bytes" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +// Saved site credentials. 'site login' saves one credential per site under +// the user config directory, and every site command uses it when no +// --cookie-stdin or --api-key-stdin flag is given. An explicit flag always +// wins, so scripts keep full control over what is sent. + +const maxSavedCredentialBytes = 64 << 10 + +// siteCredentialSource says where one site command reads its credential. +type siteCredentialSource struct { + method domain.AuthMethod + saved bool + // savedPath is the file 'site login' saved, set by locateSaved. + savedPath string +} + +// defaultSiteAuthMethod is the method a site signs in with when no flag names +// one: the API key for a site that only takes API keys, else the cookie. +func defaultSiteAuthMethod(descriptor domain.SiteDescriptor) domain.AuthMethod { + if descriptor.SupportsAuth(domain.AuthMethodAPIKeyHeader) && !descriptor.SupportsAuth(domain.AuthMethodCookieHeader) { + return domain.AuthMethodAPIKeyHeader + } + return domain.AuthMethodCookieHeader +} + +func credentialStdinFlag(method domain.AuthMethod) string { + if method == domain.AuthMethodAPIKeyHeader { + return "--api-key-stdin" + } + return "--cookie-stdin" +} + +func savedCredentialLabel(method domain.AuthMethod) string { + if method == domain.AuthMethodAPIKeyHeader { + return "API key" + } + return "session cookie" +} + +// savedCredentialPath is where 'site login' keeps the credential of one site: +// /ptctl/sessions/SITE.cookie or SITE.api-key. +func savedCredentialPath(siteID string, method domain.AuthMethod) (string, error) { + dir, err := os.UserConfigDir() + if err != nil { + return "", err + } + name := siteID + ".cookie" + if method == domain.AuthMethodAPIKeyHeader { + name = siteID + ".api-key" + } + return filepath.Join(dir, "ptctl", "sessions", name), nil +} + +// siteCredentialSourceFor picks the credential method of one site command and +// checks the site accepts it. An explicit flag selects stdin; with neither +// flag the command uses the saved credential for the site's default method. +func siteCredentialSourceFor(descriptor domain.SiteDescriptor, cookieStdin, apiKeyStdin bool) (siteCredentialSource, error) { + method := defaultSiteAuthMethod(descriptor) + switch { + case cookieStdin: + method = domain.AuthMethodCookieHeader + case apiKeyStdin: + method = domain.AuthMethodAPIKeyHeader + } + if !descriptor.SupportsAuth(method) { + return siteCredentialSource{}, usageError("site %q does not support %s authentication", descriptor.ID, method) + } + return siteCredentialSource{method: method, saved: !cookieStdin && !apiKeyStdin}, nil +} + +// locateSaved finds the saved credential once every other usage check has +// passed, so a missing file is a usage error and nothing is read or sent. +func (source *siteCredentialSource) locateSaved(siteID string) error { + if !source.saved { + return nil + } + label, flag := savedCredentialLabel(source.method), credentialStdinFlag(source.method) + path, err := savedCredentialPath(siteID, source.method) + if err != nil { + return usageError("no user config directory for a saved %s; pipe one with %s", label, flag) + } + if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) { + return usageError("no saved %s for site %q; run 'ptctl site login %s' first, or pipe one with %s", label, siteID, siteID, flag) + } + source.savedPath = path + return nil +} + +// readSiteCredential reads the credential from its source. Stdin keeps the +// command's own reader; a saved file is always parsed canonically. +func (a *app) readSiteCredential(source siteCredentialSource, fromStdin func(io.Reader) (site.Credential, error)) (site.Credential, error) { + if !source.saved { + return fromStdin(a.stdin) + } + if source.savedPath == "" { + return site.Credential{}, fmt.Errorf("saved %s was not located", savedCredentialLabel(source.method)) + } + return readSavedCredential(source.savedPath, source.method) +} + +// siteCredentialReadError is what a report-writing command returns when its +// credential cannot be read. Stdin keeps the generic line; a saved file's +// error names the file and what is wrong with it, never its content. +func siteCredentialReadError(source siteCredentialSource, err error) error { + if source.saved { + return err + } + return fmt.Errorf("read site credential failed") +} + +// readSavedCredential reads one saved credential. It refuses a symlink or +// other non-regular file, and on systems with Unix permissions a file that +// group or other users can access. The error texts name the file, never its +// content. +func readSavedCredential(path string, method domain.AuthMethod) (site.Credential, error) { + label := savedCredentialLabel(method) + info, err := os.Lstat(path) + if err != nil { + return site.Credential{}, fmt.Errorf("read saved %s %s failed", label, path) + } + if !info.Mode().IsRegular() { + return site.Credential{}, fmt.Errorf("refusing to use saved %s %s because it is not a regular file", label, path) + } + file, err := os.Open(path) + if err != nil { + return site.Credential{}, fmt.Errorf("read saved %s %s failed", label, path) + } + defer file.Close() + opened, err := file.Stat() + if err != nil || !os.SameFile(info, opened) { + return site.Credential{}, fmt.Errorf("saved %s %s changed while it was opened", label, path) + } + if runtime.GOOS != "windows" && opened.Mode().Perm()&0o077 != 0 { + return site.Credential{}, fmt.Errorf("refusing to use saved %s %s because other users can access it; make it owner-only (chmod 600) or sign in again", label, path) + } + raw, err := io.ReadAll(io.LimitReader(file, maxSavedCredentialBytes+3)) + if err != nil { + return site.Credential{}, fmt.Errorf("read saved %s %s failed", label, path) + } + if bytes.HasSuffix(raw, []byte("\r\n")) { + raw = raw[:len(raw)-2] + } else if bytes.HasSuffix(raw, []byte("\n")) { + raw = raw[:len(raw)-1] + } + var credential site.Credential + if method == domain.AuthMethodAPIKeyHeader { + credential, err = canonicalAPIKeyCredential(raw) + } else { + credential, err = canonicalCookieCredential(raw) + } + if err != nil { + return site.Credential{}, fmt.Errorf("saved %s %s is invalid; sign in again with 'ptctl site login'", label, path) + } + return credential, nil +} + +// askBonusExchangePassword asks for the account password with echo off. The +// password confirms this one exchange and is never saved. +func (a *app) askBonusExchangePassword(terminal promptTerminal, descriptor domain.SiteDescriptor) (site.AccountPassword, error) { + value, err := terminal.ReadSecret(func() { + fmt.Fprintf(a.stderr, "%s confirms this exchange with the account password (hidden, not saved): ", terminalSafe(descriptor.Name)) + }) + fmt.Fprintln(a.stderr) + if err != nil { + return site.AccountPassword{}, fmt.Errorf("read the account password from the terminal failed; nothing was submitted") + } + password, err := site.NewAccountPassword(value) + if err != nil { + return site.AccountPassword{}, fmt.Errorf("bonus exchange account password is invalid; nothing was submitted") + } + return password, nil +} diff --git a/internal/cli/saved_credentials_test.go b/internal/cli/saved_credentials_test.go new file mode 100644 index 0000000..7a0b69e --- /dev/null +++ b/internal/cli/saved_credentials_test.go @@ -0,0 +1,489 @@ +package cli + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/tonycoder-hub/ptctl/internal/bonusexchange" + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/metastore" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +const ( + savedCookieCanary = "sid=SAVED-COOKIE-CANARY" + savedAPIKeyCanary = "SAVED-API-KEY-CANARY" + terminalPasswordCan = "PASSWORD-TERMINAL-CANARY" +) + +// writeSavedCredential saves content where 'site login' would for siteID, +// owner-only, inside the temporary config directory of the test. +func writeSavedCredential(t *testing.T, siteID string, method domain.AuthMethod, content string) string { + t.Helper() + path, err := savedCredentialPath(siteID, method) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func authenticatedAPIKeySite() *apiKeySiteAdapter { + return &apiKeySiteAdapter{status: domain.SessionStatus{ + State: domain.AuthenticationAuthenticated, Username: "Alice", ObservedAt: time.Date(2026, 10, 16, 1, 2, 3, 0, time.UTC), + }} +} + +func TestSavedCredentialServesEverySiteCommandWithoutReadingStdin(t *testing.T) { + useTempConfigDir(t) + writeSavedCredential(t, "api-key-test", domain.AuthMethodAPIKeyHeader, savedAPIKeyCanary+"\n") + writeSavedCredential(t, "fakept", domain.AuthMethodAPIKeyHeader, savedAPIKeyCanary+"\r\n") + + for _, args := range [][]string{ + {"status", "--output", "json", "api-key-test"}, + {"search", "--output", "json", "api-key-test", "query"}, + } { + adapter := authenticatedAPIKeySite() + stdin := &trackingReader{} + var out, errOut bytes.Buffer + a := &app{stdin: stdin, stdout: &out, stderr: &errOut, registry: site.NewRegistry(adapter)} + if err := a.siteRead(args[0], args[1:]); err != nil { + t.Fatalf("%s: %v", args[0], err) + } + if stdin.read || adapter.calls != 1 || adapter.method != domain.AuthMethodAPIKeyHeader || adapter.secret != savedAPIKeyCanary || + strings.Contains(out.String()+errOut.String(), "CANARY") { + t.Fatalf("%s: read=%t calls=%d method=%q stdout=%q stderr=%q", args[0], stdin.read, adapter.calls, adapter.method, out.String(), errOut.String()) + } + } + + detail := successfulFakeTorrentDetail(t) + detail.authMethod = domain.AuthMethodAPIKeyHeader + stdin := &trackingReader{} + var out bytes.Buffer + a := &app{stdin: stdin, stdout: &out, stderr: &bytes.Buffer{}, registry: site.NewRegistry(detail)} + if err := a.siteDetail([]string{"--output", "json", "fakept", "42"}); err != nil || stdin.read || detail.opened != 1 || + detail.credential != savedAPIKeyCanary || strings.Contains(out.String(), "CANARY") { + t.Fatalf("detail err=%v read=%t opened=%d stdout=%q", err, stdin.read, detail.opened, out.String()) + } + + // A cookie site finds its own file; the API key saved for the same site + // is never sent in its place. + writeSavedCredential(t, "fakept", domain.AuthMethodCookieHeader, savedCookieCanary+"\n") + review := successfulFakeBonusReview(t) + stdin, out = &trackingReader{}, bytes.Buffer{} + a = &app{stdin: stdin, stdout: &out, stderr: &bytes.Buffer{}, registry: site.NewRegistry(review)} + if err := a.siteBonusReview([]string{"--output", "json", "fakept", "1"}); err != nil || stdin.read || review.opened != 1 || + review.credential != savedCookieCanary || strings.Contains(out.String(), "CANARY") { + t.Fatalf("bonus review err=%v read=%t opened=%d stdout=%q", err, stdin.read, review.opened, out.String()) + } + + storeRoot := filepath.Join(physicalCLITempDir(t), "store") + if _, _, err := metastore.Init(storeRoot); err != nil { + t.Fatal(err) + } + fetch := &fakeMetafileFetchAdapter{raw: sitePrivateTrackerMetafile("saved.bin", []byte("x"), "SAVED-PASSKEY-CANARY")} + stdin, out = &trackingReader{}, bytes.Buffer{} + a = &app{stdin: stdin, stdout: &out, stderr: &bytes.Buffer{}, registry: site.NewRegistry(fetch)} + if err := a.siteMetafileFetch([]string{"--acknowledge-site-effect", "--metafile-store", storeRoot, "--output", "json", "fakept", "42"}); err != nil || + stdin.read || fetch.opened != 1 || fetch.lastCredential != savedCookieCanary || strings.Contains(out.String(), "CANARY") { + t.Fatalf("metafile fetch err=%v read=%t opened=%d stdout=%q", err, stdin.read, fetch.opened, out.String()) + } + assertDirectoryExcludesText(t, storeRoot, savedCookieCanary) +} + +func TestExplicitCredentialFlagWinsOverTheSavedOne(t *testing.T) { + useTempConfigDir(t) + writeSavedCredential(t, "api-key-test", domain.AuthMethodAPIKeyHeader, savedAPIKeyCanary+"\n") + adapter := authenticatedAPIKeySite() + a := &app{stdin: strings.NewReader(apiKeyCanary + "\n"), stdout: &bytes.Buffer{}, stderr: &bytes.Buffer{}, registry: site.NewRegistry(adapter)} + if err := a.siteRead("status", []string{"--api-key-stdin", "api-key-test"}); err != nil || adapter.secret != apiKeyCanary { + t.Fatalf("err=%v explicit key sent=%t", err, adapter.secret == apiKeyCanary) + } +} + +func TestSavedCredentialThatIsUnsafeOrInvalidIsRefusedWithoutDisclosure(t *testing.T) { + type savedCase struct { + name string + setup func(t *testing.T, path string) + want string + } + write := func(content string, mode os.FileMode) func(*testing.T, string) { + return func(t *testing.T, path string) { + if err := os.WriteFile(path, []byte(content), mode); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, mode); err != nil { + t.Fatal(err) + } + } + } + cases := []savedCase{ + {name: "empty", setup: write("", 0o600), want: "is invalid; sign in again with 'ptctl site login'"}, + {name: "blank line", setup: write("\n", 0o600), want: "is invalid; sign in again with 'ptctl site login'"}, + {name: "inner space", setup: write("SAVED-API KEY-CANARY\n", 0o600), want: "is invalid; sign in again with 'ptctl site login'"}, + {name: "two lines", setup: write(savedAPIKeyCanary+"\nSECOND-LINE-CANARY\n", 0o600), want: "is invalid; sign in again with 'ptctl site login'"}, + {name: "extra newline", setup: write(savedAPIKeyCanary+"\n\n", 0o600), want: "is invalid; sign in again with 'ptctl site login'"}, + {name: "oversized", setup: write(strings.Repeat("A", maxSavedCredentialBytes+1), 0o600), want: "is invalid; sign in again with 'ptctl site login'"}, + {name: "directory", setup: func(t *testing.T, path string) { + if err := os.Mkdir(path, 0o700); err != nil { + t.Fatal(err) + } + }, want: "it is not a regular file"}, + } + if runtime.GOOS != "windows" { + cases = append(cases, + savedCase{name: "group readable", setup: write(savedAPIKeyCanary+"\n", 0o640), want: "other users can access it; make it owner-only (chmod 600) or sign in again"}, + savedCase{name: "symlink", setup: func(t *testing.T, path string) { + target := filepath.Join(t.TempDir(), "target") + write(savedAPIKeyCanary+"\n", 0o600)(t, target) + if err := os.Symlink(target, path); err != nil { + t.Fatal(err) + } + }, want: "it is not a regular file"}, + ) + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + useTempConfigDir(t) + path := writeSavedCredential(t, "api-key-test", domain.AuthMethodAPIKeyHeader, "") + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + test.setup(t, path) + adapter := authenticatedAPIKeySite() + stdin := &trackingReader{} + var out, errOut bytes.Buffer + a := &app{stdin: stdin, stdout: &out, stderr: &errOut, registry: site.NewRegistry(adapter)} + code := runWithApp([]string{"site", "status", "api-key-test"}, a) + if code != 1 || stdin.read || adapter.calls != 0 || out.Len() != 0 || + !strings.Contains(errOut.String(), "saved API key "+path) || !strings.Contains(errOut.String(), test.want) || + strings.Contains(errOut.String(), "CANARY") || strings.Contains(errOut.String(), "AAAA") { + t.Fatalf("code=%d read=%t calls=%d stdout=%q stderr=%q", code, stdin.read, adapter.calls, out.String(), errOut.String()) + } + }) + } +} + +func TestSiteLoginPromptsForAnAPIKeyAndSavesItOnlyAfterTheCheck(t *testing.T) { + useTempConfigDir(t) + path, err := savedCredentialPath("api-key-test", domain.AuthMethodAPIKeyHeader) + if err != nil { + t.Fatal(err) + } + adapter := authenticatedAPIKeySite() + terminal := &fakeTerminal{answers: []string{" " + apiKeyCanary + " \n"}} + var out bytes.Buffer + code, stderr := runInteractiveLogin(adapter, terminal, &out, "api-key-test") + if code != 0 || out.Len() != 0 || fmt.Sprint(terminal.secret) != "[true]" || adapter.calls != 1 || + adapter.method != domain.AuthMethodAPIKeyHeader || adapter.secret != apiKeyCanary { + t.Fatalf("code=%d stdout=%q hidden=%v calls=%d stderr=%q", code, out.String(), terminal.secret, adapter.calls, stderr) + } + if written, err := os.ReadFile(path); err != nil || string(written) != apiKeyCanary+"\n" { + t.Fatalf("saved API key content mismatch err=%v", err) + } + if runtime.GOOS != "windows" { + for check, want := range map[string]os.FileMode{path: 0o600, filepath.Dir(path): 0o700} { + if info, err := os.Stat(check); err != nil || info.Mode().Perm() != want { + t.Fatalf("%s err=%v, want mode %v", check, err, want) + } + } + } + assertOnlyEntries(t, filepath.Dir(path), "api-key-test.api-key") + if want := "Saving the API key for API key test; one read checks it first.\nAPI key (hidden): \n" + + "site login succeeded: site=api-key-test username=Alice requests=1\n" + + "API key saved to " + path + " (owner-only)\n" + + "site commands now use it when no --api-key-stdin is given, for example: ptctl site status api-key-test\n"; stderr != want { + t.Fatalf("stderr=%q\nwant %q", stderr, want) + } + + // After login, the plain command works. + stdin := &trackingReader{} + status := authenticatedAPIKeySite() + a := &app{stdin: stdin, stdout: &bytes.Buffer{}, stderr: &bytes.Buffer{}, registry: site.NewRegistry(status)} + if err := a.siteRead("status", []string{"api-key-test"}); err != nil || stdin.read || status.secret != apiKeyCanary { + t.Fatalf("status after login err=%v read=%t", err, stdin.read) + } +} + +func TestSiteLoginSavesAPipedAPIKeyAndReportsJSON(t *testing.T) { + useTempConfigDir(t) + path, err := savedCredentialPath("api-key-test", domain.AuthMethodAPIKeyHeader) + if err != nil { + t.Fatal(err) + } + adapter := authenticatedAPIKeySite() + var out bytes.Buffer + code, stderr := runSiteLogin(adapter, strings.NewReader(apiKeyCanary+"\n"), &out, "--api-key-stdin", "--output", "json", "api-key-test") + if code != 0 || stderr != "" || adapter.calls != 1 || adapter.secret != apiKeyCanary || strings.Contains(out.String(), "CANARY") { + t.Fatalf("code=%d calls=%d stdout=%q stderr=%q", code, adapter.calls, out.String(), stderr) + } + var envelope struct { + Kind string `json:"kind"` + Data map[string]json.RawMessage `json:"data"` + } + if err := json.Unmarshal(out.Bytes(), &envelope); err != nil { + t.Fatal(err) + } + wantPath, _ := json.Marshal(path) + if envelope.Kind != "site.login" || string(envelope.Data["site_id"]) != `"api-key-test"` || string(envelope.Data["username"]) != `"Alice"` || + string(envelope.Data["api_key_file"]) != string(wantPath) || string(envelope.Data["requests_attempted"]) != "1" || len(envelope.Data) != 4 { + t.Fatalf("report=%s", out.String()) + } + if written, err := os.ReadFile(path); err != nil || string(written) != apiKeyCanary+"\n" { + t.Fatalf("saved API key content mismatch err=%v", err) + } +} + +func TestSiteLoginSavesNothingWhenTheCheckFails(t *testing.T) { + tests := []struct { + state domain.AuthenticationState + err error + want string + }{ + {state: domain.AuthenticationUnauthenticated, want: "site login stopped: login_credentials_rejected"}, + {state: domain.AuthenticationIndeterminate, want: "site login stopped: login_session_unverified"}, + {err: fmt.Errorf("status: %w", site.ErrCredentialRejected), want: "site login failed: " + site.ErrCredentialRejected.Error()}, + {err: fmt.Errorf("status: %w", site.ErrRateLimited), want: "site login failed: " + site.ErrRateLimited.Error()}, + {err: errors.New("body api_key=" + apiKeyCanary), want: "site login failed"}, + } + for _, test := range tests { + useTempConfigDir(t) + path := writeSavedCredential(t, "api-key-test", domain.AuthMethodAPIKeyHeader, savedAPIKeyCanary+"\n") + adapter := &apiKeySiteAdapter{status: domain.SessionStatus{State: test.state}, err: test.err} + var out bytes.Buffer + code, stderr := runSiteLogin(adapter, strings.NewReader(apiKeyCanary), &out, "--api-key-stdin", "api-key-test") + if code != 1 || adapter.calls != 1 || out.Len() != 0 || stderr != "error: "+test.want+"\n" { + t.Fatalf("want=%q code=%d calls=%d stdout=%q stderr=%q", test.want, code, adapter.calls, out.String(), stderr) + } + // The previous saved key is left exactly as it was. + if written, err := os.ReadFile(path); err != nil || string(written) != savedAPIKeyCanary+"\n" { + t.Fatalf("want=%q replaced the saved key: err=%v", test.want, err) + } + assertOnlyEntries(t, filepath.Dir(path), "api-key-test.api-key") + } +} + +func TestSiteLoginSaveModeUsageErrorsNeverReadStdin(t *testing.T) { + cookieFile := filepath.Join(t.TempDir(), "cookie") + tests := []struct { + adapter site.Adapter + args []string + want string + }{ + {authenticatedAPIKeySite(), []string{"--api-key-stdin", "--cookie-stdin", "api-key-test"}, "site login accepts only one of --credential-bundle-stdin, --cookie-stdin, and --api-key-stdin"}, + {authenticatedAPIKeySite(), []string{"--api-key-stdin", "--credential-bundle-stdin", "api-key-test"}, "site login accepts only one of"}, + {authenticatedAPIKeySite(), []string{"--api-key-stdin", "--cookie-file", cookieFile, "api-key-test"}, "--cookie-file and --session-days apply only to a password login"}, + {authenticatedAPIKeySite(), []string{"--session-days", "7", "api-key-test"}, "--cookie-file and --session-days apply only to a password login"}, + {authenticatedAPIKeySite(), []string{"--cookie-stdin", "api-key-test"}, `site "api-key-test" does not support cookie_header authentication`}, + {authenticatedAPIKeySite(), []string{"api-key-test"}, "site login prompts on an interactive terminal; without one, pipe the API key with --api-key-stdin"}, + {successfulLoginAdapter(t), []string{"--api-key-stdin", "fakept"}, `site "fakept" does not support api_key_header authentication`}, + {successfulLoginAdapter(t), []string{"--cookie-stdin", "fakept"}, `site "fakept" cannot verify a saved credential because it does not declare capability "auth.check"`}, + } + for _, test := range tests { + useTempConfigDir(t) + reader := &trackingReader{} + var out bytes.Buffer + code, stderr := runSiteLogin(test.adapter, reader, &out, test.args...) + if code != 2 || reader.read || out.Len() != 0 || !strings.Contains(stderr, test.want) { + t.Fatalf("args=%q code=%d read=%t stderr=%q", test.args, code, reader.read, stderr) + } + if api, ok := test.adapter.(*apiKeySiteAdapter); ok && api.calls != 0 { + t.Fatalf("args=%q contacted the site", test.args) + } + if _, err := os.Stat(cookieFile); !os.IsNotExist(err) { + t.Fatalf("args=%q wrote the cookie file", test.args) + } + } + + useTempConfigDir(t) + path, err := savedCredentialPath("api-key-test", domain.AuthMethodAPIKeyHeader) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(path, 0o700); err != nil { + t.Fatal(err) + } + adapter, reader := authenticatedAPIKeySite(), &trackingReader{} + code, stderr := runSiteLogin(adapter, reader, &bytes.Buffer{}, "--api-key-stdin", "api-key-test") + if code != 2 || reader.read || adapter.calls != 0 || + !strings.Contains(stderr, "refusing to replace saved API key "+path+" because it is not a regular file") { + t.Fatalf("directory destination code=%d read=%t stderr=%q", code, reader.read, stderr) + } +} + +func TestSiteLogoutDeletesOnlyTheSavedCredentials(t *testing.T) { + useTempConfigDir(t) + run := func(args ...string) (int, string, string, *fakeLoginAdapter) { + adapter := successfulLoginAdapter(t) + var out, errOut bytes.Buffer + a := &app{stdin: &trackingReader{}, stdout: &out, stderr: &errOut, registry: site.NewRegistry(adapter)} + code := runWithApp(append([]string{"site", "logout"}, args...), a) + if adapter.calls != 0 { + t.Fatalf("logout contacted the site") + } + return code, out.String(), errOut.String(), adapter + } + + cookie := writeSavedCredential(t, "fakept", domain.AuthMethodCookieHeader, savedCookieCanary+"\n") + apiKey := writeSavedCredential(t, "fakept", domain.AuthMethodAPIKeyHeader, savedAPIKeyCanary+"\n") + code, stdout, stderr, _ := run("fakept") + if want := "deleted saved session cookie " + cookie + "\ndeleted saved API key " + apiKey + "\n" + + "nothing was sent to the site; a session cookie stays valid there until it expires, and an API key until you revoke it\n"; code != 0 || stdout != "" || stderr != want { + t.Fatalf("code=%d stdout=%q stderr=%q", code, stdout, stderr) + } + assertOnlyEntries(t, filepath.Dir(cookie)) + if code, stdout, stderr, _ = run("fakept"); code != 0 || stdout != "" || stderr != "no saved credential for site fakept\n" { + t.Fatalf("second logout code=%d stdout=%q stderr=%q", code, stdout, stderr) + } + + cookie = writeSavedCredential(t, "fakept", domain.AuthMethodCookieHeader, savedCookieCanary+"\n") + for _, want := range [][]string{{cookie}, {}} { + code, stdout, stderr, _ = run("--output", "json", "fakept") + var envelope struct { + Kind string `json:"kind"` + Data siteLogoutReport `json:"data"` + } + if err := json.Unmarshal([]byte(stdout), &envelope); err != nil || code != 0 || stderr != "" || envelope.Kind != "site.logout" || + envelope.Data.SiteID != "fakept" || envelope.Data.RemovedFiles == nil || strings.Join(envelope.Data.RemovedFiles, ",") != strings.Join(want, ",") { + t.Fatalf("code=%d stdout=%q stderr=%q err=%v", code, stdout, stderr, err) + } + } + + if err := os.Mkdir(cookie, 0o700); err != nil { + t.Fatal(err) + } + if code, stdout, stderr, _ = run("fakept"); code != 1 || stdout != "" || + stderr != "error: refusing to delete saved session cookie "+cookie+" because it is not a regular file\n" { + t.Fatalf("directory code=%d stdout=%q stderr=%q", code, stdout, stderr) + } + if info, err := os.Stat(cookie); err != nil || !info.IsDir() { + t.Fatalf("the directory was removed: %v", err) + } + if err := os.Remove(cookie); err != nil { + t.Fatal(err) + } + + if runtime.GOOS != "windows" { + target := filepath.Join(t.TempDir(), "elsewhere") + if err := os.WriteFile(target, []byte(savedCookieCanary+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, cookie); err != nil { + t.Fatal(err) + } + if code, _, stderr, _ = run("fakept"); code != 0 || !strings.Contains(stderr, "deleted saved session cookie "+cookie) { + t.Fatalf("symlink code=%d stderr=%q", code, stderr) + } + if _, err := os.Lstat(cookie); !os.IsNotExist(err) { + t.Fatalf("the symlink is still there: %v", err) + } + if _, err := os.Stat(target); err != nil { + t.Fatalf("the symlink target was deleted: %v", err) + } + } + + for _, args := range [][]string{{}, {"fakept", "extra"}, {"unknown"}, {"--output", "yaml", "fakept"}} { + if code, stdout, _, _ = run(args...); code != 2 || stdout != "" { + t.Fatalf("args=%q code=%d stdout=%q", args, code, stdout) + } + } +} + +func TestSiteBonusExchangeSubmitUsesTheSavedCookieAndAsksForThePassword(t *testing.T) { + useTempConfigDir(t) + writeSavedCredential(t, "fakept", domain.AuthMethodCookieHeader, savedCookieCanary+"\n") + adapter := &fakePasswordBonusExchangeAdapter{fakeBonusExchangeAdapter: successfulFakeBonusExchange(t)} + adapter.confirmationCode = "fake.bonus_exchange.confirm" + site.BonusExchangeMessageConfirmationSuffix + stateRoot := initializedBonusExchangeStore(t) + reviewID := adapter.review.ReviewID + prepared := runBonusExchangeCLI(t, &app{stdin: &trackingReader{}, registry: site.NewRegistry(adapter)}, []string{ + "prepare", "--state-store", stateRoot, "--expect-review-id", reviewID, "--output", "json", "fakept", "1", + }, false) + intent := prepared.Operation.IntentRecord.ID.String() + stdin := &trackingReader{} + submit := func(terminal *fakeTerminal, stdout, stderr *bytes.Buffer, flags ...string) error { + a := &app{stdin: stdin, stdout: stdout, stderr: stderr, registry: site.NewRegistry(adapter), + terminal: func(io.Reader) (promptTerminal, bool) { return terminal, true }} + return a.siteBonusExchange(append([]string{ + "submit", "--state-store", stateRoot, "--intent-record", intent, "--expect-review-id", reviewID, "--output", "json", + }, append(flags, "fakept", "1")...)) + } + + // The acknowledgement is still required, and without it nothing is asked. + var out, errOut bytes.Buffer + none := &fakeTerminal{} + var usage *usageErr + if err := submit(none, &out, &errOut); !errors.As(err, &usage) || err.Error() != "site bonus exchange submit requires --acknowledge-bonus-exchange" || + len(none.secret) != 0 || out.Len() != 0 || errOut.Len() != 0 { + t.Fatalf("err=%v asked=%d stdout=%q stderr=%q", err, len(none.secret), out.String(), errOut.String()) + } + // A terminal that gives no password stops before any session opens. + if err := submit(none, &out, &errOut, "--acknowledge-bonus-exchange"); err == nil || + err.Error() != "read the account password from the terminal failed; nothing was submitted" || out.Len() != 0 || adapter.opened != 0 { + t.Fatalf("err=%v opened=%d stdout=%q", err, adapter.opened, out.String()) + } + if status := runBonusExchangeCLI(t, &app{stdin: &trackingReader{}, registry: site.NewRegistry(adapter)}, []string{ + "status", "--state-store", stateRoot, "--intent-record", intent, "--output", "json", + }, false); status.Outcome != bonusexchange.StatePrepared || status.Operation.AttemptRecord != nil { + t.Fatalf("a failed prompt changed durable state: %#v", status) + } + + terminal := &fakeTerminal{answers: []string{terminalPasswordCan}} + out.Reset() + errOut.Reset() + if err := submit(terminal, &out, &errOut, "--acknowledge-bonus-exchange"); err != nil { + t.Fatalf("err=%v stdout=%s", err, out.String()) + } + if stdin.read || fmt.Sprint(terminal.secret) != "[true]" || adapter.passwordOpens != 1 || adapter.cookieOnlyOpens != 0 || adapter.submissions != 1 || + adapter.credential != savedCookieCanary || adapter.password != terminalPasswordCan { + t.Fatalf("read=%t hidden=%v adapter=%#v", stdin.read, terminal.secret, adapter) + } + if errOut.String() != "Fake PT confirms this exchange with the account password (hidden, not saved): \n" || strings.Contains(out.String(), "CANARY") { + t.Fatalf("stderr=%q stdout=%s", errOut.String(), out.String()) + } + var envelope struct { + Data siteBonusExchangeReport `json:"data"` + } + if err := json.Unmarshal(out.Bytes(), &envelope); err != nil || envelope.Data.Outcome != bonusexchange.StateConfirmed { + t.Fatalf("err=%v report=%s", err, out.String()) + } + assertDirectoryExcludesText(t, stateRoot, savedCookieCanary) + assertDirectoryExcludesText(t, stateRoot, terminalPasswordCan) +} + +func TestSiteBonusExchangeSubmitUsesTheSavedCookieWithoutATerminal(t *testing.T) { + useTempConfigDir(t) + writeSavedCredential(t, "fakept", domain.AuthMethodCookieHeader, savedCookieCanary+"\n") + adapter := successfulFakeBonusExchange(t) + stateRoot := initializedBonusExchangeStore(t) + reviewID := adapter.review.ReviewID + prepared := runBonusExchangeCLI(t, &app{stdin: &trackingReader{}, registry: site.NewRegistry(adapter)}, []string{ + "prepare", "--state-store", stateRoot, "--expect-review-id", reviewID, "--output", "json", "fakept", "1", + }, false) + stdin := &trackingReader{} + submitted := runBonusExchangeCLI(t, &app{stdin: stdin, registry: site.NewRegistry(adapter)}, []string{ + "submit", "--state-store", stateRoot, "--intent-record", prepared.Operation.IntentRecord.ID.String(), + "--expect-review-id", reviewID, "--acknowledge-bonus-exchange", "--output", "json", "fakept", "1", + }, false) + if stdin.read || submitted.Outcome != bonusexchange.StateConfirmed || adapter.opened != 1 || adapter.submissions != 1 || adapter.credential != savedCookieCanary { + t.Fatalf("read=%t submitted=%#v adapter=%#v", stdin.read, submitted, adapter) + } + assertDirectoryExcludesText(t, stateRoot, savedCookieCanary) +} diff --git a/internal/cli/site.go b/internal/cli/site.go index 958502b..07012db 100644 --- a/internal/cli/site.go +++ b/internal/cli/site.go @@ -28,6 +28,8 @@ func (a *app) site(args []string) error { return a.siteDetail(args[1:]) case "login": return a.siteLogin(args[1:]) + case "logout": + return a.siteLogout(args[1:]) case "bonus": if len(args) >= 2 { switch args[1] { @@ -133,9 +135,6 @@ func (a *app) siteRead(command string, args []string) error { if *cookieStdin && *apiKeyStdin { return usageError("--cookie-stdin and --api-key-stdin are mutually exclusive") } - if !*cookieStdin && !*apiKeyStdin { - return usageError("%s is required; credentials are never accepted in argv", requiredCredentialFlag(a.registry, fs.Arg(0))) - } adapter, ok := a.registry.Get(fs.Arg(0)) if !ok { return usageError("unknown site %q", fs.Arg(0)) @@ -153,12 +152,13 @@ func (a *app) siteRead(command string, args []string) error { if !descriptor.Supports(capability) { return usageError("site %q does not declare capability %q", descriptor.ID, capability) } - method, readSecret := domain.AuthMethodCookieHeader, readCredential - if *apiKeyStdin { - method, readSecret = domain.AuthMethodAPIKeyHeader, readAPIKeyCredential + source, err := siteCredentialSourceFor(descriptor, *cookieStdin, *apiKeyStdin) + if err != nil { + return err } - if !descriptor.SupportsAuth(method) { - return usageError("site %q does not support %s authentication", descriptor.ID, method) + readSecret := readCredential + if source.method == domain.AuthMethodAPIKeyHeader { + readSecret = readAPIKeyCredential } var read func(context.Context, site.Credential) (any, error) var warnings []string @@ -203,7 +203,10 @@ func (a *app) siteRead(command string, args []string) error { default: return usageError("unknown site read command %q", command) } - credential, err := readSecret(a.stdin) + if err := source.locateSaved(descriptor.ID); err != nil { + return err + } + credential, err := a.readSiteCredential(source, readSecret) if err != nil { return err } @@ -236,19 +239,6 @@ func siteReadPublicError(ctx context.Context, command string, err error) error { return fmt.Errorf("site %s failed", command) } -// requiredCredentialFlag names the stdin flag a site's read commands need. A -// site that only accepts API keys gets --api-key-stdin; every other site, and -// an unknown one, keeps the original --cookie-stdin message. -func requiredCredentialFlag(registry *site.Registry, id string) string { - if adapter, ok := registry.Get(id); ok { - descriptor := adapter.Descriptor() - if descriptor.SupportsAuth(domain.AuthMethodAPIKeyHeader) && !descriptor.SupportsAuth(domain.AuthMethodCookieHeader) { - return "--api-key-stdin" - } - } - return "--cookie-stdin" -} - func writeSiteHuman(out io.Writer, command string, data any, warnings []string) error { w := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0) switch command { diff --git a/internal/cli/site_api_key_test.go b/internal/cli/site_api_key_test.go index de0da25..a813fe2 100644 --- a/internal/cli/site_api_key_test.go +++ b/internal/cli/site_api_key_test.go @@ -70,15 +70,15 @@ func TestSiteReadSendsAPIKeyFromStdin(t *testing.T) { } } -func TestSiteReadNamesTheCredentialFlagASiteNeeds(t *testing.T) { +func TestSiteReadWithoutAFlagNamesTheSavedCredentialASiteNeeds(t *testing.T) { tests := []struct { args []string want string }{ - {args: []string{"site", "status", "mteam"}, want: "--api-key-stdin is required; credentials are never accepted in argv"}, - {args: []string{"site", "search", "mteam", "query"}, want: "--api-key-stdin is required; credentials are never accepted in argv"}, - {args: []string{"site", "status", "tjupt"}, want: "--cookie-stdin is required; credentials are never accepted in argv"}, - {args: []string{"site", "account", "unknown-site"}, want: "--cookie-stdin is required; credentials are never accepted in argv"}, + {args: []string{"site", "status", "mteam"}, want: "no saved API key for site \"mteam\"; run 'ptctl site login mteam' first, or pipe one with --api-key-stdin"}, + {args: []string{"site", "search", "mteam", "query"}, want: "no saved API key for site \"mteam\"; run 'ptctl site login mteam' first, or pipe one with --api-key-stdin"}, + {args: []string{"site", "status", "tjupt"}, want: "no saved session cookie for site \"tjupt\"; run 'ptctl site login tjupt' first, or pipe one with --cookie-stdin"}, + {args: []string{"site", "account", "unknown-site"}, want: `unknown site "unknown-site"`}, {args: []string{"site", "status", "--cookie-stdin", "--api-key-stdin", "mteam"}, want: "--cookie-stdin and --api-key-stdin are mutually exclusive"}, } for _, test := range tests { @@ -301,9 +301,9 @@ func TestSiteDetailNamesAndChecksTheCredentialFlagBeforeReadingIt(t *testing.T) args []string want string }{ - {adapter: apiKeyOnly(), args: []string{"fakept", "42"}, want: "--api-key-stdin is required; credentials are never accepted in argv"}, + {adapter: apiKeyOnly(), args: []string{"fakept", "42"}, want: "no saved API key for site \"fakept\"; run 'ptctl site login fakept' first, or pipe one with --api-key-stdin"}, {adapter: apiKeyOnly(), args: []string{"--cookie-stdin", "fakept", "42"}, want: `site "fakept" does not support cookie_header authentication`}, - {adapter: successfulFakeTorrentDetail(t), args: []string{"fakept", "42"}, want: "--cookie-stdin is required; credentials are never accepted in argv"}, + {adapter: successfulFakeTorrentDetail(t), args: []string{"fakept", "42"}, want: "no saved session cookie for site \"fakept\"; run 'ptctl site login fakept' first, or pipe one with --cookie-stdin"}, {adapter: successfulFakeTorrentDetail(t), args: []string{"--api-key-stdin", "fakept", "42"}, want: `site "fakept" does not support api_key_header authentication`}, {adapter: successfulFakeTorrentDetail(t), args: []string{"--cookie-stdin", "--api-key-stdin", "fakept", "42"}, want: "--cookie-stdin and --api-key-stdin are mutually exclusive"}, } { @@ -317,8 +317,8 @@ func TestSiteDetailNamesAndChecksTheCredentialFlagBeforeReadingIt(t *testing.T) args []string want string }{ - {args: []string{"site", "detail", "mteam", "1"}, want: "--api-key-stdin is required; credentials are never accepted in argv"}, - {args: []string{"site", "detail", "tjupt", "1"}, want: "--cookie-stdin is required; credentials are never accepted in argv"}, + {args: []string{"site", "detail", "mteam", "1"}, want: "no saved API key for site \"mteam\"; run 'ptctl site login mteam' first, or pipe one with --api-key-stdin"}, + {args: []string{"site", "detail", "tjupt", "1"}, want: "no saved session cookie for site \"tjupt\"; run 'ptctl site login tjupt' first, or pipe one with --cookie-stdin"}, {args: []string{"site", "detail", "--api-key-stdin", "tjupt", "1"}, want: `site "tjupt" does not support api_key_header authentication`}, {args: []string{"site", "detail", "--cookie-stdin", "mteam", "1"}, want: `site "mteam" does not support cookie_header authentication`}, } { diff --git a/internal/cli/site_bonus.go b/internal/cli/site_bonus.go index 64005d2..24d6c3d 100644 --- a/internal/cli/site_bonus.go +++ b/internal/cli/site_bonus.go @@ -60,9 +60,6 @@ func (a *app) siteBonusReview(args []string) error { if err := validateOutput(*output); err != nil { return err } - if !*cookieStdin { - return usageError("--cookie-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)) @@ -74,6 +71,11 @@ func (a *app) siteBonusReview(args []string) error { if !descriptor.SupportsAuth(domain.AuthMethodCookieHeader) { return usageError("site %q does not support cookie_header authentication", descriptor.ID) } + // The site takes cookies, so without the flag this picks its saved cookie. + source, err := siteCredentialSourceFor(descriptor, *cookieStdin, false) + if err != nil { + return err + } reader, ok := adapter.(site.BonusReviewReader) if !ok { return usageError("site %q declares %q but does not implement its typed port", descriptor.ID, domain.CapabilityBonusReview) @@ -90,12 +92,15 @@ func (a *app) siteBonusReview(args []string) error { if err := limits.Validate(); err != nil { return usageError("site bonus review limits are invalid") } + if err := source.locateSaved(descriptor.ID); err != nil { + return err + } report := newSiteBonusReviewReport(descriptor.ID, selector, config, limits) - credential, err := readCredential(a.stdin) + credential, err := a.readSiteCredential(source, readCredential) if err != nil { report.Blockers = append(report.Blockers, siteDetailFinding{Code: "credential.unavailable", Message: "the site credential could not be read"}) - return a.finishSiteBonusReview(*output, report, fmt.Errorf("read site credential failed")) + return a.finishSiteBonusReview(*output, report, siteCredentialReadError(source, err)) } ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) defer cancel() diff --git a/internal/cli/site_bonus_exchange.go b/internal/cli/site_bonus_exchange.go index 6fd53a6..867b883 100644 --- a/internal/cli/site_bonus_exchange.go +++ b/internal/cli/site_bonus_exchange.go @@ -536,8 +536,8 @@ func (a *app) siteBonusExchangeSubmit(args []string) error { if *cookieStdin && *bundleStdin { return usageError("site bonus exchange submit accepts --cookie-stdin or --credential-bundle-stdin, not both") } - if (!*cookieStdin && !*bundleStdin) || !*acknowledge { - return usageError("site bonus exchange submit requires --cookie-stdin and --acknowledge-bonus-exchange") + if !*acknowledge { + return usageError("site bonus exchange submit requires --acknowledge-bonus-exchange") } if err := validateOutput(*output); err != nil { return err @@ -557,12 +557,33 @@ func (a *app) siteBonusExchangeSubmit(args []string) error { return err } passwordWriter, needsPassword := writer.(site.PasswordConfirmedBonusExchangeWriter) - if needsPassword && !*bundleStdin { + if needsPassword && *cookieStdin { return usageError("site %q confirms bonus exchange with the account password; submit requires --credential-bundle-stdin", descriptor.ID) } if !needsPassword && *bundleStdin { return usageError("site %q bonus exchange takes only --cookie-stdin", descriptor.ID) } + // Without a flag the saved cookie is used, and a site that confirms with + // the account password asks for it, hidden, on this terminal. + source := siteCredentialSource{method: domain.AuthMethodCookieHeader, saved: !*cookieStdin && !*bundleStdin} + var terminal promptTerminal + if source.saved && needsPassword { + var ok bool + if terminal, ok = a.promptTerminal(); !ok { + return usageError("site %q confirms bonus exchange with the account password; without a terminal to ask for it, submit requires --credential-bundle-stdin", descriptor.ID) + } + } + if err := source.locateSaved(descriptor.ID); err != nil { + return err + } + // The password is asked for before the timeout starts, so typing it does + // not use up the time the review and submission have. + var savedPassword site.AccountPassword + if terminal != nil { + if savedPassword, err = a.askBonusExchangePassword(terminal, descriptor); err != nil { + return err + } + } report := newSiteBonusExchangeReport("site.bonus.exchange.submit", descriptor.ID, fs.Arg(1), *expectedReview, config) report.Effect = []string{site.BonusReviewReadEffect, bonusexchange.ReserveEffect, site.BonusExchangeSubmitEffect, bonusexchange.OutcomeEffect} report.Acknowledgement = siteBonusExchangeAcknowledgement{Provided: true, Scope: "one_fresh_review_then_at_most_one_form_submission"} @@ -615,19 +636,30 @@ func (a *app) siteBonusExchangeSubmit(args []string) error { var siteSession site.BonusExchangeSession if needsPassword { - credential, password, readErr := readBonusExchangeCredentialBundle(a.stdin) + var credential site.Credential + var password site.AccountPassword + var readErr error + if source.saved { + credential, readErr = a.readSiteCredential(source, nil) + password = savedPassword + } else { + credential, password, readErr = readBonusExchangeCredentialBundle(a.stdin) + if readErr != nil { + readErr = fmt.Errorf("read site credential failed") + } + } if readErr != nil { _ = stateSession.Close() addBonusExchangeBlocker(&report, "credential.read_failed", "the site credential could not be read") - return a.finishSiteBonusExchange(*output, report, fmt.Errorf("read site credential failed")) + return a.finishSiteBonusExchange(*output, report, readErr) } siteSession, err = passwordWriter.OpenPasswordConfirmedBonusExchangeSession(ctx, credential, password) } else { - credential, readErr := readEffectfulSiteCredential(a.stdin) + credential, readErr := a.readSiteCredential(source, readEffectfulSiteCredential) if readErr != nil { _ = stateSession.Close() addBonusExchangeBlocker(&report, "credential.read_failed", "the site credential could not be read") - return a.finishSiteBonusExchange(*output, report, fmt.Errorf("read site credential failed")) + return a.finishSiteBonusExchange(*output, report, siteCredentialReadError(source, readErr)) } siteSession, err = writer.OpenBonusExchangeSession(ctx, credential) } @@ -1286,7 +1318,7 @@ func bonusRecordID(ref *metastore.RecordRef) string { func (a *app) siteBonusExchangeHelp() { fmt.Fprint(a.stdout, `Usage: ptctl site bonus exchange prepare --state-store DIR --expect-review-id ID [--output table|json] SITE OPTION - ptctl site bonus exchange submit --state-store DIR --intent-record RECORD_ID --expect-review-id ID (--cookie-stdin | --credential-bundle-stdin) --acknowledge-bonus-exchange [--output table|json] SITE OPTION + ptctl site bonus exchange submit --state-store DIR --intent-record RECORD_ID --expect-review-id ID [--cookie-stdin | --credential-bundle-stdin] --acknowledge-bonus-exchange [--output table|json] SITE OPTION ptctl site bonus exchange status --state-store DIR --intent-record RECORD_ID [--output table|json] ptctl site bonus exchange list --state-store DIR [--max-operations N] [--output table|json] ptctl site bonus exchange prune --state-store DIR --intent-record RECORD_ID --operation-id ID --acknowledge-state-prune [--output table|json] @@ -1297,10 +1329,13 @@ the production adapter before reading stdin, performs one fresh bounded review, durably publishes a deterministic at-most-once attempt marker, and only then may submit the exact opaque form once. There are no redirects or retries. -A site that confirms each exchange with the account password, such as TJUPT, -requires --credential-bundle-stdin instead of --cookie-stdin. Pipe strict JSON -containing schema "ptctl.credentials/v1", site_cookie, and site_password. The -password is added to that single POST only; it is never stored or printed. +Without a credential flag, submit uses the session cookie 'ptctl site login +SITE' saved. A site that confirms each exchange with the account password, such +as TJUPT, then asks for the password on this terminal with echo off. Scripts +pipe credentials instead: --cookie-stdin for a cookie alone, or, for a site +that needs the password, --credential-bundle-stdin with strict JSON containing +schema "ptctl.credentials/v1", site_cookie, and site_password. The password is +added to that single POST only; it is never stored or printed. After the POST, a bounded local finalization interval may persist the exact adapter observation even if the network context ended. If no durable outcome diff --git a/internal/cli/site_bonus_exchange_test.go b/internal/cli/site_bonus_exchange_test.go index 54dc8bd..8532c6d 100644 --- a/internal/cli/site_bonus_exchange_test.go +++ b/internal/cli/site_bonus_exchange_test.go @@ -323,7 +323,8 @@ func TestSiteBonusExchangeCredentialFlagsMatchTheSite(t *testing.T) { {password, []string{"--cookie-stdin"}, `site "fakept" confirms bonus exchange with the account password; submit requires --credential-bundle-stdin`}, {cookieOnly, []string{"--credential-bundle-stdin"}, `site "fakept" bonus exchange takes only --cookie-stdin`}, {password, []string{"--cookie-stdin", "--credential-bundle-stdin"}, "accepts --cookie-stdin or --credential-bundle-stdin, not both"}, - {cookieOnly, nil, "requires --cookie-stdin and --acknowledge-bonus-exchange"}, + {cookieOnly, nil, "no saved session cookie for site \"fakept\"; run 'ptctl site login fakept' first, or pipe one with --cookie-stdin"}, + {password, nil, `site "fakept" confirms bonus exchange with the account password; without a terminal to ask for it, submit requires --credential-bundle-stdin`}, } for _, test := range tests { reader := &trackingReader{} @@ -895,7 +896,7 @@ func TestSiteBonusExchangeHelpAndDispatch(t *testing.T) { var out, errOut bytes.Buffer if code := Run([]string{"site", "bonus", "exchange", "help"}, strings.NewReader(""), &out, &errOut); code != 0 || !strings.Contains(out.String(), "deterministic at-most-once attempt marker") || !strings.Contains(out.String(), "never chooses a latest operation") || !strings.Contains(out.String(), "acknowledge-state-prune") || !strings.Contains(out.String(), "acknowledge-history-forget") || !strings.Contains(out.String(), "submission-unknown operations are never pruned") || - !strings.Contains(out.String(), "(--cookie-stdin | --credential-bundle-stdin)") || !strings.Contains(out.String(), "site_password") { + !strings.Contains(out.String(), "[--cookie-stdin | --credential-bundle-stdin]") || !strings.Contains(out.String(), "site_password") { t.Fatalf("code=%d out=%q err=%q", code, out.String(), errOut.String()) } out.Reset() diff --git a/internal/cli/site_detail.go b/internal/cli/site_detail.go index 8d2ee40..5f2660c 100644 --- a/internal/cli/site_detail.go +++ b/internal/cli/site_detail.go @@ -60,9 +60,6 @@ func (a *app) siteDetail(args []string) error { if *cookieStdin && *apiKeyStdin { return usageError("--cookie-stdin and --api-key-stdin are mutually exclusive") } - if !*cookieStdin && !*apiKeyStdin { - return usageError("%s is required; credentials are never accepted in argv", requiredCredentialFlag(a.registry, fs.Arg(0))) - } adapter, ok := a.registry.Get(fs.Arg(0)) if !ok { return usageError("unknown site %q", fs.Arg(0)) @@ -71,12 +68,13 @@ func (a *app) siteDetail(args []string) error { if !descriptor.Supports(domain.CapabilityDetail) { return usageError("site %q does not declare capability %q", descriptor.ID, domain.CapabilityDetail) } - method, readSecret := domain.AuthMethodCookieHeader, readCredential - if *apiKeyStdin { - method, readSecret = domain.AuthMethodAPIKeyHeader, readAPIKeyCredential + source, err := siteCredentialSourceFor(descriptor, *cookieStdin, *apiKeyStdin) + if err != nil { + return err } - if !descriptor.SupportsAuth(method) { - return usageError("site %q does not support %s authentication", descriptor.ID, method) + readSecret := readCredential + if source.method == domain.AuthMethodAPIKeyHeader { + readSecret = readAPIKeyCredential } reader, ok := adapter.(site.TorrentDetailReader) if !ok { @@ -90,13 +88,16 @@ func (a *app) siteDetail(args []string) error { if err := reader.ValidateTorrentDetailRef(ref); err != nil { return usageError("site detail remote reference is invalid") } + if err := source.locateSaved(descriptor.ID); err != nil { + return err + } limits := site.DefaultTorrentDetailLimits() report := newSiteDetailReport(ref, config, limits) - credential, err := readSecret(a.stdin) + credential, err := a.readSiteCredential(source, readSecret) if err != nil { report.Blockers = append(report.Blockers, siteDetailFinding{Code: "credential.unavailable", Message: "the site credential could not be read"}) - return a.finishSiteDetail(*output, report, fmt.Errorf("read site credential failed")) + return a.finishSiteDetail(*output, report, siteCredentialReadError(source, err)) } ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) defer cancel() diff --git a/internal/cli/site_login.go b/internal/cli/site_login.go index be94d8b..6078efe 100644 --- a/internal/cli/site_login.go +++ b/internal/cli/site_login.go @@ -23,35 +23,50 @@ const siteLoginTimeout = 45 * time.Second const siteLoginHelp = `Usage: pt site login [--cookie-file PATH] [--session-days N] [--output table|json] SITE pt site login --credential-bundle-stdin [--cookie-file PATH] [--session-days N] [--output table|json] SITE + pt site login (--cookie-stdin | --api-key-stdin) [--output table|json] SITE -Signs in to SITE with the account password and saves a new session cookie for -the --cookie-stdin commands. Sites that list the auth.login_effectful -capability support it; see 'pt site capabilities SITE'. +Signs in to SITE once, so the site commands work without a credential flag. +After it, for example: + pt site status SITE + pt site search SITE QUERY +Each site command uses the saved credential unless --cookie-stdin or +--api-key-stdin pipes one in; an explicit flag always wins. 'pt site logout +SITE' deletes the saved credential. -By default the command prompts on this terminal for the username, the -password, and the two-step code (press Enter if the account has none). The -password and code are not shown as you type. It sends one login request, then -one read that confirms the new session, and never retries. The cookie is saved, -readable only by you, to +Sites that list the auth.login_effectful capability (TJUPT) sign in with the +account password. By default the command prompts on this terminal for the +username, the password, and the two-step code (press Enter if the account has +none). The password and code are not shown as you type. It sends one login +request, then one read that confirms the new session, and never retries. The +session cookie is saved, readable only by you, to /ptctl/sessions/SITE.cookie -and the exact path is printed. Nothing reads that file automatically; pass it -on stdin, for example: - pt site status --cookie-stdin SITE < PATH +and the exact path is printed. The password itself is never saved. + +Sites without a password login (M-Team) prompt for their API key instead, with +echo off, check it with one session read, and save it, readable only by you, +to + /ptctl/sessions/SITE.api-key +The same works for a session cookie you already have, with --cookie-stdin. +The saved file holds the credential in plain text; anyone who can read your +account's files can use it. Failed logins count toward the site's lockout (TJUPT blocks the IP after ten), so never run login in a loop. Flags: --cookie-file PATH - Save the cookie to PATH instead. PATH is replaced atomically and is - readable only by you; its directory must already exist. + Password login only: save the cookie to PATH instead. PATH is replaced + atomically and is readable only by you; its directory must already + exist. Site commands do not read PATH by themselves; pipe it with + --cookie-stdin. --session-days N - Session length in days, one the site offers; an invalid value lists them. - The default is the site's own default (TJUPT: 7). + Password login only: session length in days, one the site offers; an + invalid value lists them. The default is the site's own default + (TJUPT: 7). --output table|json json prints a site.login report on stdout with site_id, username, - session_days, session_expires_at, cookie_file, and requests_attempted. - It never contains the cookie. + session_days, session_expires_at, cookie_file or api_key_file, and + requests_attempted. It never contains the credential. --credential-bundle-stdin For scripts and agents: read the credentials from stdin as one strict JSON object instead of prompting: @@ -61,40 +76,52 @@ Flags: terminal on stdin is refused. Without --cookie-file the cookie, and nothing else, is written to stdout, which must be a pipe or an owner-only file, and --output json is refused. + --cookie-stdin, --api-key-stdin + For scripts and agents: read the session cookie or API key to save from + stdin instead of prompting. A terminal on stdin is refused. -Agent example, with no secret in any argv: +Agent examples, with no secret in any argv: jq -n --arg user "$SITE_USER" --rawfile password "$PASSWORD_FILE" \ --rawfile totp <(op item get "$OP_ITEM" --otp) \ '{schema: "ptctl.credentials/v1", site_username: $user, site_password: ($password | rtrimstr("\n")), site_totp: ($totp | rtrimstr("\n"))}' | pt site login --credential-bundle-stdin --cookie-file "$COOKIE_FILE" --output json tjupt + pt site login --api-key-stdin --output json mteam < "$API_KEY_FILE" Exit status: - 0 Logged in. Text output reports the account, the expiry, and the cookie + 0 Logged in. Text output reports the account, the expiry, and the saved file on stderr. 1 "site login stopped: REASON", where REASON is one of - login_credentials_rejected the site refused the username or password + login_credentials_rejected the site refused the username or password, + or the cookie or API key to save login_two_factor_required the account needs a two-step code login_two_factor_rejected the code was wrong or expired login_response_unrecognized the site answered with an unknown page - login_session_unverified the new cookie did not show the same account + login_session_unverified the new cookie did not show the same + account, or the site's answer did not + confirm the cookie or API key to save login_request_failed the request failed; the site may still have counted the attempt The line may end with "(the site reports N login attempts left before it blocks this IP)". Other failures print "site login failed" with an - optional ": CAUSE". + optional ": CAUSE". Nothing is saved after a failure. 2 Usage error. Nothing was read or sent. ` // siteLoginReport is the --output json result of a verified login. It says // where the session cookie went and never contains the cookie itself. +// A password login always has a session length and, in json mode, a cookie +// file, so omitempty never drops either from its report. Saving an existing +// credential has no session length and names an api_key_file instead of a +// cookie_file for an API key. type siteLoginReport struct { SiteID string `json:"site_id"` Username string `json:"username"` - SessionDays int `json:"session_days"` + SessionDays int `json:"session_days,omitempty"` SessionExpiresAt *time.Time `json:"session_expires_at,omitempty"` - CookieFile string `json:"cookie_file"` + CookieFile string `json:"cookie_file,omitempty"` + APIKeyFile string `json:"api_key_file,omitempty"` RequestsAttempted int `json:"requests_attempted"` } @@ -106,6 +133,8 @@ type siteLoginReport struct { 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 instead of prompting") + cookieStdin := fs.Bool("cookie-stdin", false, "save a Cookie header value read from stdin, after one verifying read, instead of signing in with the password") + apiKeyStdin := fs.Bool("api-key-stdin", false, "save a site-issued API key read from stdin, after one verifying read, instead of prompting for it") cookieFile := fs.String("cookie-file", "", "save the session cookie to this owner-only file") sessionDays := fs.Int("session-days", 0, "session length in days; must be one the site offers (default: the site's default)") output := fs.String("output", "table", "table or json") @@ -122,6 +151,9 @@ func (a *app) siteLogin(args []string) error { if err := validateOutput(*output); err != nil { return err } + if countTrue(*bundleStdin, *cookieStdin, *apiKeyStdin) > 1 { + return usageError("site login accepts only one of --credential-bundle-stdin, --cookie-stdin, and --api-key-stdin") + } if *bundleStdin && *cookieFile == "" && *output == "json" { return usageError("--output json needs --cookie-file, because --credential-bundle-stdin otherwise writes the session cookie to stdout") } @@ -130,6 +162,12 @@ func (a *app) siteLogin(args []string) error { return usageError("unknown site %q", fs.Arg(0)) } descriptor := adapter.Descriptor() + if *cookieStdin || *apiKeyStdin || (!*bundleStdin && !descriptor.Supports(domain.CapabilityLogin)) { + if *cookieFile != "" || *sessionDays != 0 { + return usageError("--cookie-file and --session-days apply only to a password login") + } + return a.siteSaveCredential(adapter, descriptor, *cookieStdin, *apiKeyStdin, *output) + } if !descriptor.Supports(domain.CapabilityLogin) { return usageError("site %q does not declare capability %q", descriptor.ID, domain.CapabilityLogin) } @@ -213,13 +251,130 @@ func (a *app) siteLogin(args []string) error { } 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) - if pending != nil { + if pending != nil && defaultDestination { + fmt.Fprintf(a.stderr, "session cookie saved to %s (owner-only)\nsite commands now use it when no --cookie-stdin is given, for example: ptctl site status %s\n", + terminalSafe(destination), terminalSafe(descriptor.ID)) + } else if pending != nil { fmt.Fprintf(a.stderr, "session cookie saved to %s (owner-only)\nuse it with: %s\n", terminalSafe(destination), terminalSafe(cookieUseHint(descriptor.ID, destination))) } return nil } +// siteSaveCredential verifies a cookie or API key the user already has with +// one session read, then saves it where site commands find it. It prompts on +// the terminal with echo off unless --cookie-stdin or --api-key-stdin pipes +// the credential in. +func (a *app) siteSaveCredential(adapter site.Adapter, descriptor domain.SiteDescriptor, cookieStdin, apiKeyStdin bool, output string) error { + source, err := siteCredentialSourceFor(descriptor, cookieStdin, apiKeyStdin) + if err != nil { + return err + } + label, flagName := savedCredentialLabel(source.method), credentialStdinFlag(source.method) + if !descriptor.Supports(domain.CapabilityAuthCheck) { + return usageError("site %q cannot verify a saved credential because it does not declare capability %q", descriptor.ID, domain.CapabilityAuthCheck) + } + checker, ok := adapter.(site.AuthChecker) + if !ok { + return fmt.Errorf("site %q declares %q but does not implement its typed port", descriptor.ID, domain.CapabilityAuthCheck) + } + prompt := !cookieStdin && !apiKeyStdin + var terminal promptTerminal + if prompt { + if terminal, ok = a.promptTerminal(); !ok { + return usageError("site login prompts on an interactive terminal; without one, pipe the %s with %s", label, flagName) + } + } + destination, err := savedCredentialPath(descriptor.ID, source.method) + if err == nil { + destination, err = filepath.Abs(destination) + } + if err != nil { + return usageError("no user config directory for the saved %s", label) + } + if info, err := os.Lstat(destination); err == nil && !info.Mode().IsRegular() { + return usageError("refusing to replace saved %s %s because it is not a regular file", label, destination) + } else if err != nil && !errors.Is(err, os.ErrNotExist) { + return usageError("inspect saved %s %s failed", label, destination) + } + + var credential site.Credential + if prompt { + fmt.Fprintf(a.stderr, "Saving the %s for %s; one read checks it first.\n", label, terminalSafe(descriptor.Name)) + question := "Cookie header value (hidden): " + if source.method == domain.AuthMethodAPIKeyHeader { + question = "API key (hidden): " + } + value, readErr := terminal.ReadSecret(func() { fmt.Fprint(a.stderr, question) }) + fmt.Fprintln(a.stderr) + if readErr != nil { + return loginPromptError(readErr) + } + value = strings.TrimSpace(value) + if source.method == domain.AuthMethodAPIKeyHeader { + credential, err = canonicalAPIKeyCredential([]byte(value)) + } else { + credential, err = canonicalCookieCredential([]byte(value)) + } + } else if source.method == domain.AuthMethodAPIKeyHeader { + credential, err = readEffectfulAPIKeyCredential(a.stdin) + } else { + credential, err = readEffectfulSiteCredential(a.stdin) + } + if err != nil { + return err + } + pending, err := prepareSessionCookieFile(destination, true) + if err != nil { + return err + } + defer pending.discard() + + ctx, cancel := context.WithTimeout(context.Background(), siteLoginTimeout) + defer cancel() + status, err := checker.CheckSession(ctx, credential) + if err != nil { + for _, cause := range []error{site.ErrCredentialMalformed, site.ErrCredentialRejected} { + if errors.Is(err, cause) { + return fmt.Errorf("site login failed: %v", cause) + } + } + return siteLoginPublicError(ctx, err) + } + switch status.State { + case domain.AuthenticationAuthenticated: + case domain.AuthenticationUnauthenticated: + return fmt.Errorf("site login stopped: %s", site.LoginCredentialsRejected) + default: + return fmt.Errorf("site login stopped: %s", site.LoginSessionUnverified) + } + if err := pending.commit(credential.SecretValue()); err != nil { + return err + } + if output == "json" { + report := siteLoginReport{SiteID: descriptor.ID, Username: status.Username, RequestsAttempted: 1} + if source.method == domain.AuthMethodAPIKeyHeader { + report.APIKeyFile = destination + } else { + report.CookieFile = destination + } + return writeJSON(a.stdout, report, nil) + } + fmt.Fprintf(a.stderr, "site login succeeded: site=%s username=%s requests=1\n%s saved to %s (owner-only)\nsite commands now use it when no %s is given, for example: ptctl site status %s\n", + terminalSafe(descriptor.ID), terminalSafe(status.Username), label, terminalSafe(destination), flagName, terminalSafe(descriptor.ID)) + return nil +} + +func countTrue(values ...bool) int { + count := 0 + for _, value := range values { + if value { + count++ + } + } + return count +} + // promptLoginCredentials asks for the username with echo, then for the // password and the optional one-time code with echo off. Prompts go to stderr. func (a *app) promptLoginCredentials(terminal promptTerminal, descriptor domain.SiteDescriptor) (site.LoginCredentials, error) { @@ -270,7 +425,7 @@ func checkSessionCookiePath(path string, explicit bool) (string, error) { info, err := os.Lstat(resolved) switch { case err == nil && !info.Mode().IsRegular(): - return "", fmt.Errorf("refusing to replace %s with a session cookie: it is not a regular file", resolved) + return "", fmt.Errorf("refusing to replace %s with a session cookie because it is not a regular file", resolved) case err != nil && !errors.Is(err, os.ErrNotExist): return "", fmt.Errorf("inspect session cookie file %s failed", resolved) } @@ -446,3 +601,83 @@ func knownLoginStopReason(reason string) bool { } return false } + +const siteLogoutHelp = `Usage: + pt site logout [--output table|json] SITE + +Deletes the session cookie or API key 'pt site login' saved for SITE, so site +commands stop using it. Nothing is sent to the site: a session cookie stays +valid on the site until it expires, and an API key stays valid until you +revoke it in the site's own settings. A file saved elsewhere with +--cookie-file is not touched. + +Exit status: + 0 The saved credential was deleted, or there was none. + 1 A saved credential path is not a regular file, or it could not be deleted. + 2 Usage error. Nothing was deleted. +` + +// siteLogoutReport is the --output json result of site logout. +type siteLogoutReport struct { + SiteID string `json:"site_id"` + RemovedFiles []string `json:"removed_files"` +} + +// siteLogout deletes the credentials 'site login' saved for one site. It +// never contacts the site. +func (a *app) siteLogout(args []string) error { + fs := newFlagSet("site logout") + output := fs.String("output", "table", "table or json") + if err := fs.Parse(args); err != nil { + if errors.Is(err, flag.ErrHelp) { + fmt.Fprint(a.stdout, siteLogoutHelp) + return nil + } + return usageError("site logout: %v", err) + } + if fs.NArg() != 1 { + return usageError("site logout requires exactly one SITE") + } + if err := validateOutput(*output); err != nil { + return err + } + adapter, ok := a.registry.Get(fs.Arg(0)) + if !ok { + return usageError("unknown site %q", fs.Arg(0)) + } + descriptor := adapter.Descriptor() + report := siteLogoutReport{SiteID: descriptor.ID, RemovedFiles: []string{}} + for _, method := range []domain.AuthMethod{domain.AuthMethodCookieHeader, domain.AuthMethodAPIKeyHeader} { + path, err := savedCredentialPath(descriptor.ID, method) + if err != nil { + return usageError("no user config directory for saved credentials") + } + info, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return fmt.Errorf("inspect saved %s %s failed", savedCredentialLabel(method), path) + } + // A symlink is deleted itself, never the file it points to. + if !info.Mode().IsRegular() && info.Mode()&os.ModeSymlink == 0 { + return fmt.Errorf("refusing to delete saved %s %s because it is not a regular file", savedCredentialLabel(method), path) + } + if err := os.Remove(path); err != nil { + return fmt.Errorf("delete saved %s %s failed", savedCredentialLabel(method), path) + } + report.RemovedFiles = append(report.RemovedFiles, path) + if *output != "json" { + fmt.Fprintf(a.stderr, "deleted saved %s %s\n", savedCredentialLabel(method), terminalSafe(path)) + } + } + if *output == "json" { + return writeJSON(a.stdout, report, nil) + } + if len(report.RemovedFiles) == 0 { + fmt.Fprintf(a.stderr, "no saved credential for site %s\n", terminalSafe(descriptor.ID)) + return nil + } + fmt.Fprintln(a.stderr, "nothing was sent to the site; a session cookie stays valid there until it expires, and an API key until you revoke it") + return nil +} diff --git a/internal/cli/site_login_test.go b/internal/cli/site_login_test.go index f451217..0d46d43 100644 --- a/internal/cli/site_login_test.go +++ b/internal/cli/site_login_test.go @@ -345,7 +345,7 @@ func TestSiteLoginPromptsByDefaultAndSavesTheCookieOwnerOnly(t *testing.T) { "Username: ", "Password (hidden): ", "Two-step code (hidden; press Enter if none): ", "site login succeeded: site=fakept username=CanaryUser session_expires=2026-10-22T15:04:33Z requests=2\n", "session cookie saved to " + cookiePath + " (owner-only)\n", - "use it with: ", + "site commands now use it when no --cookie-stdin is given, for example: ptctl site status fakept\n", } { if !strings.Contains(stderr, want) { t.Fatalf("stderr lacks %q: %q", want, stderr) diff --git a/internal/cli/site_metafile.go b/internal/cli/site_metafile.go index f3a5114..20e5e05 100644 --- a/internal/cli/site_metafile.go +++ b/internal/cli/site_metafile.go @@ -107,9 +107,6 @@ func (a *app) siteMetafileFetch(args []string) error { if *cookieStdin && *apiKeyStdin { return usageError("--cookie-stdin and --api-key-stdin are mutually exclusive") } - if !*cookieStdin && !*apiKeyStdin { - return usageError("%s is required; credentials are never accepted in argv", requiredCredentialFlag(a.registry, fs.Arg(0))) - } if !*acknowledge { return usageError("--acknowledge-site-effect is required because the GET may be recorded as a torrent download") } @@ -140,12 +137,13 @@ func (a *app) siteMetafileFetch(args []string) error { if !descriptor.Supports(domain.CapabilityMetafile) { return usageError("site %q does not declare capability %q", descriptor.ID, domain.CapabilityMetafile) } - method, readSecret := domain.AuthMethodCookieHeader, readEffectfulSiteCredential - if *apiKeyStdin { - method, readSecret = domain.AuthMethodAPIKeyHeader, readEffectfulAPIKeyCredential + source, err := siteCredentialSourceFor(descriptor, *cookieStdin, *apiKeyStdin) + if err != nil { + return err } - if !descriptor.SupportsAuth(method) { - return usageError("site %q does not support %s authentication", descriptor.ID, method) + readSecret := readEffectfulSiteCredential + if source.method == domain.AuthMethodAPIKeyHeader { + readSecret = readEffectfulAPIKeyCredential } fetcher, ok := adapter.(site.MetafileFetcher) if !ok { @@ -164,6 +162,9 @@ func (a *app) siteMetafileFetch(args []string) error { if err := fetcher.ValidateMetafileRef(ref); err != nil { return usageError("site metafile fetch: invalid SITE/REMOTE_ID") } + if err := source.locateSaved(descriptor.ID); err != nil { + return err + } report := newSiteMetafileFetchReport(ref, config, fetchLimits, storeLimits, *showAbsolute, *storeRoot) store, err := metastore.Open(*storeRoot) @@ -175,11 +176,11 @@ func (a *app) siteMetafileFetch(args []string) error { } report.StoreOperation.Store = storeSummary(store.Info(), *showAbsolute) - credential, err := readSecret(a.stdin) + credential, err := a.readSiteCredential(source, readSecret) if err != nil { report.Outcome = "blocked" report.Blockers = append(report.Blockers, "credential.read_failed") - return a.finishSiteMetafileFetch(*output, report, fmt.Errorf("read site credential failed")) + return a.finishSiteMetafileFetch(*output, report, siteCredentialReadError(source, err)) } ctx, cancel := context.WithTimeout(context.Background(), *timeout) defer cancel() @@ -333,7 +334,7 @@ func (a *app) siteMetafileFetch(args []string) error { func (a *app) siteMetafileFetchHelp() { fmt.Fprint(a.stdout, `Usage: - ptctl site metafile fetch (--cookie-stdin | --api-key-stdin) --acknowledge-site-effect --metafile-store DIR [flags] SITE REMOTE_ID + ptctl site metafile fetch [--cookie-stdin | --api-key-stdin] --acknowledge-site-effect --metafile-store DIR [flags] SITE REMOTE_ID This command performs one explicitly acknowledged, effectful torrent-metafile GET and imports the exact bounded response into an initialized private metafile store. @@ -348,9 +349,10 @@ link, then GETs it; one redirect is followed only to the site's own HTTPS hosts, and the link is never printed or stored. Each link request may count as a download on the site, and is reported as a link request. -Credentials (stdin only, one line): +Credentials: the one 'ptctl site login SITE' saved, or one line on stdin: --cookie-stdin session Cookie header value (tjupt) --api-key-stdin site-issued API key (mteam) +A saved credential never stands in for --acknowledge-site-effect. Flags: --acknowledge-site-effect acknowledge that the GET may count as a download diff --git a/internal/cli/site_metafile_test.go b/internal/cli/site_metafile_test.go index 72b26cf..66a2f1e 100644 --- a/internal/cli/site_metafile_test.go +++ b/internal/cli/site_metafile_test.go @@ -515,9 +515,9 @@ func TestSiteMetafileFetchNamesAndChecksTheCredentialFlagBeforeReadingIt(t *test args []string want string }{ - {adapter: &fakeMetafileFetchAdapter{linked: true}, args: []string{"fakept", "42"}, want: "--api-key-stdin is required; credentials are never accepted in argv"}, + {adapter: &fakeMetafileFetchAdapter{linked: true}, args: []string{"fakept", "42"}, want: "no saved API key for site \"fakept\"; run 'ptctl site login fakept' first, or pipe one with --api-key-stdin"}, {adapter: &fakeMetafileFetchAdapter{linked: true}, args: []string{"--cookie-stdin", "fakept", "42"}, want: `site "fakept" does not support cookie_header authentication`}, - {adapter: &fakeMetafileFetchAdapter{}, args: []string{"fakept", "42"}, want: "--cookie-stdin is required; credentials are never accepted in argv"}, + {adapter: &fakeMetafileFetchAdapter{}, args: []string{"fakept", "42"}, want: "no saved session cookie for site \"fakept\"; run 'ptctl site login fakept' first, or pipe one with --cookie-stdin"}, {adapter: &fakeMetafileFetchAdapter{}, args: []string{"--api-key-stdin", "fakept", "42"}, want: `site "fakept" does not support api_key_header authentication`}, {adapter: &fakeMetafileFetchAdapter{}, args: []string{"--cookie-stdin", "--api-key-stdin", "fakept", "42"}, want: "--cookie-stdin and --api-key-stdin are mutually exclusive"}, } { @@ -531,8 +531,8 @@ func TestSiteMetafileFetchNamesAndChecksTheCredentialFlagBeforeReadingIt(t *test args []string want string }{ - {args: []string{"mteam", "1"}, want: "--api-key-stdin is required; credentials are never accepted in argv"}, - {args: []string{"tjupt", "1"}, want: "--cookie-stdin is required; credentials are never accepted in argv"}, + {args: []string{"mteam", "1"}, want: "no saved API key for site \"mteam\"; run 'ptctl site login mteam' first, or pipe one with --api-key-stdin"}, + {args: []string{"tjupt", "1"}, want: "no saved session cookie for site \"tjupt\"; run 'ptctl site login tjupt' first, or pipe one with --cookie-stdin"}, {args: []string{"--api-key-stdin", "tjupt", "1"}, want: `site "tjupt" does not support api_key_header authentication`}, {args: []string{"--cookie-stdin", "mteam", "1"}, want: `site "mteam" does not support cookie_header authentication`}, } {