diff --git a/README.md b/README.md index 3c57618..9c2f1cb 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ The complete inventory, including what is deliberately not implemented, is in |---|---|---| | Zero-write | `torrent inspect/verify`, `storage probe/map`, `seed discover/plan`, `client status/list`, ordinary `site` reads and `site bonus review`, `reconcile report`, and every `plan`, `status`, `list`, and `inspect` subcommand | None. Reads can still update atime, hydrate offline placeholders, or be recorded by the remote side. | | Private store | `metafile store init/import`, `storage profile create`, `storage index refresh/refresh-discover`, `reconcile refresh-report`, `site bonus exchange prepare` | The explicit command itself. Owner-only and no-clobber; not encrypted. | -| Tracker-visible | `site metafile fetch` (one GET), `site bonus exchange submit` (at most one POST), `site login` (one POST and one verifying GET) | `--acknowledge-site-effect`, `--acknowledge-bonus-exchange`; `site login` is the command itself, with the cookie written only to a pipe or owner-only file | +| Tracker-visible | `site metafile fetch` (one GET), `site bonus exchange submit` (at most one POST), `site login` (one POST and one verifying GET) | `--acknowledge-site-effect`, `--acknowledge-bonus-exchange`; `site login` is the command itself, with the cookie saved only to an owner-only file or a pipe | | 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` | @@ -130,8 +130,10 @@ stdin; interactive TTY input is refused, and the cookie is never persisted: printf '%s' "$TJUPT_COOKIE" | ptctl site status --cookie-stdin tjupt ``` -For TJUPT, `site login --credential-bundle-stdin tjupt` can issue that cookie -from the account password and two-step code instead; see +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, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 455555e..21aa8d6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -356,10 +356,12 @@ Capabilities are small and explicit: - `auth.login_effectful` `auth.login_effectful` (`site.SessionLoginer`) signs in with an account -password and optional one-time code, read from one stdin bundle, and returns a -verified cookie credential that ptctl writes only to a non-terminal stdout and -never stores. It sends one login request and at most one verifying read, never -retries, and reports a refusal only by a fixed stop reason. +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. Site-specific form or action writes live under narrow namespaced typed ports and durable action schemas. They are not forced into universal fields. The effectful diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index b80652f..9cdc397 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -51,6 +51,7 @@ Every JSON result is a single object on stdout, indented with two spaces: |---|---| | General | `version` | | Site reads | `site.descriptor.list` (`site list`, `site capabilities`), `site.session`, `site.account`, `site.torrent.list`, `site.torrent.detail`, `site.bonus.catalog`, `site.bonus.offer_review` | +| Site login | `site.login` | | Bonus exchange | `site.bonus.exchange.prepare`, `site.bonus.exchange.submit`, `site.bonus.exchange.status`, `site.bonus.exchange.operation_list`, `site.bonus.exchange.prune`, `site.bonus.exchange.forget` | | Site metafiles | `site.metafile.fetch`, `site.metafile.binding.list`, `site.metafile.binding.inspect` | | Metafiles | `metafile.manifest` (`torrent inspect`), `content.verification` (`torrent verify`), `metafile.store.init`, `metafile.store.import`, `metafile.store.inspect` | @@ -104,15 +105,22 @@ Per-command details are in | `--credential-bundle-stdin` | `site bonus exchange submit` for sites that confirm with the account password (TJUPT) | `{"schema":"ptctl.credentials/v1","site_cookie":"...","site_password":"..."}` | | `--credential-bundle-stdin` | `site login` | `{"schema":"ptctl.credentials/v1","site_username":"...","site_password":"...","site_totp":"123456"}`; `site_totp` is optional | -- An interactive terminal on stdin is refused; the secret must be piped. +- 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. - 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: - it is written to stdout, which must be a pipe or an owner-only file, so the - caller decides where it is kept. + 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. - `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. diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 934004c..6d8700e 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -96,11 +96,13 @@ deliberately does not. For step-by-step usage, see the - an explicitly acknowledged TJUPT metafile fetch for one remote ID, using one bounded GET with no redirect or retry and publishing the strictly validated exact response only into an initialized private metafile store; -- TJUPT password login with an optional six-digit two-step code from one strict - stdin bundle: one non-retried login POST, recognized refusal pages reported - as fixed stop reasons with the site's remaining-attempts count, and one - verifying read that must name the same account before the new session cookie - is written to a pipe or owner-only stdout; +- TJUPT password login with an optional six-digit two-step code, typed at + hidden terminal prompts by default or passed as one strict stdin bundle by + scripts and agents: one non-retried login POST, recognized refusal pages + reported as fixed stop reasons with the site's remaining-attempts count, and + one verifying read that must name the same account before the new session + cookie is saved to an owner-only file or written to a pipe or owner-only + stdout, with an optional `site.login` JSON report; - an experimental M-Team session check, account snapshot (username, uploaded and downloaded bytes, ratio, and bonus), and first-page torrent search with seeders, leechers, and promotion factors, through one read-only POST per diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index ee9500b..7a2f30d 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -129,8 +129,16 @@ the site issued a session cookie. Because TJUPT blocks the client IP after ten failed logins, a failed or ambiguous login is never retried, the site's own remaining-attempts count is surfaced when its page states one, and the two-step page, which echoes the password in a hidden field, is cleared after -classification. The issued cookie is written only to a pipe or an owner-only -stdout file and is kept only after the verifying read names the same account. +classification. The issued cookie is kept only after the verifying read names +the same account. It is then renamed into place from an owner-only temporary +file created before the login request, so an unwritable destination never +costs an attempt and a failed login leaves an earlier cookie file untouched. +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`. The M-Team adapter sends at most one bounded POST per command to one of two read-only JSON API endpoints (`member/profile` and `torrent/search`), with a non-replayable body of at most 16 KiB, and never retries. HTTP 429 is terminal. There is no cross-process limiter in the alpha, so @@ -1501,7 +1509,8 @@ upgrade storage, client, path, or private-variant proof. ### Supply chain The runtime uses the Go standard library plus `golang.org/x/sys` for audited -OS-specific filesystem security primitives. GitHub Actions are pinned to full +OS-specific filesystem security primitives and echo-off terminal input, and +`golang.org/x/net/html` for site page parsing. GitHub Actions are pinned to full commit SHAs and receive read-only repository permission. Tests construct synthetic metafiles; real tracker artifacts are forbidden. diff --git a/docs/TJUPT_ADAPTER.md b/docs/TJUPT_ADAPTER.md index bdc78a4..16da662 100644 --- a/docs/TJUPT_ADAPTER.md +++ b/docs/TJUPT_ADAPTER.md @@ -264,12 +264,13 @@ response details do not cross the CLI boundary. ### Login -`site login --credential-bundle-stdin tjupt` implements -`auth.login_effectful`, declared only on the default origin. Usage, the -session length, and stdout safety are checked before stdin is read; the bundle -then carries `site_username`, `site_password`, and an optional `site_totp`, -which TJUPT requires to be exactly six digits. Command usage, output, and stop -reasons are in the [sites guide](guide/sites.md). +`site login tjupt` implements `auth.login_effectful`, declared only on the +default origin. Usage, the session length, and the cookie destination are +checked before the command prompts on the terminal or, with +`--credential-bundle-stdin`, reads stdin. Either way the credentials are a +username, a password, and an optional two-step code, which TJUPT requires to +be exactly six digits. Command usage, output, and stop reasons are in the +[sites guide](guide/sites.md) and `ptctl help login`. TJUPT's `login.php` posts `username`, `password`, and `logout` (the session length in days: 1, 7, 14, 30, or 90) to `takelogin.php`. An account with @@ -304,7 +305,9 @@ TJUPT blocks the client IP after ten failed logins, so a failed login is never retried. In October 2026 a login without a code returned the two-step page with all ten attempts still offered, and a login with a code from a password manager issued a seven-day `access_token` in two requests that `site status` -and `site account` then accepted. +and `site account` then accepted. The interactive default did the same on a +terminal: neither hidden answer appeared in the terminal output, and +`site status` accepted the cookie file it saved. ## Fixtures diff --git a/docs/guide/sites.md b/docs/guide/sites.md index 32b5245..b846132 100644 --- a/docs/guide/sites.md +++ b/docs/guide/sites.md @@ -35,33 +35,73 @@ seeders, leechers, snatches, and promotion when the results table has its usual shape; otherwise a result keeps only its name and size. Instead of copying the cookie out of a browser, `site login` can sign in with -the account password and write a new session cookie for the commands above. -It takes one strict `ptctl.credentials/v1` bundle on stdin with -`site_username`, `site_password`, and, for an account with two-step -verification, the current one-time code in `site_totp`. Stdout must be a pipe -or an owner-only file: the command refuses a terminal, a device, or a file -other users can read. One way to build the bundle without putting a secret in -argv, here with the 1Password CLI supplying the code: +the account password and save a new session cookie for the commands above. +Run it in a terminal and answer the prompts: + +```console +$ ptctl site login tjupt +Signing in to TJUPT / 北洋园PT with one login request; failed logins count toward the site's lockout. +Username: alice +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' +``` + +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. + +Scripts and agents pass the credentials instead with `--credential-bundle-stdin`, +as one strict `ptctl.credentials/v1` bundle on stdin: `site_username`, +`site_password`, and, for an account with two-step verification, the current +one-time code in `site_totp`. A terminal on stdin is then refused. With +`--cookie-file` the cookie goes to that file and `--output json` reports a +`site.login` object, without the cookie, on stdout. Without `--cookie-file` the +cookie line and nothing else goes to stdout, which must be a pipe or an +owner-only file, and `--output json` is refused. One way to build the bundle +without putting a secret in argv, here with the 1Password CLI supplying the +code: ```bash -(umask 077 - jq -n --arg user "$TJUPT_USER" \ - --rawfile password "$PASSWORD_FILE" \ - --rawfile totp <(op item get "$TJUPT_ITEM" --otp) \ - '{schema: "ptctl.credentials/v1", - site_username: $user, - site_password: ($password | rtrimstr("\n")), - site_totp: ($totp | rtrimstr("\n"))}' | \ - ptctl site login --credential-bundle-stdin tjupt > "$COOKIE_FILE") +jq -n --arg user "$TJUPT_USER" \ + --rawfile password "$PASSWORD_FILE" \ + --rawfile totp <(op item get "$TJUPT_ITEM" --otp) \ + '{schema: "ptctl.credentials/v1", + site_username: $user, + site_password: ($password | rtrimstr("\n")), + site_totp: ($totp | rtrimstr("\n"))}' | \ + ptctl site login --credential-bundle-stdin --cookie-file "$COOKIE_FILE" --output json tjupt ptctl site status --cookie-stdin tjupt < "$COOKIE_FILE" ``` -Leave out `site_totp` when the account has no two-step verification. -`--session-days` picks the session length the site offers (TJUPT: 1, 7, 14, 30, -or 90; default 7). On success, stdout holds only the cookie line and stderr -reports `site login succeeded: site=tjupt username=... session_expires=... -requests=2`. +```json +{ + "schema": "ptctl.dev/v1", + "kind": "site.login", + "data": { + "site_id": "tjupt", + "username": "alice", + "session_days": 7, + "session_expires_at": "2026-10-23T08:00:00Z", + "cookie_file": "/home/alice/tjupt.cookie", + "requests_attempted": 2 + } +} +``` + +Leave out `site_totp` when the account has no two-step verification. In text +mode, stderr reports `site login succeeded: site=tjupt username=... +session_expires=... requests=2` and, with a cookie file, where it was saved. Login sends one POST and never retries. If the site issues a session cookie, ptctl waits two seconds and makes one read with it, and keeps the cookie only @@ -71,7 +111,7 @@ if that read shows the same signed-in account. Otherwise it exits `1` with | Reason | Meaning | |---|---| | `login_credentials_rejected` | The site refused the username or password. | -| `login_two_factor_required` | The account needs a one-time code and the bundle had none. | +| `login_two_factor_required` | The account needs a one-time code and none was given. | | `login_two_factor_rejected` | The one-time code was wrong or expired. | | `login_response_unrecognized` | The site answered with a page ptctl does not recognize. | | `login_session_unverified` | A cookie was issued, but the verifying read did not show the same signed-in account. The cookie is discarded. | @@ -80,7 +120,8 @@ if that read shows the same signed-in account. Otherwise it exits `1` with TJUPT blocks the client IP after ten failed logins. When the page states how many attempts are left, the error line ends with `(the site reports N login attempts left before it blocks this IP)`. Fix the input before trying again, -and never loop `site login`. Usage errors exit `2` before stdin is read. +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`, and diff --git a/internal/cli/help.go b/internal/cli/help.go index bb6f6d3..f9913ed 100644 --- a/internal/cli/help.go +++ b/internal/cli/help.go @@ -19,7 +19,10 @@ func (a *app) helpTopic(args []string) error { fmt.Fprint(a.stdout, `Configuration (explicit inputs; no automatic discovery) pt cli does not search your home/project directories for configuration or credentials. -There is no --config file or saved downloader-login profile. +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'). Downloader reads: --driver qbittorrent|transmission (default: qbittorrent) @@ -72,6 +75,8 @@ report is read-only. The separate refresh-report command writes a storage-index Details: pt help reconcile report | pt help config `) + case "login", "site login": + fmt.Fprint(a.stdout, siteLoginHelp) case "version": return a.version([]string{"--help"}) case "torrent inspect": @@ -85,7 +90,7 @@ Details: pt help reconcile report | pt help config case "reconcile report": return a.reconcileCommand([]string{"report", "--help"}) default: - return usageError("unknown help topic; use torrent, client, reconcile, config, version, or 'pt help' for the complete command list") + return usageError("unknown help topic; use torrent, client, reconcile, login, config, version, or 'pt help' for the complete command list") } return nil } diff --git a/internal/cli/output.go b/internal/cli/output.go index 68bacde..f45dbc6 100644 --- a/internal/cli/output.go +++ b/internal/cli/output.go @@ -57,6 +57,8 @@ func jsonKind(data any) string { return typed.kind case domain.BonusCatalog: return "site.bonus.catalog" + case siteLoginReport: + return "site.login" case *metafile.MetaInfo: return "metafile.manifest" case metafileStoreReport: diff --git a/internal/cli/run.go b/internal/cli/run.go index 348d7f2..61fc90a 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -27,6 +27,8 @@ type app struct { stderr io.Writer registry *site.Registry refreshDiscovery refreshDiscoveryFunc + // terminal replaces stdinTerminal in tests. + terminal func(io.Reader) (promptTerminal, bool) } type refreshDiscoveryFunc func( @@ -131,7 +133,8 @@ are supplied. See docs/READ_ONLY_QUICKSTART.md for the short read-only guide. Usage: ptctl site list [--output table|json] ptctl site capabilities [--output table|json] [SITE] - ptctl site login --credential-bundle-stdin [--session-days N] SITE + ptctl site 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... @@ -218,8 +221,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. - * Site login reads the account password and optional one-time code only from stdin, sends one login request plus one verifying read, never retries, and writes the new session cookie only to a non-terminal stdout. + * 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'. * .torrent tracker URLs are reduced to origins; passkeys are never printed. * The metafile store preserves exact private bytes with owner-only access and atomic no-clobber commits. * v1, v2, and hybrid verification use exact content proofs; names and sizes are not proof. diff --git a/internal/cli/site_login.go b/internal/cli/site_login.go index bddf559..be94d8b 100644 --- a/internal/cli/site_login.go +++ b/internal/cli/site_login.go @@ -3,9 +3,11 @@ package cli import ( "context" "errors" + "flag" "fmt" "io" "os" + "path/filepath" "runtime" "strconv" "strings" @@ -18,22 +20,110 @@ import ( const siteLoginTimeout = 45 * time.Second -// siteLogin signs in with an account password from stdin and writes the new -// session cookie, and nothing else, to stdout, so it can be redirected into a -// private file that later --cookie-stdin commands read. Everything a person -// needs to see goes to stderr. +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 + +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'. + +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 + /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 + +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. + --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). + --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. + --credential-bundle-stdin + For scripts and agents: read the credentials from stdin as one strict + JSON object instead of prompting: + {"schema":"ptctl.credentials/v1","site_username":"...", + "site_password":"...","site_totp":"123456"} + Leave out site_totp when the account has no two-step verification. A + 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. + +Agent example, 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 + +Exit status: + 0 Logged in. Text output reports the account, the expiry, and the cookie + file on stderr. + 1 "site login stopped: REASON", where REASON is one of + login_credentials_rejected the site refused the username or password + 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_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". + 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. +type siteLoginReport struct { + SiteID string `json:"site_id"` + Username string `json:"username"` + SessionDays int `json:"session_days"` + SessionExpiresAt *time.Time `json:"session_expires_at,omitempty"` + CookieFile string `json:"cookie_file"` + RequestsAttempted int `json:"requests_attempted"` +} + +// siteLogin signs in with an account password and saves the new session +// cookie. By default it prompts on the terminal and saves the cookie to an +// owner-only file. --credential-bundle-stdin reads the credentials from stdin +// instead and, without --cookie-file, writes the cookie and nothing else to +// stdout, so it can be piped. Everything a person needs to see goes to stderr. func (a *app) siteLogin(args []string) error { fs := newFlagSet("site login") - bundleStdin := fs.Bool("credential-bundle-stdin", false, "read a ptctl.credentials/v1 bundle with site_username, site_password, and optional site_totp from stdin") + 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") + 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") if err := fs.Parse(args); err != nil { + if errors.Is(err, flag.ErrHelp) { + fmt.Fprint(a.stdout, siteLoginHelp) + return nil + } return usageError("site login: %v", err) } if fs.NArg() != 1 { return usageError("site login requires exactly one SITE") } - if !*bundleStdin { - return usageError("--credential-bundle-stdin is required; credentials are never accepted in argv") + if err := validateOutput(*output); err != nil { + return err + } + if *bundleStdin && *cookieFile == "" && *output == "json" { + return usageError("--output json needs --cookie-file, because --credential-bundle-stdin otherwise writes the session cookie to stdout") } adapter, ok := a.registry.Get(fs.Arg(0)) if !ok { @@ -55,13 +145,46 @@ func (a *app) siteLogin(args []string) error { if !config.Allows(days) { return usageError("--session-days must be one of %s for site %q", joinDays(config.SessionDays), descriptor.ID) } - if err := rejectUnsafeCookieOutput(a.stdout); err != nil { + var terminal promptTerminal + if !*bundleStdin { + if terminal, ok = a.promptTerminal(); !ok { + return usageError("site login prompts on an interactive terminal; without one, pipe the credentials with --credential-bundle-stdin (see 'pt help login')") + } + } + destination, defaultDestination := *cookieFile, false + if destination == "" && !*bundleStdin { + dir, err := os.UserConfigDir() + if err != nil { + return usageError("no user config directory for the session cookie; pass --cookie-file PATH") + } + destination, defaultDestination = filepath.Join(dir, "ptctl", "sessions", descriptor.ID+".cookie"), true + } + if destination != "" { + var err error + if destination, err = checkSessionCookiePath(destination, !defaultDestination); err != nil { + return usageError("%v", err) + } + } else if err := rejectUnsafeCookieOutput(a.stdout); err != nil { return usageError("%v", err) } - credentials, err := readLoginCredentialBundle(a.stdin) + + var credentials site.LoginCredentials + var err error + if *bundleStdin { + credentials, err = readLoginCredentialBundle(a.stdin) + } else { + credentials, err = a.promptLoginCredentials(terminal, descriptor) + } if err != nil { return err } + var pending *pendingCookieFile + if destination != "" { + if pending, err = prepareSessionCookieFile(destination, defaultDestination); err != nil { + return err + } + defer pending.discard() + } ctx, cancel := context.WithTimeout(context.Background(), siteLoginTimeout) defer cancel() @@ -69,8 +192,20 @@ func (a *app) siteLogin(args []string) error { if err != nil { return siteLoginPublicError(ctx, err) } - if _, err := io.WriteString(a.stdout, result.Session.SecretValue()+"\n"); err != nil { - return fmt.Errorf("write site session cookie to stdout failed") + if pending == nil { + if _, err := io.WriteString(a.stdout, result.Session.SecretValue()+"\n"); err != nil { + return fmt.Errorf("write site session cookie to stdout failed") + } + } else if err := pending.commit(result.Session.SecretValue()); err != nil { + return err + } + if *output == "json" { + report := siteLoginReport{SiteID: descriptor.ID, Username: result.Username, SessionDays: days, CookieFile: destination, RequestsAttempted: result.RequestsAttempted} + if result.ExpiresAt != nil { + expires := result.ExpiresAt.UTC() + report.SessionExpiresAt = &expires + } + return writeJSON(a.stdout, report, nil) } expires := "unknown" if result.ExpiresAt != nil { @@ -78,9 +213,138 @@ 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 { + 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 } +// 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) { + fmt.Fprintf(a.stderr, "Signing in to %s with one login request; failed logins count toward the site's lockout.\n", terminalSafe(descriptor.Name)) + fmt.Fprint(a.stderr, "Username: ") + username, err := terminal.ReadLine() + if err != nil { + return site.LoginCredentials{}, loginPromptError(err) + } + password, err := terminal.ReadSecret(func() { fmt.Fprint(a.stderr, "Password (hidden): ") }) + fmt.Fprintln(a.stderr) + if err != nil { + return site.LoginCredentials{}, loginPromptError(err) + } + code, err := terminal.ReadSecret(func() { fmt.Fprint(a.stderr, "Two-step code (hidden; press Enter if none): ") }) + fmt.Fprintln(a.stderr) + if err != nil { + return site.LoginCredentials{}, loginPromptError(err) + } + accountPassword, err := site.NewAccountPassword(password) + if err != nil { + return site.LoginCredentials{}, fmt.Errorf("site login account password is invalid") + } + // Authenticator apps often show a code as "123 456". + code = strings.Join(strings.Fields(code), "") + credentials, err := site.NewLoginCredentials(strings.TrimSpace(username), accountPassword, code) + if err != nil { + return site.LoginCredentials{}, fmt.Errorf("site %v", err) + } + return credentials, nil +} + +func loginPromptError(err error) error { + if errors.Is(err, io.EOF) { + return fmt.Errorf("site login canceled before anything was sent") + } + return fmt.Errorf("read site login input from the terminal failed") +} + +// checkSessionCookiePath resolves the cookie file path before anything is +// read or sent. It refuses an existing directory, symlink, or other +// non-regular file, and an explicit path whose directory does not exist. +func checkSessionCookiePath(path string, explicit bool) (string, error) { + resolved, err := filepath.Abs(path) + if err != nil { + return "", fmt.Errorf("--cookie-file path is invalid") + } + 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) + case err != nil && !errors.Is(err, os.ErrNotExist): + return "", fmt.Errorf("inspect session cookie file %s failed", resolved) + } + if explicit { + if parent, err := os.Stat(filepath.Dir(resolved)); err != nil || !parent.IsDir() { + return "", fmt.Errorf("--cookie-file directory %s does not exist", filepath.Dir(resolved)) + } + } + return resolved, nil +} + +// pendingCookieFile is an owner-only temporary file next to the cookie file. +// It is created before the login request, so an unwritable destination never +// costs a login attempt, and replaces the cookie file only after the login is +// verified. +type pendingCookieFile struct { + temp *os.File + path string +} + +func prepareSessionCookieFile(path string, createDir bool) (*pendingCookieFile, error) { + dir := filepath.Dir(path) + if createDir { + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, fmt.Errorf("create session cookie directory %s failed", dir) + } + } + // CreateTemp opens the file with mode 0600. + temp, err := os.CreateTemp(dir, ".ptctl-session-*.tmp") + if err != nil { + return nil, fmt.Errorf("create a session cookie file in %s failed", dir) + } + return &pendingCookieFile{temp: temp, path: path}, nil +} + +func (pending *pendingCookieFile) commit(cookie string) error { + name := pending.temp.Name() + _, err := io.WriteString(pending.temp, cookie+"\n") + if err == nil { + err = pending.temp.Sync() + } + if closeErr := pending.temp.Close(); err == nil { + err = closeErr + } + pending.temp = nil + if err == nil { + err = os.Rename(name, pending.path) + } + if err != nil { + _ = os.Remove(name) + return fmt.Errorf("save the session cookie to %s failed; the new session was not kept", pending.path) + } + return nil +} + +func (pending *pendingCookieFile) discard() { + if pending.temp == nil { + return + } + name := pending.temp.Name() + _ = pending.temp.Close() + _ = os.Remove(name) + pending.temp = nil +} + +// cookieUseHint is a follow-up command that reads the saved cookie, quoted +// for the platform's usual shell. +func cookieUseHint(siteID, path string) string { + if runtime.GOOS == "windows" { + return fmt.Sprintf(`Get-Content "%s" | ptctl site status --cookie-stdin %s`, path, siteID) + } + return fmt.Sprintf("ptctl site status --cookie-stdin %s < '%s'", siteID, strings.ReplaceAll(path, "'", `'\''`)) +} + func joinDays(days []int) string { parts := make([]string, len(days)) for i, day := range days { @@ -103,10 +367,10 @@ func rejectUnsafeCookieOutput(writer io.Writer) error { return fmt.Errorf("inspect session cookie output failed") } if info.Mode()&(os.ModeDevice|os.ModeCharDevice) != 0 { - return fmt.Errorf("refusing to write a session cookie to a terminal or device; redirect stdout to a private file or a pipe") + return fmt.Errorf("refusing to write a session cookie to a terminal or device; redirect stdout to a private file or a pipe, or use --cookie-file") } if runtime.GOOS != "windows" && info.Mode().IsRegular() && info.Mode().Perm()&0o077 != 0 { - return fmt.Errorf("refusing to write a session cookie to a file other users can access; create it with umask 077") + return fmt.Errorf("refusing to write a session cookie to a file other users can access; create it with umask 077, or use --cookie-file") } return nil } diff --git a/internal/cli/site_login_test.go b/internal/cli/site_login_test.go index 87c6280..f451217 100644 --- a/internal/cli/site_login_test.go +++ b/internal/cli/site_login_test.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "runtime" + "strconv" "strings" "testing" "time" @@ -244,3 +245,260 @@ func TestSiteLoginRefusesUnsafeStdout(t *testing.T) { t.Fatalf("written cookie is not readable by --cookie-stdin: err=%v", err) } } + +// fakeTerminal answers prompts in order and records whether each read had +// echo off. It reports EOF once the answers run out. +type fakeTerminal struct { + answers []string + secret []bool +} + +func (terminal *fakeTerminal) next(secret bool) (string, error) { + terminal.secret = append(terminal.secret, secret) + if len(terminal.answers) == 0 { + return "", io.EOF + } + answer := terminal.answers[0] + terminal.answers = terminal.answers[1:] + return answer, nil +} + +func (terminal *fakeTerminal) ReadLine() (string, error) { return terminal.next(false) } + +func (terminal *fakeTerminal) ReadSecret(showPrompt func()) (string, error) { + showPrompt() + return terminal.next(true) +} + +// useTempConfigDir points the user config directory at a temporary directory +// on every platform and returns the default cookie path for fakept. +func useTempConfigDir(t *testing.T) string { + t.Helper() + dir := t.TempDir() + t.Setenv("HOME", dir) + t.Setenv("XDG_CONFIG_HOME", dir) + t.Setenv("AppData", dir) + config, err := os.UserConfigDir() + if err != nil { + t.Fatal(err) + } + return filepath.Join(config, "ptctl", "sessions", "fakept.cookie") +} + +func runInteractiveLogin(adapter site.Adapter, terminal *fakeTerminal, stdout io.Writer, args ...string) (int, string) { + var errOut bytes.Buffer + a := &app{ + stdin: &trackingReader{}, stdout: stdout, stderr: &errOut, + registry: site.NewRegistry(adapter, readOnlyFakeSite{}), + terminal: func(io.Reader) (promptTerminal, bool) { return terminal, terminal != nil }, + } + code := runWithApp(append([]string{"site", "login"}, args...), a) + return code, errOut.String() +} + +func assertOnlyEntries(t *testing.T, dir string, want ...string) { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + var names []string + for _, entry := range entries { + names = append(names, entry.Name()) + } + if strings.Join(names, ",") != strings.Join(want, ",") { + t.Fatalf("%s holds %q, want %q", dir, names, want) + } +} + +func TestSiteLoginPromptsByDefaultAndSavesTheCookieOwnerOnly(t *testing.T) { + cookiePath := useTempConfigDir(t) + adapter := successfulLoginAdapter(t) + terminal := &fakeTerminal{answers: []string{" CanaryUser ", "PASSWORD-CANARY", " 123 456 "}} + var out bytes.Buffer + code, stderr := runInteractiveLogin(adapter, terminal, &out, "fakept") + if code != 0 || out.Len() != 0 { + t.Fatalf("code=%d stdout=%q stderr=%q", code, out.String(), stderr) + } + if fmt.Sprint(terminal.secret) != "[false true true]" { + t.Fatalf("echo-off reads=%v, want username echoed and password and code hidden", terminal.secret) + } + if adapter.calls != 1 || adapter.username != "CanaryUser" || adapter.password != "PASSWORD-CANARY" || !adapter.hasCode || adapter.code != "123456" || adapter.sessionDays != 7 { + t.Fatalf("login calls=%d username=%q days=%d hasCode=%v", adapter.calls, adapter.username, adapter.sessionDays, adapter.hasCode) + } + written, err := os.ReadFile(cookiePath) + if err != nil || string(written) != loginSessionCanary+"\n" { + t.Fatalf("cookie file content mismatch err=%v", err) + } + if session, err := readCredential(bytes.NewReader(written)); err != nil || session.SecretValue() != loginSessionCanary { + t.Fatalf("saved cookie is not readable by --cookie-stdin: err=%v", err) + } + if runtime.GOOS != "windows" { + for path, want := range map[string]os.FileMode{cookiePath: 0o600, filepath.Dir(cookiePath): 0o700} { + if info, err := os.Stat(path); err != nil || info.Mode().Perm() != want { + t.Fatalf("%s mode=%v err=%v, want %v", path, info.Mode().Perm(), err, want) + } + } + } + assertOnlyEntries(t, filepath.Dir(cookiePath), "fakept.cookie") + for _, want := range []string{ + "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: ", + } { + if !strings.Contains(stderr, want) { + t.Fatalf("stderr lacks %q: %q", want, stderr) + } + } + assertNoLoginLeak(t, stderr) + + // A second login replaces the file, and a looser mode does not survive. + if runtime.GOOS != "windows" { + if err := os.Chmod(cookiePath, 0o644); err != nil { + t.Fatal(err) + } + } + adapter = successfulLoginAdapter(t) + terminal = &fakeTerminal{answers: []string{"CanaryUser", "PASSWORD-CANARY", ""}} + code, stderr = runInteractiveLogin(adapter, terminal, &out, "--session-days", "30", "fakept") + if code != 0 || adapter.hasCode || adapter.sessionDays != 30 { + t.Fatalf("relogin code=%d hasCode=%v days=%d stderr=%q", code, adapter.hasCode, adapter.sessionDays, stderr) + } + if info, err := os.Stat(cookiePath); err != nil || (runtime.GOOS != "windows" && info.Mode().Perm() != 0o600) { + t.Fatalf("replaced cookie file err=%v", err) + } + assertOnlyEntries(t, filepath.Dir(cookiePath), "fakept.cookie") +} + +func TestSiteLoginReportsJSONWithoutTheCookie(t *testing.T) { + useTempConfigDir(t) + dir := t.TempDir() + for _, mode := range []string{"prompt", "bundle"} { + adapter := successfulLoginAdapter(t) + cookiePath := filepath.Join(dir, mode+".cookie") + var out bytes.Buffer + var code int + var stderr string + if mode == "prompt" { + terminal := &fakeTerminal{answers: []string{"CanaryUser", "PASSWORD-CANARY", "123456"}} + code, stderr = runInteractiveLogin(adapter, terminal, &out, "--cookie-file", cookiePath, "--output", "json", "fakept") + } else { + code, stderr = runSiteLogin(adapter, strings.NewReader(loginBundle()), &out, "--credential-bundle-stdin", "--cookie-file", cookiePath, "--output", "json", "fakept") + } + want := `{ + "schema": "ptctl.dev/v1", + "kind": "site.login", + "data": { + "site_id": "fakept", + "username": "CanaryUser", + "session_days": 7, + "session_expires_at": "2026-10-22T15:04:33Z", + "cookie_file": ` + strconv.Quote(cookiePath) + `, + "requests_attempted": 2 + } +} +` + if code != 0 || out.String() != want || strings.Contains(stderr, "site login succeeded") { + t.Fatalf("%s: code=%d stdout=%s stderr=%q", mode, code, out.String(), stderr) + } + if written, err := os.ReadFile(cookiePath); err != nil || string(written) != loginSessionCanary+"\n" { + t.Fatalf("%s: cookie file content mismatch err=%v", mode, err) + } + assertNoLoginLeak(t, out.String(), stderr) + } + assertOnlyEntries(t, dir, "bundle.cookie", "prompt.cookie") +} + +func TestSiteLoginInteractiveUsageErrorsNeverPrompt(t *testing.T) { + useTempConfigDir(t) + dir := t.TempDir() + for _, args := range [][]string{ + {"--cookie-file", dir, "fakept"}, + {"--cookie-file", filepath.Join(dir, "missing", "fakept.cookie"), "fakept"}, + {"--output", "yaml", "fakept"}, + {"--session-days", "2", "fakept"}, + {"unknown"}, + {"readonly"}, + {"--credential-bundle-stdin", "--output", "json", "fakept"}, + } { + adapter := successfulLoginAdapter(t) + terminal := &fakeTerminal{answers: []string{"CanaryUser", "PASSWORD-CANARY", ""}} + var out bytes.Buffer + code, stderr := runInteractiveLogin(adapter, terminal, &out, args...) + if code != 2 || len(terminal.secret) != 0 || adapter.calls != 0 || out.Len() != 0 || strings.Contains(stderr, "Username:") { + t.Fatalf("args=%q code=%d prompts=%d calls=%d stderr=%q", args, code, len(terminal.secret), adapter.calls, stderr) + } + } + assertOnlyEntries(t, dir) + + adapter := successfulLoginAdapter(t) + var out bytes.Buffer + code, stderr := runInteractiveLogin(adapter, nil, &out, "fakept") + if code != 2 || adapter.calls != 0 || !strings.Contains(stderr, "pipe the credentials with --credential-bundle-stdin") { + t.Fatalf("no terminal code=%d calls=%d stderr=%q", code, adapter.calls, stderr) + } +} + +func TestSiteLoginInteractiveFailuresKeepNoCookieFile(t *testing.T) { + cookiePath := useTempConfigDir(t) + tests := []struct { + answers []string + err error + want string + }{ + {answers: []string{"CanaryUser"}, want: "site login canceled before anything was sent"}, + {answers: []string{"", "PASSWORD-CANARY", ""}, want: "site login username is invalid"}, + {answers: []string{"CanaryUser", "", ""}, want: "site login account password is invalid"}, + {answers: []string{"CanaryUser", "PASSWORD-CANARY", "12a456"}, want: "site login one-time code is invalid"}, + {answers: []string{"CanaryUser", "PASSWORD-CANARY", "123456"}, err: &site.LoginError{Reason: site.LoginTwoFactorRejected}, want: "site login stopped: login_two_factor_rejected"}, + } + for _, test := range tests { + adapter := successfulLoginAdapter(t) + adapter.err = test.err + var out bytes.Buffer + code, stderr := runInteractiveLogin(adapter, &fakeTerminal{answers: test.answers}, &out, "fakept") + if code != 1 || out.Len() != 0 || !strings.HasSuffix(stderr, "error: "+test.want+"\n") { + t.Fatalf("answers=%q code=%d stderr=%q", test.answers, code, stderr) + } + if wantCalls := map[bool]int{true: 1, false: 0}[test.err != nil]; adapter.calls != wantCalls { + t.Fatalf("answers=%q login calls=%d", test.answers, adapter.calls) + } + assertOnlyEntries(t, filepath.Dir(cookiePath)) + assertNoLoginLeak(t, stderr) + } + + // A failed login leaves an earlier cookie file untouched. + if err := os.WriteFile(cookiePath, []byte("access_token=OLD\n"), 0o600); err != nil { + t.Fatal(err) + } + adapter := successfulLoginAdapter(t) + adapter.err = &site.LoginError{Reason: site.LoginCredentialsRejected} + if code, stderr := runInteractiveLogin(adapter, &fakeTerminal{answers: []string{"CanaryUser", "PASSWORD-CANARY", ""}}, io.Discard, "fakept"); code != 1 { + t.Fatalf("code=%d stderr=%q", code, stderr) + } + if written, err := os.ReadFile(cookiePath); err != nil || string(written) != "access_token=OLD\n" { + t.Fatalf("earlier cookie file changed: %q err=%v", written, err) + } + assertOnlyEntries(t, filepath.Dir(cookiePath), "fakept.cookie") +} + +func TestSiteLoginHelpExplainsEveryFlag(t *testing.T) { + for _, args := range [][]string{{"site", "login", "--help"}, {"help", "login"}, {"help", "site", "login"}} { + reader := &trackingReader{} + var out, errOut bytes.Buffer + if code := Run(args, reader, &out, &errOut); code != 0 || reader.read || errOut.Len() != 0 || out.String() != siteLoginHelp { + t.Fatalf("args=%q code=%d stderr=%q", args, code, errOut.String()) + } + } + for _, want := range []string{ + "--cookie-file PATH", "--session-days N", "--output table|json", "--credential-bundle-stdin", + `"schema":"ptctl.credentials/v1"`, "site_totp", "/ptctl/sessions/SITE.cookie", + site.LoginCredentialsRejected, site.LoginTwoFactorRequired, site.LoginTwoFactorRejected, + site.LoginResponseUnrecognized, site.LoginSessionUnverified, site.LoginRequestFailed, + } { + if !strings.Contains(siteLoginHelp, want) { + t.Fatalf("site login help lacks %q", want) + } + } +} diff --git a/internal/cli/terminal.go b/internal/cli/terminal.go new file mode 100644 index 0000000..209c59b --- /dev/null +++ b/internal/cli/terminal.go @@ -0,0 +1,98 @@ +package cli + +import ( + "errors" + "fmt" + "io" + "os" + "os/signal" + "strings" +) + +const maxPromptAnswerBytes = 4 << 10 + +// promptTerminal reads answers to prompts from an interactive terminal. +// ReadSecret turns echo off before it calls showPrompt, so nothing typed after +// the prompt appears is echoed. +type promptTerminal interface { + ReadLine() (string, error) + ReadSecret(showPrompt func()) (string, error) +} + +// stdinTerminal returns stdin as a prompt terminal when it is one. +func stdinTerminal(reader io.Reader) (promptTerminal, bool) { + file, ok := reader.(*os.File) + if !ok { + return nil, false + } + if _, err := getTerminalMode(file.Fd()); err != nil { + return nil, false + } + return fileTerminal{file: file}, true +} + +func (a *app) promptTerminal() (promptTerminal, bool) { + if a.terminal != nil { + return a.terminal(a.stdin) + } + return stdinTerminal(a.stdin) +} + +type fileTerminal struct{ file *os.File } + +// ReadLine reads one echoed line a byte at a time, so nothing typed after the +// newline is buffered away from a later ReadSecret. +func (t fileTerminal) ReadLine() (string, error) { + var line []byte + var b [1]byte + for { + n, err := t.file.Read(b[:]) + if n == 1 { + if b[0] == '\n' { + return strings.TrimSuffix(string(line), "\r"), nil + } + if len(line) == maxPromptAnswerBytes { + return "", errors.New("prompt answer is too long") + } + line = append(line, b[0]) + continue + } + if err == io.EOF && len(line) > 0 { + return strings.TrimSuffix(string(line), "\r"), nil + } + if err != nil { + return "", err + } + } +} + +// ReadSecret reads one line with echo off. Line editing and Ctrl+C keep +// working, and an interrupt restores echo before the process exits. +func (t fileTerminal) ReadSecret(showPrompt func()) (string, error) { + mode, err := getTerminalMode(t.file.Fd()) + if err != nil { + return "", err + } + interrupts := make(chan os.Signal, 1) + done := make(chan struct{}) + signal.Notify(interrupts, os.Interrupt) + go func() { + select { + case <-interrupts: + _ = mode.restore() + fmt.Fprintln(os.Stderr) + os.Exit(130) + case <-done: + } + }() + defer func() { + signal.Stop(interrupts) + close(done) + }() + if err := mode.hideInput(); err != nil { + return "", err + } + defer mode.restore() + showPrompt() + return t.ReadLine() +} diff --git a/internal/cli/terminal_bsd.go b/internal/cli/terminal_bsd.go new file mode 100644 index 0000000..5561c42 --- /dev/null +++ b/internal/cli/terminal_bsd.go @@ -0,0 +1,10 @@ +//go:build darwin || dragonfly || freebsd || netbsd || openbsd + +package cli + +import "golang.org/x/sys/unix" + +const ( + ioctlReadTermios = unix.TIOCGETA + ioctlWriteTermios = unix.TIOCSETA +) diff --git a/internal/cli/terminal_other.go b/internal/cli/terminal_other.go new file mode 100644 index 0000000..2774656 --- /dev/null +++ b/internal/cli/terminal_other.go @@ -0,0 +1,17 @@ +//go:build !(aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos || windows) + +package cli + +import "errors" + +var errNoHiddenInput = errors.New("hidden terminal input is not supported on this platform") + +// terminalMode is unavailable here, so site login needs +// --credential-bundle-stdin. +type terminalMode struct{} + +func getTerminalMode(uintptr) (*terminalMode, error) { return nil, errNoHiddenInput } + +func (*terminalMode) hideInput() error { return errNoHiddenInput } + +func (*terminalMode) restore() error { return nil } diff --git a/internal/cli/terminal_sysv.go b/internal/cli/terminal_sysv.go new file mode 100644 index 0000000..b6dd137 --- /dev/null +++ b/internal/cli/terminal_sysv.go @@ -0,0 +1,10 @@ +//go:build aix || linux || solaris || zos + +package cli + +import "golang.org/x/sys/unix" + +const ( + ioctlReadTermios = unix.TCGETS + ioctlWriteTermios = unix.TCSETS +) diff --git a/internal/cli/terminal_unix.go b/internal/cli/terminal_unix.go new file mode 100644 index 0000000..ca50bed --- /dev/null +++ b/internal/cli/terminal_unix.go @@ -0,0 +1,33 @@ +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos + +package cli + +import "golang.org/x/sys/unix" + +// terminalMode is the termios state a hidden read restores. +type terminalMode struct { + fd int + termios unix.Termios +} + +func getTerminalMode(fd uintptr) (*terminalMode, error) { + termios, err := unix.IoctlGetTermios(int(fd), ioctlReadTermios) + if err != nil { + return nil, err + } + return &terminalMode{fd: int(fd), termios: *termios}, nil +} + +// hideInput turns echo off and keeps canonical line editing and signals. It +// does not flush input that is already queued. +func (m *terminalMode) hideInput() error { + hidden := m.termios + hidden.Lflag &^= unix.ECHO + hidden.Lflag |= unix.ICANON | unix.ISIG + hidden.Iflag |= unix.ICRNL + return unix.IoctlSetTermios(m.fd, ioctlWriteTermios, &hidden) +} + +func (m *terminalMode) restore() error { + return unix.IoctlSetTermios(m.fd, ioctlWriteTermios, &m.termios) +} diff --git a/internal/cli/terminal_windows.go b/internal/cli/terminal_windows.go new file mode 100644 index 0000000..9b82757 --- /dev/null +++ b/internal/cli/terminal_windows.go @@ -0,0 +1,30 @@ +//go:build windows + +package cli + +import "golang.org/x/sys/windows" + +// terminalMode is the console input mode a hidden read restores. +type terminalMode struct { + handle windows.Handle + mode uint32 +} + +func getTerminalMode(fd uintptr) (*terminalMode, error) { + var mode uint32 + if err := windows.GetConsoleMode(windows.Handle(fd), &mode); err != nil { + return nil, err + } + return &terminalMode{handle: windows.Handle(fd), mode: mode}, nil +} + +// hideInput turns echo off and keeps console line editing and Ctrl+C. +func (m *terminalMode) hideInput() error { + hidden := m.mode &^ windows.ENABLE_ECHO_INPUT + hidden |= windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_INPUT + return windows.SetConsoleMode(m.handle, hidden) +} + +func (m *terminalMode) restore() error { + return windows.SetConsoleMode(m.handle, m.mode) +}