| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package clipboard |
| 9 |
|
| 10 |
import ( |
| 11 |
"context" |
| 12 |
"encoding/base64" |
| 13 |
"fmt" |
| 14 |
"os/exec" |
| 15 |
"strings" |
| 16 |
) |
| 17 |
|
| 18 |
var ( |
| 19 |
pasteCmdArgs = "pbpaste" |
| 20 |
copyCmdArgs = "pbcopy" |
| 21 |
osascriptPath = "osascript" |
| 22 |
) |
| 23 |
|
| 24 |
func readAll(ctx context.Context) ([]byte, error) { |
| 25 |
pasteCmd := exec.CommandContext(ctx, pasteCmdArgs) |
| 26 |
out, err := pasteCmd.Output() |
| 27 |
if err != nil { |
| 28 |
return nil, err |
| 29 |
} |
| 30 |
|
| 31 |
return out, nil |
| 32 |
} |
| 33 |
|
| 34 |
func writeAll(ctx context.Context, text []byte, secret bool) error { |
| 35 |
if secret { |
| 36 |
|
| 37 |
|
| 38 |
if err := copyViaOsascript(ctx, string(text)); err == nil { |
| 39 |
return nil |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
copyCmd := exec.CommandContext(ctx, copyCmdArgs) |
| 45 |
in, err := copyCmd.StdinPipe() |
| 46 |
if err != nil { |
| 47 |
return err |
| 48 |
} |
| 49 |
|
| 50 |
if err := copyCmd.Start(); err != nil { |
| 51 |
return err |
| 52 |
} |
| 53 |
if _, err := in.Write(text); err != nil { |
| 54 |
return err |
| 55 |
} |
| 56 |
if err := in.Close(); err != nil { |
| 57 |
return err |
| 58 |
} |
| 59 |
|
| 60 |
return copyCmd.Wait() |
| 61 |
} |
| 62 |
|
| 63 |
func copyViaOsascript(ctx context.Context, password string) error { |
| 64 |
|
| 65 |
=] |
| 66 |
|
| 67 |
b64 := base64.StdEncoding.EncodeToString([]byte(password)) |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
script := fmt.Sprintf(`use framework "Foundation" |
| 74 |
use scripting additions |
| 75 |
set pw to do shell script "printf '%%s' '%s' | base64 -D" |
| 76 |
set type to current application's NSPasteboardTypeString |
| 77 |
set pb to current application's NSPasteboard's generalPasteboard() |
| 78 |
pb's clearContents() |
| 79 |
pb's setString:"" forType:"org.nspasteboard.ConcealedType" |
| 80 |
pb's setString:pw forType:type |
| 81 |
`, b64) |
| 82 |
|
| 83 |
cmd := exec.CommandContext(ctx, osascriptPath, "-") |
| 84 |
cmd.Stdin = strings.NewReader(script) |
| 85 |
|
| 86 |
out, err := cmd.Output() |
| 87 |
if err != nil { |
| 88 |
return fmt.Errorf("osascript: %w", err) |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
if string(out) != "true\n" { |
| 94 |
return fmt.Errorf("osascript failed to set password: %s", string(out)) |
| 95 |
} |
| 96 |
|
| 97 |
return nil |
| 98 |
} |
| 99 |
|
| 100 |
func unsupported() bool { |
| 101 |
return false |
| 102 |
} |