From 94774329bcf8a18da2c9845bb70331b74cd8e4fb Mon Sep 17 00:00:00 2001 From: Patrick Scheid Date: Fri, 27 Nov 2026 18:57:17 +0100 Subject: [PATCH] One clipboard flag: -c/--clipboard, the clipboard instead of the terminal --from-clipboard, --to-clipboard and --copy-link each named a direction, and next to each other they never said what moved. -c/--clipboard now means one thing on every command: what you would type comes from the clipboard, what you would read goes there. - share -c: at a terminal with no files and no --text, the clipboard's text is shared instead of asked for; the link goes on the clipboard and is not printed (the owner link is). With --code the code is printed. - open -c: the link from the clipboard instead of the prompt, the text onto it. Files are saved as usual; --json still prints. - receive -c: the text, or with --link the link, onto the clipboard. The code is never taken from it. - status, send, delete -c: the link from the clipboard. Files, -t, a link argument or a pipe still win, and an empty pipe is an error, never a reason to share the clipboard. A clipboard without a link is refused without showing what it holds. The terminal tests run the two-computer flow, share -c --code and receive -c, against a clipboard in a file. --- README.md | 27 +++-- internal/cli/cli.go | 4 +- internal/cli/clipboard.go | 2 +- internal/cli/clipboard_test.go | 188 +++++++++++++++------------------ internal/cli/delete.go | 15 ++- internal/cli/main_test.go | 30 ++++++ internal/cli/open.go | 65 ++++++------ internal/cli/receive.go | 15 +-- internal/cli/send.go | 14 ++- internal/cli/share.go | 70 +++++++----- internal/cli/status.go | 14 ++- internal/cli/terminal_test.go | 106 +++++++++++++++++++ internal/cli/transfer_test.go | 2 +- internal/cli/untrusted.go | 2 +- 14 files changed, 370 insertions(+), 184 deletions(-) diff --git a/README.md b/README.md index fa2a5aa..2d61783 100644 --- a/README.md +++ b/README.md @@ -7,13 +7,15 @@ It speaks the same format as the web app, so links work in both directions: a li ```bash secretli share # type or paste the secret, then Ctrl-D pbpaste | secretli share -e 1h # text from a pipe, gone after an hour -secretli share --from-clipboard -c # the clipboard's text in, the link back on the clipboard +secretli share -c # the clipboard's text in, the link back on the clipboard secretli share deploy.key notes.pdf # files; -p adds a password, --reusable lets it open more than once -secretli open # text to stdout, files to the current directory; -c copies text instead +secretli open # text to stdout, files to the current directory +secretli open -c # the link from the clipboard, the text back on it secretli status # what a link points to, without opening it secretli delete # remove a secret for everyone secretli send # hand a link to another device with a code like 7-acid-rocket secretli receive 7-acid-rocket # open what another device sends with a code +secretli share -c --code # the clipboard's text to another device; there: secretli receive -c ``` ## Install @@ -58,25 +60,36 @@ For shell completion without Homebrew, `secretli completion zsh --help` (or `bas ## Use -**Sharing.** Files are arguments; text comes from a pipe, from a prompt when you are at a terminal, from the clipboard with `--from-clipboard`, or from `-t`. The prompt, the pipe and the clipboard keep the secret out of your shell history; `-t` does not. `--from-clipboard` leaves off the clipboard's final line break, as `open --to-clipboard` does, and with `--name` shares the clipboard as a file; it works with the same clipboard tools as `--to-clipboard`. `-` shares stdin as a file named by `--name`: +**Sharing.** Files are arguments; text comes from a pipe, from a prompt when you are at a terminal, from the clipboard with `-c`, or from `-t`. The prompt, the pipe and the clipboard keep the secret out of your shell history; `-t` does not. `-` shares stdin as a file named by `--name`: ```bash pg_dump db | gzip | secretli share --name db.sql.gz ``` -Links open once and expire after a day unless you say otherwise: `-e` takes `5m`, `10m`, `15m`, `1h`, `4h`, `12h`, `1d`, `3d` or `7d`, and `--reusable` lets a link open again and again until it expires. `-p` asks for a password; `--password-file` and `SECRETLI_PASSWORD` provide one without asking. The server takes ten wrong passwords for a secret and deletes it at the tenth; `open` says after each wrong one how many are left, and at a terminal asks again. `--qr` also draws the link as a QR code, for a phone to scan off the screen, and `-c`/`--copy-link` copies it to the clipboard. +Links open once and expire after a day unless you say otherwise: `-e` takes `5m`, `10m`, `15m`, `1h`, `4h`, `12h`, `1d`, `3d` or `7d`, and `--reusable` lets a link open again and again until it expires. `-p` asks for a password; `--password-file` and `SECRETLI_PASSWORD` provide one without asking. The server takes ten wrong passwords for a secret and deletes it at the tenth; `open` says after each wrong one how many are left, and at a terminal asks again. `--qr` also draws the link as a QR code, for a phone to scan off the screen, and `-c` puts it on the clipboard instead of printing it. Every share prints two links: the one to hand out, and the owner link, which can delete the secret and, for a reusable one, tells you whether it has been opened. Keep the owner link to yourself. -**Opening.** Text goes to stdout exactly as it was shared. At a terminal, control characters in it, which could steer the terminal, show as `�`, and the command says so; a pipe, a file or `--to-clipboard` gets the exact text. File names and error messages from the server reach the terminal without control characters or direction overrides either. Files are saved to the current directory or to `--out`, and nothing is overwritten unless you pass `--force`; `--stdout` streams a single file instead. When a file of that name exists, a reusable secret is refused before anything is saved, and you can open it again elsewhere; a one-time secret, used up by then, saves that file as `name (2).ext`, or the next number free, and says so. A file's name is made safe first: no path, no control characters, no names Windows reserves for devices, at most 255 bytes. Two files of one secret with the same name are both saved, the second as `name (2).ext`, and the command says so. `--force` replaces a file that exists with a new one, so a link in its place is replaced, never followed. Before anything is opened, the command says what the link points to. Opening a one-time secret uses it up, so for one of those it asks first, and Enter means no; `-y`/`--yes` opens it without asking. Reusable secrets open right away. Without an argument the link is read from stdin, or asked for without showing what you paste, which keeps it out of your shell history and the scrollback too. +**Opening.** Text goes to stdout exactly as it was shared. At a terminal, control characters in it, which could steer the terminal, show as `�`, and the command says so; a pipe, a file or `-c` gets the exact text. File names and error messages from the server reach the terminal without control characters or direction overrides either. Files are saved to the current directory or to `--out`, and nothing is overwritten unless you pass `--force`; `--stdout` streams a single file instead. When a file of that name exists, a reusable secret is refused before anything is saved, and you can open it again elsewhere; a one-time secret, used up by then, saves that file as `name (2).ext`, or the next number free, and says so. A file's name is made safe first: no path, no control characters, no names Windows reserves for devices, at most 255 bytes. Two files of one secret with the same name are both saved, the second as `name (2).ext`, and the command says so. `--force` replaces a file that exists with a new one, so a link in its place is replaced, never followed. Before anything is opened, the command says what the link points to. Opening a one-time secret uses it up, so for one of those it asks first, and Enter means no; `-y`/`--yes` opens it without asking. Reusable secrets open right away. Without an argument the link is read from stdin, or asked for without showing what you paste, which keeps it out of your shell history and the scrollback too. When a secret holds several files, `open` lists them with their sizes and asks which to save. Enter saves them all; numbers, ranges and names or patterns pick some, as in `2`, `1 3`, `1-2` or `*.jpg`, and a list of more than 30 files shows the first 30, while numbers and patterns reach them all. Of a one-time secret, the files you don't save are gone with it, and it says so before it asks. A secret over 1 MiB is downloaded after the question, which the server allows for 15 minutes after it is opened, so for one of those it also says the time by which the files have to be saved. Only the files you pick count when names are checked against the directory. `--stdout` asks for the one file to write. With `--yes` or `--json`, or where there is no terminal, nothing is asked: every file is saved, and `--stdout` needs a secret of a single file. -`-c`/`--to-clipboard` puts text on the clipboard instead of the terminal, so it doesn't stay in the scrollback. The final line break is left off, so pasting a password doesn't also press Enter. 45 seconds later the clipboard is cleared, unless you copied something else by then. Before anything is opened, `--to-clipboard` checks that there is a clipboard tool (`pbcopy`, `wl-copy`, `xclip`, `xsel` or `clip.exe`) and that the secret is text; should copying still fail, the text is printed after all, so a one-time secret isn't lost. +**The clipboard.** `-c`/`--clipboard` uses the clipboard instead of the terminal, on every command: what you would type comes from it, and what you would read goes to it. + +| | from the clipboard | to the clipboard | +|---|---|---| +| `share -c` | the secret, instead of the prompt | the link, instead of printing it | +| `open -c` | the link, instead of the prompt | the text | +| `receive -c` | — (the code is typed) | the text, or with `--link` the link | +| `status -c`, `send -c`, `delete -c` | the link, instead of the prompt | — | + +Anything you give explicitly still wins: files, `-t` or a pipe for `share`, a link as an argument or piped in for the others; then only the other side uses the clipboard. An empty pipe is an error, never a reason to share the clipboard. Files of an opened secret are saved as usual, `--json` still prints everything, and with `share --code` the code is printed, since you read it to type it on the other device. Before anything is uploaded or opened, `-c` checks that there is a clipboard tool (`pbcopy`, `wl-copy`, `xclip`, `xsel` or `clip.exe`). + +What goes on the clipboard carries a key, so 45 seconds later the clipboard is cleared, unless you copied something else by then. Text goes there without its final line break, so pasting a password doesn't also press Enter, and `share -c` leaves the clipboard's final line break off in the same way, so what one shares, the other gives back. Should copying fail, what was to be copied is printed after all, so a one-time secret isn't lost. A clipboard that holds no link is never shown in the error, as it may hold a secret. **Handing a link over with a code.** Instead of copying a link to another device, `send` hands it over with a short code like `7-acid-rocket`. On the other device, type the code at the server's `/c` page (`secretli.app/c`) or run `secretli receive 7-acid-rocket`; `secretli share --code` makes a secret and hands it over in one go. The link travels encrypted, and only after the other device has proved it typed the same code; the words never leave the two devices. A code works once and for ten minutes, and a wrong code ends the transfer on both sides. Given an owner link, `send` hands over only the link to hand out. It works both ways with the web app's "Send with a code". -`receive` opens what it receives like `open` does, with the same `--out`, `--stdout`, `--force`, `--yes`, `--to-clipboard` and password options, or prints the link with `--link` (with `--to-clipboard`, it copies the link). If you decline to open a one-time secret, it prints the link instead, since the code is used up by then. Typing is forgiving: `7 acid rocket`, `7-ACID-ROCKET` and `7-aci-roc` all work. Without an argument the code is asked for, and what you type isn't shown; a misspelt word is caught before the code is used. +`receive` opens what it receives like `open` does, with the same `--out`, `--stdout`, `--force`, `--yes`, `-c` and password options, or prints the link with `--link` (with `-c`, it copies the link). If you decline to open a one-time secret, it prints the link instead, since the code is used up by then. Typing is forgiving: `7 acid rocket`, `7-ACID-ROCKET` and `7-aci-roc` all work. Without an argument the code is asked for, and what you type isn't shown; a misspelt word is caught before the code is used. **Checking and deleting.** `status` describes a secret from its link without opening it: text or files, one-time or reusable, password or not, when it was sent and when it expires, and whether it has been opened. Once a secret is gone, opened, deleted or expired, the server keeps nothing about it, so all `status` can say then is that it is gone, to the owner as to a recipient, as it does for a link to nothing. The exit code is 4 then, and with `--json` the state is `live` or `gone`. `delete` takes the owner link and asks before it deletes, unless you pass `--yes`. diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 08c704f..e98c525 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -123,7 +123,9 @@ Links from this command open in the web app and the other way round.`, secretli status what a link points to, without opening it secretli delete remove a secret for everyone secretli send hand a link to another device with a short code - secretli receive 7-acid-rocket open what another device sends with a code`, + secretli receive 7-acid-rocket open what another device sends with a code + secretli share -c --code the clipboard's text, handed over with a code + secretli receive 7-acid-rocket -c and on the other device, back onto the clipboard`, SilenceUsage: true, SilenceErrors: true, Version: version(), diff --git a/internal/cli/clipboard.go b/internal/cli/clipboard.go index 182ccb4..91acefc 100644 --- a/internal/cli/clipboard.go +++ b/internal/cli/clipboard.go @@ -22,7 +22,7 @@ const clipboardClearAfter = 45 * time.Second // clipboardTool is the desktop's clipboard. type clipboardTool interface { // Available fails when there is no clipboard to copy to, so that - // --to-clipboard is refused before anything is opened. + // --clipboard is refused before anything is opened. Available() error Copy(text string) error Paste() (string, error) diff --git a/internal/cli/clipboard_test.go b/internal/cli/clipboard_test.go index 99ec0d9..d89b721 100644 --- a/internal/cli/clipboard_test.go +++ b/internal/cli/clipboard_test.go @@ -94,7 +94,7 @@ func TestOpenCopiesTheSecretInsteadOfPrintingIt(t *testing.T) { cb := fakeClipboard(t) link, _ := shareText(t, "--server="+srv.URL, "hunter2\n") - stdout, stderr, code := runCLI(t, "", "open", link, "--to-clipboard", "--yes") + stdout, stderr, code := runCLI(t, "", "open", link, "--clipboard", "--yes") if code != 0 || stdout != "" { t.Fatalf("exit %d, stdout %q, stderr %q", code, stdout, stderr) } @@ -112,135 +112,118 @@ func TestOpenCopiesTheSecretInsteadOfPrintingIt(t *testing.T) { } } -// The link carries the key, so share --copy-link has it cleared like open -// --to-clipboard. -func TestShareCopiesTheLinkAndClearsItLater(t *testing.T) { +// share --clipboard puts the link on the clipboard instead of printing it, +// and has it cleared like the secret: the link carries the key. A pipe is +// still what is shared; the clipboard stands in only for the prompt. +func TestShareCopiesTheLinkInsteadOfPrintingIt(t *testing.T) { srv := fakeServer(t) cb := fakeClipboard(t) + cb.text = "not this" - stdout, stderr, code := runCLI(t, "the launch code", "share", "--server="+srv.URL, "--copy-link") - if code != 0 { - t.Fatalf("exit %d, stderr %q", code, stderr) + stdout, stderr, code := runCLI(t, "the launch code", "share", "--server="+srv.URL, "-c") + if code != 0 || stdout != "" { + t.Fatalf("exit %d, stdout %q, stderr %q", code, stdout, stderr) } - link := strings.TrimSpace(stdout) - text, clearers := cb.state() - if text != link || !strings.Contains(link, "/s#") { - t.Errorf("clipboard = %q, link = %q", text, link) + link, clearers := cb.state() + if !strings.Contains(link, "/s#") || strings.Contains(link, "!") { + t.Fatalf("clipboard = %q, want the link to hand out", link) } if len(clearers) != 1 || clearers[0].hash != clipHash(link) || clearers[0].after != 45*time.Second { t.Errorf("clearers = %+v", clearers) } - if !strings.Contains(stderr, "Copied the link to the clipboard; it is cleared in 45 seconds.") { + // The owner link exists nowhere else, so it is still printed. + if !strings.Contains(stderr, "Copied the link to the clipboard; it is cleared in 45 seconds.") || !strings.Contains(stderr, "Owner link") || strings.Contains(stderr, link+"\n") { t.Errorf("stderr = %q", stderr) } -} - -// --from-clipboard shares the clipboard's text, and with --copy-link the -// link takes its place there: what open --to-clipboard gives back is what -// was pasted. -func TestSharePastesTheClipboard(t *testing.T) { - srv := fakeServer(t) - server := "--server=" + srv.URL - cb := fakeClipboard(t) + if stdout, _, code := runCLI(t, "", "open", link, "--yes"); code != 0 || stdout != "the launch code" { + t.Errorf("open: exit %d, stdout %q", code, stdout) + } - // The paste tool's own line break is not part of the secret. - cb.text, cb.pasteSuffix = "hunter2", "\r\n" - stdout, stderr, code := runCLI(t, "ignored", "share", server, "--from-clipboard", "--copy-link") - if code != 0 { - t.Fatalf("exit %d, stderr %q", code, stderr) + // Files are shared as files; only the link goes on the clipboard. + file := filepath.Join(t.TempDir(), "a.txt") + if err := os.WriteFile(file, []byte("a"), 0o600); err != nil { + t.Fatal(err) } - link := strings.TrimSpace(stdout) - cb.pasteSuffix = "" - if text, _ := cb.state(); text != link { - t.Errorf("clipboard = %q, want the link %q", text, link) + if stdout, stderr, code := runCLI(t, "", "share", "--server="+srv.URL, file, "-c"); code != 0 || stdout != "" { + t.Errorf("file: exit %d, stdout %q, stderr %q", code, stdout, stderr) } - if stdout, _, code := runCLI(t, "", "open", link, "--yes"); code != 0 || stdout != "hunter2" { - t.Errorf("open: exit %d, stdout %q", code, stdout) + if text, _ := cb.state(); !strings.Contains(text, "/s#") || text == link { + t.Errorf("clipboard after a file = %q", text) } +} - // With --name, the clipboard is shared as a file. - cb.text = "A=1\nB=2\n" - link, _ = shareText(t, server, "", "--from-clipboard", "--name", ".env") - dir := t.TempDir() - if _, stderr, code := runCLI(t, "", "open", link, "--yes", "--out", dir); code != 0 { - t.Fatalf("open file: exit %d, stderr %q", code, stderr) +// An empty pipe, as from a command that printed nothing, is an error, never +// a reason to share whatever is on the clipboard. +func TestShareNeverFallsBackToTheClipboard(t *testing.T) { + srv := fakeServer(t) + cb := fakeClipboard(t) + cb.text = "the clipboard" + + if _, stderr, code := runCLI(t, "", "share", "--server="+srv.URL, "-c"); code == 0 || !strings.Contains(stderr, share.ErrNothingToShare.Error()) { + t.Errorf("exit %d, stderr %q", code, stderr) } - if data, err := os.ReadFile(filepath.Join(dir, ".env")); err != nil || string(data) != "A=1\nB=2" { - t.Errorf(".env = %q, %v", data, err) + if text, clearers := cb.state(); text != "the clipboard" || len(clearers) != 0 { + t.Errorf("clipboard = %q, clearers %+v", text, clearers) } } -func TestPasteIsRefusedBeforeAnythingIsUploaded(t *testing.T) { +func TestClipboardIsRefusedBeforeAnythingIsUsedUp(t *testing.T) { srv := fakeServer(t) server := "--server=" + srv.URL - cb := fakeClipboard(t) - file := filepath.Join(t.TempDir(), "a.txt") - if err := os.WriteFile(file, []byte("a"), 0o600); err != nil { - t.Fatal(err) - } + fakeClipboard(t) + link, owner := shareText(t, server, "only once\n") - cb.text = "x" - for _, args := range [][]string{{"-t", "y"}, {file}, {"-"}} { - if _, stderr, code := runCLI(t, "", append([]string{"share", server, "--from-clipboard"}, args...)...); code != ExitError || !strings.Contains(stderr, "--from-clipboard shares the clipboard; leave out --text and files") { + // No clipboard tool: refused before anything is read or uploaded. + clipboard = noClipboard{} + for _, args := range [][]string{ + {"share", server, "-t", "x", "-c"}, + {"open", link, "-c", "--yes"}, + {"status", link, "-c"}, + {"send", link, "-c"}, + {"delete", owner, "-c", "--yes"}, + {"receive", "7-acid-rocket", server, "-c", "--yes"}, + } { + if _, stderr, code := runCLI(t, "", args...); code != ExitError || !strings.Contains(stderr, "--clipboard: no clipboard tool found") { t.Errorf("%v: exit %d, stderr %q", args, code, stderr) } } - cb.text = "\n" - if _, stderr, code := runCLI(t, "", "share", server, "--from-clipboard"); code != ExitError || !strings.Contains(stderr, "--from-clipboard: the clipboard holds no text") { - t.Errorf("empty clipboard: exit %d, stderr %q", code, stderr) + // Nothing was deleted or used up: it still opens. + if _, _, code := runCLI(t, "", "status", owner); code != 0 { + t.Errorf("owner link afterwards: exit %d", code) } - - clipboard = noClipboard{} - if _, stderr, code := runCLI(t, "", "share", server, "--from-clipboard"); code != ExitError || !strings.Contains(stderr, "--from-clipboard: no clipboard tool found") { - t.Errorf("no clipboard: exit %d, stderr %q", code, stderr) + if stdout, _, code := runCLI(t, "", "open", link, "--yes"); code != 0 || stdout != "only once\n" { + t.Errorf("afterwards: exit %d, stdout %q", code, stdout) } } -func TestCopyIsRefusedBeforeAnythingIsUsedUp(t *testing.T) { +// Files are saved as usual with --clipboard, and --json still prints text: +// what is given explicitly wins. +func TestOpenWithTheClipboardSavesFilesAndKeepsJSON(t *testing.T) { srv := fakeServer(t) server := "--server=" + srv.URL cb := fakeClipboard(t) - link, _ := shareText(t, server, "only once\n") - - for _, tc := range []struct { - args []string - want string - }{ - {[]string{"--stdout"}, "--stdout writes a file and --to-clipboard copies text"}, - {[]string{"--json"}, "--json prints the secret; leave out --to-clipboard"}, - } { - // With --json, the error is JSON on stdout. - stdout, stderr, code := runCLI(t, "", append([]string{"open", link, "--to-clipboard", "--yes"}, tc.args...)...) - if code != ExitError || !strings.Contains(stdout+stderr, tc.want) { - t.Errorf("%v: exit %d, stdout %q, stderr %q", tc.args, code, stdout, stderr) - } - } - - // No clipboard tool: refused before the link is even read. - clipboard = noClipboard{} - if _, stderr, code := runCLI(t, "", "open", link, "--to-clipboard", "--yes"); code != ExitError || !strings.Contains(stderr, "--to-clipboard: no clipboard tool found") { - t.Errorf("no clipboard: exit %d, stderr %q", code, stderr) - } - clipboard = cb - - // Files: refused once the link says what it holds, before it is opened. dir := t.TempDir() notes := filepath.Join(dir, "notes.txt") if err := os.WriteFile(notes, []byte("notes"), 0o600); err != nil { t.Fatal(err) } fileLink, _ := shareText(t, server, "", notes) - if _, stderr, code := runCLI(t, "", "open", fileLink, "--to-clipboard", "--yes"); code != ExitError || !strings.Contains(stderr, "--to-clipboard is for text, and this secret holds files") { - t.Errorf("files: exit %d, stderr %q", code, stderr) + out := filepath.Join(dir, "received") + if _, stderr, code := runCLI(t, "", "open", fileLink, "-c", "--yes", "--out", out); code != 0 { + t.Fatalf("files: exit %d, stderr %q", code, stderr) + } + if data, err := os.ReadFile(filepath.Join(out, "notes.txt")); err != nil || string(data) != "notes" { + t.Errorf("notes.txt = %q, %v", data, err) } - // Both still open. - if stdout, _, code := runCLI(t, "", "open", link, "--yes"); code != 0 || stdout != "only once\n" { - t.Errorf("text afterwards: exit %d, stdout %q", code, stdout) + link, _ := shareText(t, server, "in json\n") + stdout, stderr, code := runCLI(t, "", "--json", "open", link, "-c", "--yes") + if code != 0 || !strings.Contains(stdout, `"text":"in json\n"`) { + t.Errorf("json: exit %d, stdout %q, stderr %q", code, stdout, stderr) } - if _, stderr, code := runCLI(t, "", "open", fileLink, "--yes", "--out", filepath.Join(dir, "received")); code != 0 { - t.Errorf("files afterwards: exit %d, stderr %q", code, stderr) + if text, _ := cb.state(); text != "" { + t.Errorf("clipboard after json = %q", text) } } @@ -251,9 +234,15 @@ func TestACopyThatFailsPrintsTheSecretAfterAll(t *testing.T) { link, _ := shareText(t, "--server="+srv.URL, "hunter2\n") // The one-time secret is used up by then, so this is the only copy. - stdout, stderr, code := runCLI(t, "", "open", link, "--to-clipboard", "--yes") + stdout, stderr, code := runCLI(t, "", "open", link, "--clipboard", "--yes") if code != 0 || stdout != "hunter2\n" || !strings.Contains(stderr, "Couldn't copy to the clipboard (xclip: exit status 1), so here it is:") { - t.Errorf("exit %d, stdout %q, stderr %q", code, stdout, stderr) + t.Errorf("open: exit %d, stdout %q, stderr %q", code, stdout, stderr) + } + + // The new link is printed after all, too. + stdout, stderr, code = runCLI(t, "a secret", "share", "--server="+srv.URL, "-c") + if code != 0 || !strings.Contains(stdout, "/s#") || !strings.Contains(stderr, "Couldn't copy to the clipboard (xclip: exit status 1), so here it is.") { + t.Errorf("share: exit %d, stdout %q, stderr %q", code, stdout, stderr) } } @@ -274,7 +263,7 @@ func TestReceiveCopies(t *testing.T) { } link, _ := shareText(t, server, "handed over\n") - if stdout, stderr, code := receive(link, "--to-clipboard", "--yes"); code != 0 || stdout != "" { + if stdout, stderr, code := receive(link, "-c", "--yes"); code != 0 || stdout != "" { t.Errorf("text: exit %d, stdout %q, stderr %q", code, stdout, stderr) } if text, _ := cb.state(); text != "handed over" { @@ -283,27 +272,26 @@ func TestReceiveCopies(t *testing.T) { // With --link, the link is what goes on the clipboard. link, _ = shareText(t, server, "a link\n") - if stdout, stderr, code := receive(link, "--to-clipboard", "--link"); code != 0 || stdout != "" || !strings.Contains(stderr, "Copied the link") { + if stdout, stderr, code := receive(link, "-c", "--link"); code != 0 || stdout != "" || !strings.Contains(stderr, "Copied the link") { t.Errorf("link: exit %d, stdout %q, stderr %q", code, stdout, stderr) } if text, _ := cb.state(); text != link { t.Errorf("clipboard after --link = %q, want %q", text, link) } - // Files: the code is used up by the time that is known, so the link is - // printed rather than lost, and it still opens. + // Files are saved as usual. dir := t.TempDir() notes := filepath.Join(dir, "notes.txt") if err := os.WriteFile(notes, []byte("notes"), 0o600); err != nil { t.Fatal(err) } fileLink, _ := shareText(t, server, "", notes) - stdout, stderr, code := receive(fileLink, "--to-clipboard", "--yes") - if code != ExitError || strings.TrimSpace(stdout) != fileLink || !strings.Contains(stderr, "Not opened: --to-clipboard is for text") || !strings.Contains(stderr, "Here is the link, which still works") { - t.Errorf("files: exit %d, stdout %q, stderr %q", code, stdout, stderr) + out := filepath.Join(dir, "received") + if _, stderr, code := receive(fileLink, "-c", "--yes", "--out", out); code != 0 { + t.Errorf("files: exit %d, stderr %q", code, stderr) } - if _, stderr, code := runCLI(t, "", "open", fileLink, "--yes", "--out", filepath.Join(dir, "received")); code != 0 { - t.Errorf("files afterwards: exit %d, stderr %q", code, stderr) + if data, err := os.ReadFile(filepath.Join(out, "notes.txt")); err != nil || string(data) != "notes" { + t.Errorf("notes.txt = %q, %v", data, err) } } @@ -374,7 +362,7 @@ func TestTabCompletion(t *testing.T) { } } - // The command behind --to-clipboard's clearing stays out of sight. + // The command behind --clipboard's clearing stays out of sight. if stdout, _, _ := runCLI(t, "", "--help"); strings.Contains(stdout, "clear-clipboard") { t.Errorf("help lists clear-clipboard: %q", stdout) } diff --git a/internal/cli/delete.go b/internal/cli/delete.go index 8ae9375..a700037 100644 --- a/internal/cli/delete.go +++ b/internal/cli/delete.go @@ -10,26 +10,31 @@ import ( ) func newDeleteCmd(e *env) *cobra.Command { - var yes bool + var yes, fromClipboard bool cmd := &cobra.Command{ Use: "delete ", Short: "Delete a secret for everyone", Long: `Deletes a secret before it is opened or expires. Only the owner link, the one with the part after "!", can do this. The link stops working right away.`, Example: ` secretli delete 'https://secretli.app/s#…!…' - secretli delete "$OWNER_LINK" --yes`, + secretli delete "$OWNER_LINK" --yes + secretli delete -c the owner link from the clipboard`, Args: cobra.MaximumNArgs(1), ValidArgsFunction: cobra.NoFileCompletions, RunE: run(func(cmd *cobra.Command, args []string) error { - return e.delete(cmd.Context(), args, yes) + return e.delete(cmd.Context(), args, yes, fromClipboard) }), } cmd.Flags().BoolVarP(&yes, "yes", "y", false, "don't ask; needed when not at a terminal") + cmd.Flags().BoolVarP(&fromClipboard, "clipboard", "c", false, "take the owner link from the clipboard instead of asking for it") return cmd } -func (e *env) delete(ctx context.Context, args []string, yes bool) error { - link, err := e.linkArg(ctx, args) +func (e *env) delete(ctx context.Context, args []string, yes, fromClipboard bool) error { + if err := checkClipboard(fromClipboard); err != nil { + return err + } + link, err := e.linkArg(ctx, args, fromClipboard) if err != nil { return err } diff --git a/internal/cli/main_test.go b/internal/cli/main_test.go index 80ea748..f3b6265 100644 --- a/internal/cli/main_test.go +++ b/internal/cli/main_test.go @@ -12,6 +12,28 @@ import ( // way, in a pseudo-terminal of its own. const runAsCommand = "SECRETLI_TEST_RUN_AS_COMMAND" +// testClipboard names the file that is the clipboard of a command the +// terminal tests start. +const testClipboard = "SECRETLI_TEST_CLIPBOARD" + +// fileClipboard is a clipboard in a file, for commands in a process of +// their own. +type fileClipboard string + +func (f fileClipboard) Available() error { return nil } + +func (f fileClipboard) Copy(text string) error { return os.WriteFile(string(f), []byte(text), 0o600) } + +func (f fileClipboard) Paste() (string, error) { + b, err := os.ReadFile(string(f)) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + return string(b), err +} + +func (f fileClipboard) Clear() error { return f.Copy("") } + // The tests never ask on the terminal they run in: without a terminal, // as in CI, commands that would ask fail instead, and tests that want an // answer give one with answering. Nor do they touch the machine's @@ -19,6 +41,14 @@ const runAsCommand = "SECRETLI_TEST_RUN_AS_COMMAND" // fakeClipboard. func TestMain(m *testing.M) { if os.Getenv(runAsCommand) == "1" { + // At a terminal too, the tests never touch the machine's clipboard: + // one in a file stands in for it, and nothing is started to clear it. + if path := os.Getenv(testClipboard); path != "" { + clipboard = fileClipboard(path) + startClipboardClearer = func(string, time.Duration) error { return nil } + } else { + clipboard = noClipboard{} + } os.Exit(Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) } openTTY = func() (*terminal, error) { return nil, errNoTerminal } diff --git a/internal/cli/open.go b/internal/cli/open.go index a8f9c65..875cf00 100644 --- a/internal/cli/open.go +++ b/internal/cli/open.go @@ -25,16 +25,12 @@ type openOptions struct { password bool passwordFile string yes bool - toClipboard bool + clipboard bool } // errNotOpened is a one-time secret the person chose not to open yet. var errNotOpened = errors.New("not opened") -// errCopyIsForText is --to-clipboard on a secret that holds files, found out -// before it is opened. -var errCopyIsForText = errors.New("--to-clipboard is for text, and this secret holds files; leave out --to-clipboard to save them") - func newOpenCmd(e *env) *cobra.Command { var o openOptions cmd := &cobra.Command{ @@ -44,7 +40,7 @@ func newOpenCmd(e *env) *cobra.Command { saved to the current directory, or to --out, and never overwrite anything unless --force is given. At a terminal, control characters in the text, which could steer the terminal, are shown as a replacement character, and you are -told; --to-clipboard, or stdout to a file or pipe, gives the exact text. +told; --clipboard, or stdout to a file or pipe, gives the exact text. Of a secret with several files, at a terminal, the files are listed and you are asked which to save: Enter saves them all, and numbers, ranges and @@ -53,9 +49,12 @@ the one to write. With --yes or --json, or where there is no terminal to ask on, nothing is asked: every file is saved, and --stdout needs a secret of a single file. ---to-clipboard puts text on the clipboard instead, without its final line -break, so it never shows in the terminal or its scrollback. The clipboard is -cleared 45 seconds later, unless something else was copied by then. +--clipboard uses the clipboard instead of the terminal: without an argument +or a pipe, the link is taken from it instead of asked for, and text goes to +it instead of the terminal, without its final line break, so it never shows +in the terminal or its scrollback. The clipboard is cleared 45 seconds +later, unless something else was copied by then. Files are saved as usual, +and --json still prints the text. Opening a one-time secret is what uses it up, so the link is described first and you are asked before it is opened. --yes opens it without asking, and is @@ -66,7 +65,7 @@ scrollback.`, Example: ` secretli open 'https://secretli.app/s#…' secretli open 'https://secretli.app/s#…' --out ./received secretli open 'https://secretli.app/s#…' --stdout > backup.tgz - secretli open 'https://secretli.app/s#…' --to-clipboard + secretli open -c the link from the clipboard, the text back on it pbpaste | secretli open`, Args: cobra.MaximumNArgs(1), ValidArgsFunction: cobra.NoFileCompletions, @@ -92,33 +91,27 @@ func addOpenFlags(cmd *cobra.Command, o *openOptions) { f.BoolVarP(&o.password, "password", "p", false, "the secret has a password (asked for, or SECRETLI_PASSWORD)") f.StringVar(&o.passwordFile, "password-file", "", "read the password from the first line of this file") f.BoolVarP(&o.yes, "yes", "y", false, "open a one-time secret without asking; needed when not at a terminal") - f.BoolVarP(&o.toClipboard, "to-clipboard", "c", false, "copy text to the clipboard instead of printing it; cleared after 45 seconds") + f.BoolVarP(&o.clipboard, "clipboard", "c", false, "the clipboard instead of the terminal: the link from it, the text to it") _ = cmd.MarkFlagDirname("out") } -// checkCopy refuses --to-clipboard where it cannot work. It runs before the +// checkClipboard refuses --clipboard without a clipboard. It runs before the // link or the code is taken, so that nothing is used up for a refusal. -func (e *env) checkCopy(o openOptions) error { - if !o.toClipboard { +func checkClipboard(on bool) error { + if !on { return nil } - switch { - case o.toStdout: - return errors.New("--stdout writes a file and --to-clipboard copies text; use one of them") - case e.json: - return errors.New("--json prints the secret; leave out --to-clipboard") - } if err := clipboard.Available(); err != nil { - return fmt.Errorf("--to-clipboard: %w", err) + return fmt.Errorf("--clipboard: %w", err) } return nil } func (e *env) open(ctx context.Context, o openOptions, args []string) error { - if err := e.checkCopy(o); err != nil { + if err := checkClipboard(o.clipboard); err != nil { return err } - link, err := e.linkArg(ctx, args) + link, err := e.linkArg(ctx, args, o.clipboard) if err != nil { return err } @@ -134,9 +127,6 @@ func (e *env) openLink(ctx context.Context, o openOptions, link share.Link) erro return err } e.say("%s\n", describeInfo(info, link.IsOwner(), now)) - if o.toClipboard && info.Kind != share.KindText { - return errCopyIsForText - } if !info.Reusable && !o.yes { if err := e.confirmOpen(ctx, link.IsOwner()); err != nil { return err @@ -158,7 +148,7 @@ func (e *env) openLink(ctx context.Context, o openOptions, link share.Link) erro opened, err := share.Open(ctx, c, link, password, sink, bar.update) bar.finish() if err == nil { - return e.printOpened(opened, sink, o.toClipboard) + return e.printOpened(opened, sink, o.clipboard) } // A mistyped password doesn't use the secret up, but the server // counts it, and at the last one it takes deletes the secret. Ask @@ -205,8 +195,13 @@ func (e *env) confirmOpen(ctx context.Context, owner bool) error { return nil } -// linkArg takes the link from the arguments, from stdin, or from a prompt. -func (e *env) linkArg(ctx context.Context, args []string) (share.Link, error) { +// errNoLinkOnClipboard is --clipboard without a link on the clipboard. What +// is there instead may be a secret, so it is never shown. +var errNoLinkOnClipboard = errors.New("--clipboard: the clipboard holds no Secretli link") + +// linkArg takes the link from the arguments, from stdin, or from a prompt; +// with fromClipboard, from the clipboard instead of the prompt. +func (e *env) linkArg(ctx context.Context, args []string, fromClipboard bool) (share.Link, error) { raw := "" switch { case len(args) == 1: @@ -220,6 +215,16 @@ func (e *env) linkArg(ctx context.Context, args []string) (share.Link, error) { return share.Link{}, errors.New("no link given, and nothing on stdin") } raw = line + case fromClipboard: + text, err := clipboard.Paste() + if err != nil { + return share.Link{}, fmt.Errorf("--clipboard: %w", err) + } + link, err := share.ParseLink(strings.TrimSpace(text)) + if err != nil { + return share.Link{}, errNoLinkOnClipboard + } + return link, nil default: t, err := e.terminal() if err != nil { @@ -450,7 +455,7 @@ func (e *env) writeText(text []byte) error { } if changed { // Even with --quiet: what was printed is not quite the secret. - _, _ = fmt.Fprint(e.stderr, "The secret holds control characters, shown as \uFFFD; --to-clipboard, or stdout to a file or pipe, gives the exact text.\n") + _, _ = fmt.Fprint(e.stderr, "The secret holds control characters, shown as \uFFFD; --clipboard, or stdout to a file or pipe, gives the exact text.\n") } return nil } diff --git a/internal/cli/receive.go b/internal/cli/receive.go index 01d4dfc..3aac894 100644 --- a/internal/cli/receive.go +++ b/internal/cli/receive.go @@ -29,8 +29,9 @@ func newReceiveCmd(e *env) *cobra.Command { Long: `Receives a link that another device hands over with a short code, from secretli send or from "Send with a code" in the web app, and opens it like secretli open: text to stdout, files to the current directory or --out. ---link prints the link instead of opening it. --to-clipboard puts the text, -or with --link the link, on the clipboard instead, as with open. +--link prints the link instead of opening it. --clipboard puts the text, or +with --link the link, on the clipboard instead, as with open; the code is +never taken from the clipboard. A one-time secret is described and you are asked before it is opened, as with open; --yes opens it without asking. Answering no prints the link, @@ -43,7 +44,8 @@ Without an argument the code is read from stdin, or asked for at a terminal without showing it. A misspelt word is caught before the code is used.`, Example: ` secretli receive 7-acid-rocket secretli receive 7 acid rocket --out ./received - secretli receive 7-acid-rocket --link`, + secretli receive 7-acid-rocket --link + secretli receive 7-acid-rocket -c the text to the clipboard`, Args: cobra.ArbitraryArgs, ValidArgsFunction: cobra.NoFileCompletions, RunE: run(func(cmd *cobra.Command, args []string) error { @@ -51,6 +53,7 @@ without showing it. A misspelt word is caught before the code is used.`, }), } addOpenFlags(cmd, &o.openOptions) + cmd.Flags().Lookup("clipboard").Usage = "the text, or with --link the link, to the clipboard instead of the terminal" cmd.Flags().BoolVar(&o.linkOnly, "link", false, "print the link instead of opening it") return cmd } @@ -61,7 +64,7 @@ func (e *env) receive(ctx context.Context, o receiveOptions, args []string) erro if !o.yes && !o.linkOnly && !e.canAsk() { return errors.New("receive asks before it opens a one-time secret, and there is no terminal to ask on; use --yes to open it anyway, or --link to print the link") } - if err := e.checkCopy(o.openOptions); err != nil { + if err := checkClipboard(o.clipboard); err != nil { return err } server, err := share.Origin(e.server) @@ -85,7 +88,7 @@ func (e *env) receive(ctx context.Context, o receiveOptions, args []string) erro return fmt.Errorf("the code delivered a link for another server, %s; it was not opened", link.Origin) } if o.linkOnly { - if o.toClipboard { + if o.clipboard { return e.copySecret(link.String(), "the link") } return e.printLink(link) @@ -96,8 +99,6 @@ func (e *env) receive(ctx context.Context, o receiveOptions, args []string) erro switch { case errors.Is(err, errNotOpened): e.note("Not opened. Here is the link, which still works:\n") - case errors.Is(err, errCopyIsForText): - e.note("Not opened: %v. Here is the link, which still works:\n", err) default: return err } diff --git a/internal/cli/send.go b/internal/cli/send.go index cea5164..a15272a 100644 --- a/internal/cli/send.go +++ b/internal/cli/send.go @@ -16,7 +16,8 @@ import ( ) func newSendCmd(e *env) *cobra.Command { - return &cobra.Command{ + var fromClipboard bool + cmd := &cobra.Command{ Use: "send [link]", Short: "Hand a link to another device with a short code", Long: `Hands a link to another device with a short code like 7-acid-rocket, so @@ -32,12 +33,19 @@ Prints the code and waits until the link was handed over. Without an argument the link is read from stdin, or asked for at a terminal without showing it.`, Example: ` secretli send 'https://secretli.app/s#…' + secretli send -c the link from the clipboard secretli share notes.txt -q | secretli send`, Args: cobra.MaximumNArgs(1), ValidArgsFunction: cobra.NoFileCompletions, RunE: run(func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() - link, err := e.linkArg(ctx, args) + if err := checkClipboard(fromClipboard); err != nil { + return err + } + link, err := e.linkArg(ctx, args, fromClipboard) + if errors.Is(err, errNoLinkOnClipboard) { + return fmt.Errorf("%w; to hand over the clipboard's text, use secretli share -c --code", err) + } if err != nil { return err } @@ -47,6 +55,8 @@ showing it.`, return e.handOver(ctx, link.Recipient(), nil) }), } + cmd.Flags().BoolVarP(&fromClipboard, "clipboard", "c", false, "take the link from the clipboard instead of asking for it") + return cmd } // handOver sends a link with a code and waits until it was handed over. diff --git a/internal/cli/share.go b/internal/cli/share.go index e4ee541..d0e9991 100644 --- a/internal/cli/share.go +++ b/internal/cli/share.go @@ -26,8 +26,7 @@ type shareOptions struct { reusable bool password bool qr bool - copyLink bool - fromClipboard bool + clipboard bool code bool } @@ -40,22 +39,28 @@ func newShareCmd(e *env) *cobra.Command { to hand out, and the owner link, which can delete the secret and, for a reusable one, tell whether it has been opened. -Files are given as arguments. Text comes from stdin, from --text, from the -clipboard with --from-clipboard, or, at a terminal, from a prompt, which -keeps it out of your shell history. "-" shares stdin as a file named by ---name, and --name with --from-clipboard shares the clipboard as a file. +Files are given as arguments. Text comes from stdin, from --text, or, at a +terminal, from a prompt, which keeps it out of your shell history. "-" +shares stdin as a file named by --name. + +--clipboard uses the clipboard instead of the terminal: at a terminal, with +no files and no --text, it shares the clipboard's text instead of asking +for it (with --name, as a file), and it puts the link on the clipboard +instead of printing it. The clipboard is cleared 45 seconds later. With +--code the code is still printed, since it is there to be read and typed. Links open once unless --reusable is set, and expire after a day unless --expires says otherwise. --code hands the link to another device with a short code instead of printing it, as secretli send does.`, Example: ` secretli share type or paste, then Ctrl-D pbpaste | secretli share text from a pipe - secretli share --from-clipboard -c the clipboard's text in, the link out + secretli share -c the clipboard's text in, the link out secretli share -t "hunter2" text as an argument (lands in shell history) secretli share deploy.key notes.pdf files pg_dump db | gzip | secretli share --name db.sql.gz secretli share report.pdf -e 4h --reusable -p --qr - secretli share deploy.key --code hand it over with a code like 7-acid-rocket`, + secretli share deploy.key --code hand it over with a code like 7-acid-rocket + secretli share -c --code the clipboard's text, handed over with a code`, Args: cobra.ArbitraryArgs, RunE: run(func(cmd *cobra.Command, args []string) error { return e.share(cmd.Context(), o, args) @@ -70,8 +75,7 @@ short code instead of printing it, as secretli send does.`, f.BoolVarP(&o.password, "password", "p", false, "protect the secret with a password (asked for, or SECRETLI_PASSWORD)") f.StringVar(&o.passwordFile, "password-file", "", "read the password from the first line of this file") f.BoolVar(&o.qr, "qr", false, "show the link as a QR code too") - f.BoolVarP(&o.copyLink, "copy-link", "c", false, "copy the link to the clipboard; cleared after 45 seconds") - f.BoolVar(&o.fromClipboard, "from-clipboard", false, "share the clipboard's text, without its final line break") + f.BoolVarP(&o.clipboard, "clipboard", "c", false, "the clipboard instead of the terminal: share its text, put the link on it") f.BoolVar(&o.code, "code", false, "hand the link to another device with a short code instead of printing it") return cmd } @@ -80,8 +84,13 @@ func (e *env) share(ctx context.Context, o shareOptions, args []string) error { if !share.ValidExpiration(o.expires) { return fmt.Errorf("--expires must be one of %s", strings.Join(share.Expirations, ", ")) } - if o.code && (o.qr || o.copyLink) { - return errors.New("--code hands the link over itself; leave out --qr and --copy-link") + if o.code && o.qr { + return errors.New("--code hands the link over itself; leave out --qr") + } + if o.clipboard { + if err := clipboard.Available(); err != nil { + return fmt.Errorf("--clipboard: %w", err) + } } // Before anything is read or uploaded: the link has to be one that // opens, which rules out http to another machine. @@ -89,9 +98,6 @@ func (e *env) share(ctx context.Context, o shareOptions, args []string) error { if err != nil { return err } - if o.fromClipboard && (o.text != "" || len(args) > 0) { - return errors.New("--from-clipboard shares the clipboard; leave out --text and files") - } params := share.Params{Expiration: o.expires, Reusable: o.reusable} var closers []io.Closer @@ -127,7 +133,9 @@ func (e *env) share(ctx context.Context, o shareOptions, args []string) error { switch { case o.text != "": params.Text = []byte(o.text) - case o.fromClipboard: + case o.clipboard && e.stdinTTY: + // The clipboard stands in for the prompt; a pipe or a file on + // stdin is still what is shared. data, err := pasteSecret() if err != nil { return err @@ -212,17 +220,18 @@ func (e *env) readStdin(ctx context.Context) ([]byte, error) { return data, nil } -// pasteSecret reads the clipboard for --from-clipboard. It drops one final line -// break, which a paste tool may add of its own and open --to-clipboard leaves off, -// so that what --from-clipboard shares, open --to-clipboard gives back. +// pasteSecret reads the clipboard for share --clipboard. It drops one final +// line break, which a paste tool may add of its own and open --clipboard +// leaves off, so that what share --clipboard shares, open --clipboard gives +// back. func pasteSecret() ([]byte, error) { text, err := clipboard.Paste() if err != nil { - return nil, fmt.Errorf("--from-clipboard: %w", err) + return nil, fmt.Errorf("--clipboard: %w", err) } text = withoutFinalLineBreak(text) if text == "" { - return nil, errors.New("--from-clipboard: the clipboard holds no text") + return nil, errors.New("--clipboard: the clipboard holds no text") } return []byte(text), nil } @@ -265,10 +274,15 @@ func (e *env) printShared(r *share.Result, o shareOptions) error { e.note("Couldn't draw the QR code: %v\n", err) } } - if o.copyLink { - // The link is printed below anyway, so a failure needs no stand-in. + // With the link on the clipboard, it is not printed as well; the owner + // link is, as it exists nowhere else. Should copying fail, the link is + // printed as usual. + copied := false + if o.clipboard { if err := e.copyAndClear(link, "the link"); err != nil { - e.note("Couldn't copy to the clipboard: %v\n", err) + e.note("Couldn't copy to the clipboard (%v), so here it is.\n", err) + } else { + copied = true } } if e.json { @@ -277,12 +291,18 @@ func (e *env) printShared(r *share.Result, o shareOptions) error { summary := shareSummary(r) if e.quiet || !e.stdoutTTY { - _, _ = fmt.Fprintln(e.stdout, link) + if !copied { + _, _ = fmt.Fprintln(e.stdout, link) + } if !e.quiet { _, _ = fmt.Fprintf(e.stderr, "%s\n%s\n%s\n", summary, ownerNote(r), r.Link.String()) } return nil } + if copied { + _, _ = fmt.Fprintf(e.stdout, "Your link is on the clipboard. %s\n\n%s\n\n %s\n", summary, ownerNote(r), r.Link.String()) + return nil + } _, _ = fmt.Fprintf(e.stdout, "Your link is ready. %s\n\n %s\n\n%s\n\n %s\n", summary, link, ownerNote(r), r.Link.String()) return nil } diff --git a/internal/cli/status.go b/internal/cli/status.go index 9e03ae5..a7f0a6d 100644 --- a/internal/cli/status.go +++ b/internal/cli/status.go @@ -12,6 +12,7 @@ import ( ) func newStatusCmd(e *env) *cobra.Command { + var fromClipboard bool cmd := &cobra.Command{ Use: "status [link]", Short: "Say what a link points to, without opening it", @@ -24,13 +25,15 @@ about it, so status says only that it is gone, as it does for a link to nothing. The exit code is 4 then, so scripts can tell, and with --json the state is always live or gone.`, Example: ` secretli status 'https://secretli.app/s#…!…' - secretli status "$LINK" --json | jq -r .state`, + secretli status "$LINK" --json | jq -r .state + secretli status -c the link from the clipboard`, Args: cobra.MaximumNArgs(1), ValidArgsFunction: cobra.NoFileCompletions, RunE: run(func(cmd *cobra.Command, args []string) error { - return e.status(cmd.Context(), args) + return e.status(cmd.Context(), args, fromClipboard) }), } + cmd.Flags().BoolVarP(&fromClipboard, "clipboard", "c", false, "take the link from the clipboard instead of asking for it") return cmd } @@ -39,8 +42,11 @@ type exitWith struct{ code int } func (x *exitWith) Error() string { return "" } -func (e *env) status(ctx context.Context, args []string) error { - link, err := e.linkArg(ctx, args) +func (e *env) status(ctx context.Context, args []string, fromClipboard bool) error { + if err := checkClipboard(fromClipboard); err != nil { + return err + } + link, err := e.linkArg(ctx, args, fromClipboard) if err != nil { return err } diff --git a/internal/cli/terminal_test.go b/internal/cli/terminal_test.go index b00e07f..9176916 100644 --- a/internal/cli/terminal_test.go +++ b/internal/cli/terminal_test.go @@ -572,3 +572,109 @@ func TestTerminalCtrlCDuringADownload(t *testing.T) { t.Errorf("the progress line was not cleared before the error; the terminal was sent %q", raw) } } + +// At a terminal, --clipboard stands in for it: what would be typed comes +// from the clipboard, what would be read goes there, and neither shows. +// This is the way across: share -c --code on one computer, receive +// -c on the other. +func TestTerminalClipboard(t *testing.T) { + srv := fakeServer(t) + server := "--server=" + srv.URL + dir := t.TempDir() + write := func(path, text string) { + t.Helper() + if err := os.WriteFile(path, []byte(text), 0o600); err != nil { + t.Fatal(err) + } + } + read := func(path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) + } + at := func(clip string, args ...string) *atTerminal { + t.Helper() + return startAtTerminalWith(t, terminalSetup{env: []string{testClipboard + "=" + clip}}, args...) + } + clipA, clipB := filepath.Join(dir, "a"), filepath.Join(dir, "b") + + // Computer A: the clipboard's text, handed over with a code, which is + // shown, since it is there to be typed. Nothing asks for the secret. + write(clipA, "hunter2\n") + a := at(clipA, "share", "-c", "--code", server) + a.expect("Waiting for the other device.") + m := regexp.MustCompile(`secretli receive (\S+)`).FindStringSubmatch(a.screen()) + if m == nil { + t.Fatalf("no code; the terminal shows:\n%s", a.screen()) + } + if strings.Contains(a.screen(), "Type or paste") || strings.Contains(a.screen(), "hunter2") { + t.Errorf("share asked for or showed the secret:\n%s", a.screen()) + } + + // Computer B: the code is typed, never taken from the clipboard, and + // the secret goes onto the clipboard. + write(clipB, "7-acid-rocket") + b := at(clipB, "receive", m[1], "-c", server) + b.expect("[y/N] ") + b.typ("y\r") + b.expect("Copied the secret to the clipboard") + if code := b.exitCode(); code != 0 { + t.Fatalf("receive: exit %d; the terminal shows:\n%s", code, b.screen()) + } + if code := a.exitCode(); code != 0 { + t.Fatalf("share: exit %d; the terminal shows:\n%s", code, a.screen()) + } + if got := read(clipB); got != "hunter2" { + t.Errorf("clipboard on B = %q", got) + } + if strings.Contains(b.screen(), "hunter2") { + t.Errorf("receive showed the secret:\n%s", b.screen()) + } + + // share -c and open -c on one computer: the link goes on the clipboard + // instead of the screen, and open takes it from there instead of asking. + write(clipA, "round trip") + a = at(clipA, "share", "-c", server) + a.expect("Your link is on the clipboard.") + if code := a.exitCode(); code != 0 { + t.Fatalf("share -c: exit %d; the terminal shows:\n%s", code, a.screen()) + } + // The owner link, printed as ever, begins with it; the link to hand out + // is not printed on a line of its own. + link := read(clipA) + if !strings.Contains(link, "/s#") || strings.Contains(a.screen(), link+"\r\n") { + t.Errorf("clipboard %q; the terminal shows:\n%s", link, a.screen()) + } + o := at(clipA, "open", "-c") + o.expect("[y/N] ") + o.typ("y\r") + o.expect("Copied the secret to the clipboard") + if code := o.exitCode(); code != 0 { + t.Fatalf("open -c: exit %d; the terminal shows:\n%s", code, o.screen()) + } + if got := read(clipA); got != "round trip" { + t.Errorf("clipboard after open -c = %q", got) + } + if strings.Contains(o.screen(), "Paste the link") || strings.Contains(o.screen(), "round trip") { + t.Errorf("open asked for the link or showed the secret:\n%s", o.screen()) + } + + // A clipboard without a link: refused, and what it holds isn't shown. + write(clipA, "s3cret-not-a-link") + for _, args := range [][]string{{"open", "-c"}, {"status", "-c"}, {"delete", "-c"}, {"send", "-c"}} { + c := at(clipA, args...) + c.expect("the clipboard holds no Secretli link") + if code := c.exitCode(); code != ExitError { + t.Errorf("%v: exit %d", args, code) + } + if strings.Contains(c.screen(), "s3cret") { + t.Errorf("%v shows the clipboard:\n%s", args, c.screen()) + } + if args[0] == "send" && !strings.Contains(c.screen(), "secretli share -c --code") { + t.Errorf("send gives no hint:\n%s", c.screen()) + } + } +} diff --git a/internal/cli/transfer_test.go b/internal/cli/transfer_test.go index 14182a8..caa8008 100644 --- a/internal/cli/transfer_test.go +++ b/internal/cli/transfer_test.go @@ -165,7 +165,7 @@ func TestReceiveRefusesBadCodes(t *testing.T) { {[]string{"receive", "7-acid-rocket", server, "--yes"}, ExitGone, "no transfer with that number"}, {[]string{"receive", "acid-rocket", server, "--yes"}, ExitError, "codes look like 7-acid-rocket"}, {[]string{"receive", "7-acid-rokcet", server, "--yes"}, ExitError, `"rokcet" isn't a code word`}, - {[]string{"share", "-t", "x", "--code", "--qr", server}, ExitError, "leave out --qr and --copy-link"}, + {[]string{"share", "-t", "x", "--code", "--qr", server}, ExitError, "leave out --qr"}, } { _, stderr, code := runCLI(t, "", c.args...) if code != c.exit || !strings.Contains(stderr, c.says) { diff --git a/internal/cli/untrusted.go b/internal/cli/untrusted.go index 4b2951a..999be08 100644 --- a/internal/cli/untrusted.go +++ b/internal/cli/untrusted.go @@ -12,7 +12,7 @@ import ( // what was printed, retitle the window, show a link that leads elsewhere, // or set the clipboard. Format characters such as U+202E reverse text on // display: invoice, U+202E, txt.exe reads as invoiceexe.txt. Pipes, files, -// --to-clipboard and --json get the text as it is. +// --clipboard and --json get the text as it is. // printable is a file's name as the terminal may show it: control and // format characters, and bytes that aren't UTF-8, become '?'.