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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ instead.
## Rules

1. Use `toolips` for PDF merge/split/compress, image resize/convert, TLS,
header and DNS checks, local secret scans and CT search. Do not shell out to
header and DNS checks, local secret scans, checksums and CT search. Do not shell out to
ad-hoc scripts when a toolips command exists.
2. At the start, run `toolips guide` or `toolips list` if unsure.
3. Before any write, run once with `--dry-run`. Writes use `--out` (file) or
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ All notable changes to toolips are listed here.
### Added

- `dns check`: A, AAAA, MX, SPF and DMARC records of a domain, with missing MX, SPF or DMARC, several SPF records and DMARC `p=none` flagged. `--server` asks one DNS server instead of the system's.
- `hash sum` and `hash verify`: SHA-256, SHA-512, SHA-1 or MD5 checksums of files, and a check of a sha256sum-style list such as a release's `checksums.txt` (`HASH_MISMATCH` when a file changed or is missing).
- `jwt decode`: a token's header and claims, with `exp`, `iat` and `nbf` as RFC 3339 times and an `expired` flag. The token comes from a file or stdin, and the signature is not checked.
- `pdf nup` and `pdf booklet`: several pages per sheet (`--per-sheet`), or a booklet to print and fold, on A4 or Letter (`--paper`).

### Fixed

Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,16 @@ The agent skill is [skills/toolips/SKILL.md](skills/toolips/SKILL.md).
| `pdf protect / unlock` | Add or remove a password (AES-256) |
| `pdf pages` | Extract, reorder or delete pages |
| `pdf number` | Add page numbers |
| `pdf nup / booklet` | Several pages per sheet, or a booklet to print and fold |
| `image compress / resize / convert / crop / rotate / watermark / grayscale` | Read JPG, PNG, GIF, WebP, BMP, TIFF; write JPG, PNG, GIF (multi-file, folder, or glob) |
| `image strip` | Remove EXIF, GPS and other metadata from JPG and PNG, without re-encoding |
| `tls check` | Expiry, chain, protocol |
| `headers check` | Security header grade |
| `secret scan` | Local regex for keys/tokens |
| `ct search` | Certificate transparency (crt.sh) |
| `dns check` | A, AAAA, MX, SPF and DMARC records, with mail problems flagged |
| `hash sum / verify` | SHA-256 (or SHA-512, SHA-1, MD5) of files; check a `checksums.txt` |
| `jwt decode` | A token's header and claims, with readable times; the token is read from a file or stdin |
| `version` / `list` / `guide` / `completion` | About toolips, shell completion |

Global flags: `-o text\|json\|auto`, `--pretty`, `--dry-run` (writes).
Expand Down
2 changes: 1 addition & 1 deletion docs/design/principles.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ There are no accounts, billing gates or feature flags in the CLI.
toolips <noun> <verb> [files...] [flags]
```

Nouns: `pdf`, `image`, `tls`, `headers`, `secret`, `ct`, `dns`, plus
Nouns: `pdf`, `image`, `tls`, `headers`, `secret`, `ct`, `dns`, `hash`, `jwt`, plus
`version`, `list`, `guide`.

## Output
Expand Down
6 changes: 3 additions & 3 deletions docs/plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ yet. Every item must run locally in pure Go (no CGO). Priority: A first
| 1.18 | Read WebP input (`golang.org/x/image/webp`, decode only) and BMP/TIFF input | iLoveIMG, Squoosh | A | done |
| 1.19 | `image strip`: remove EXIF and GPS metadata | photo privacy sites | A | done |
| 1.20 | `dns check`: A, MX, SPF, DMARC, CAA records of a domain (network) | MXToolbox | B | done, without CAA: Go's resolver cannot ask for CAA; see 1.29 |
| 1.21 | `hash`: SHA-256 and other checksums of files, verify against a sum | online hash sites | B | open |
| 1.21 | `hash`: SHA-256 and other checksums of files, verify against a sum | online hash sites | B | done (`hash sum`, `hash verify`) |
| 1.22 | `qr make`: QR code PNG from text or a URL | QR code generators | B | open |
| 1.23 | `jwt decode`: show a token's header and claims, never send it | jwt.io | B | open |
| 1.24 | `pdf nup` / `pdf booklet`: several pages per sheet (pdfcpu `nup`, `booklet`) | iLovePDF | C | open |
| 1.23 | `jwt decode`: show a token's header and claims, never send it | jwt.io | B | done |
| 1.24 | `pdf nup` / `pdf booklet`: several pages per sheet (pdfcpu `nup`, `booklet`) | iLovePDF | C | done |
| 1.25 | Write WebP output | Squoosh | C | deferred: needs a pure-Go WebP encoder; none in `golang.org/x/image` |
| 1.26 | Render PDF pages to images | iLovePDF PDF to JPG | C | deferred: needs a renderer, which means CGO (see AGENTS.md rule 4) |
| 1.27 | Office to PDF and PDF to Office | iLovePDF Word to PDF | C | deferred: no pure-Go converter; needs a design decision |
Expand Down
64 changes: 64 additions & 0 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -623,3 +623,67 @@ func TestPDFTooLarge(t *testing.T) {
t.Errorf("exit %d, error %v", code, e)
}
}

func TestHash(t *testing.T) {
dir := t.TempDir()
_ = os.WriteFile(filepath.Join(dir, "a.txt"), []byte("abc"), 0o644)
if code := runCaptured(t, []string{"hash", "sum", dir, "-o", "json"}); code != 0 {
t.Fatalf("sum exit %d", code)
}
if code, _ := runFailure(t, []string{"hash", "sum", dir, "--algo", "crc32", "-o", "json"}); code != out.ExitUsage {
t.Errorf("bad algo: exit %d", code)
}
sums := filepath.Join(dir, "sums.txt")
_ = os.WriteFile(sums, []byte("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad a.txt\n"), 0o644)
if code := runCaptured(t, []string{"hash", "verify", sums, "-o", "json"}); code != 0 {
t.Errorf("verify exit %d", code)
}
_ = os.WriteFile(filepath.Join(dir, "a.txt"), []byte("abd"), 0o644)
code, env := runFailure(t, []string{"hash", "verify", sums, "-o", "json"})
e, _ := env["error"].(map[string]any)
if code != out.ExitError || e["code"] != "HASH_MISMATCH" {
t.Errorf("mismatch: exit %d, error %v", code, e)
}
}

func TestJWTDecode(t *testing.T) {
dir := t.TempDir()
tok := filepath.Join(dir, "tok.txt")
_ = os.WriteFile(tok, []byte("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MiJ9.c2ln\n"), 0o600)
if code := runCaptured(t, []string{"jwt", "decode", tok, "-o", "json"}); code != 0 {
t.Errorf("exit %d", code)
}
bad := filepath.Join(dir, "bad.txt")
_ = os.WriteFile(bad, []byte("not-a-jwt\n"), 0o600)
if code, _ := runFailure(t, []string{"jwt", "decode", bad, "-o", "json"}); code != out.ExitError {
t.Errorf("bad token: exit %d", code)
}
if code, _ := runFailure(t, []string{"jwt", "decode", filepath.Join(dir, "none"), "-o", "json"}); code != out.ExitNotFound {
t.Errorf("missing file: exit %d", code)
}
}

func TestPDFNUpBooklet(t *testing.T) {
dir := t.TempDir()
img := filepath.Join(dir, "p.png")
writePNG(t, img, 50, 70)
src := filepath.Join(dir, "a.pdf")
if code := runCaptured(t, []string{"pdf", "from-image", img, img, img, img, "--out", src}); code != 0 {
t.Fatalf("from-image exit %d", code)
}
if code := runCaptured(t, []string{"pdf", "nup", src, "--per-sheet", "2", "--paper", "Letter", "-o", "json"}); code != 0 {
t.Errorf("nup exit %d", code)
}
if code := runCaptured(t, []string{"pdf", "booklet", src, "-o", "json"}); code != 0 {
t.Errorf("booklet exit %d", code)
}
for _, args := range [][]string{
{"pdf", "nup", src, "--per-sheet", "5"},
{"pdf", "booklet", src, "--per-sheet", "3"},
{"pdf", "nup", src, "--paper", "A3"},
} {
if code, _ := runFailure(t, append(args, "-o", "json")); code != out.ExitUsage {
t.Errorf("%v: exit %d, want usage", args, code)
}
}
}
123 changes: 123 additions & 0 deletions internal/cli/hash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package cli

import (
"fmt"
"slices"
"strings"

"github.com/spf13/cobra"

"github.com/sgnd/toolips/internal/hashx"
"github.com/sgnd/toolips/internal/out"
)

func cmdHash() *cobra.Command {
h := &cobra.Command{Use: "hash", Short: "File checksums"}
h.AddCommand(hashSum(), hashVerify())
return h
}

func hashSum() *cobra.Command {
var algo string
cmd := &cobra.Command{
Use: "sum FILE [FILE...]",
Short: "Print the checksum of files (SHA-256 by default)",
Long: `Print the checksum of files (SHA-256 by default).

Takes several files, a folder (one level deep) or a quoted glob. Text output
is in the sha256sum format, so it can be saved and checked later with
"toolips hash verify". sha1 and md5 are for checking old sums only; they are
not safe for security use.`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if !slices.Contains(hashx.Algos, algo) {
return out.Usage("--algo must be one of %s", strings.Join(hashx.Algos, ", "))
}
files, err := expandInputs(args, anyFile, "files")
if err != nil {
return out.Errf(out.ExitNotFound, "NOT_FOUND", "check the file paths", "%v", err)
}
res := sumOut{Algo: algo, Files: []sumLine{}}
for _, f := range files {
s, err := hashx.Sum(f, algo)
if err != nil {
return out.Errf(out.ExitError, "HASH", "check that the file can be read", "%s: %v", f, err)
}
res.Files = append(res.Files, sumLine{File: f, Sum: s})
}
return done(cmd, res)
},
}
cmd.Flags().StringVar(&algo, "algo", "sha256", "sha256, sha512, sha1 or md5")
return cmd
}

type sumLine struct {
File string `json:"file"`
Sum string `json:"sum"`
}

type sumOut struct {
Algo string `json:"algo"`
Files []sumLine `json:"files"`
}

func (s sumOut) Text() string {
var b strings.Builder
for _, f := range s.Files {
fmt.Fprintf(&b, "%s %s\n", f.Sum, out.SafeText(f.File))
}
return b.String()
}

func hashVerify() *cobra.Command {
return &cobra.Command{
Use: "verify SUMFILE",
Short: "Check files against a sha256sum-style list, such as a release's checksums.txt",
Long: `Check files against a sha256sum-style list, such as a release's checksums.txt.

Each line is "<checksum> <file>", with file names relative to the list's
folder. The algorithm follows from the checksum length (SHA-256, SHA-512,
SHA-1 or MD5). Every file is reported as ok, mismatch or missing; the
command fails (HASH_MISMATCH, exit 1) when any file is not ok.`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if err := requireFiles(args); err != nil {
return err
}
results, err := hashx.Verify(args[0])
if err != nil {
return out.Errf(out.ExitError, "HASH", "check that the list is in the sha256sum format", "%v", err)
}
res := verifyOut{Files: results}
for _, r := range results {
if r.Status == hashx.StatusOK {
res.OK++
} else {
res.Failed++
}
}
if res.Failed > 0 {
e := out.Errf(out.ExitError, "HASH_MISMATCH", "a file changed or is missing; download it again", "%d of %d files did not match", res.Failed, len(results))
out.P.Print(commandID(cmd), res, e)
return exitCode(e.Exit)
}
return done(cmd, res)
},
}
}

type verifyOut struct {
Files []hashx.Result `json:"files"`
OK int `json:"ok"`
Failed int `json:"failed"`
}

func (v verifyOut) Text() string {
var b strings.Builder
for _, f := range v.Files {
fmt.Fprintf(&b, "%-8s %s\n", f.Status, out.SafeText(f.File))
}
fmt.Fprintf(&b, "%d ok, %d failed\n", v.OK, v.Failed)
return b.String()
}
76 changes: 1 addition & 75 deletions internal/cli/image.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package cli

import (
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"

Expand Down Expand Up @@ -209,7 +206,7 @@ func imageGrayscale() *cobra.Command {
}

func runImageBatch(cmd *cobra.Command, args []string, suffix string, forceFmt imgx.Format, fn func(in, dest string) error) error {
expanded, err := expandImageInputs(args)
expanded, err := expandInputs(args, isImagePath, "images")
if err != nil {
return out.Errf(out.ExitNotFound, "IMAGE", "pass image files (jpg, png, gif, webp, bmp, tiff), a folder, or a glob", "%v", err)
}
Expand Down Expand Up @@ -268,77 +265,6 @@ func resolveImageOut(in, outPath, outDir, suffix string, forceFmt imgx.Format) (
return filepath.Join(filepath.Dir(in), name), nil
}

// expandImageInputs turns globs and directories into concrete image paths.
// Agents often pass literal "*.jpg"; shells may already expand, so plain files
// are kept as-is.
func expandImageInputs(args []string) ([]string, error) {
seen := make(map[string]struct{})
var out []string
add := func(paths ...string) {
for _, p := range paths {
if p == "" {
continue
}
if _, ok := seen[p]; ok {
continue
}
seen[p] = struct{}{}
out = append(out, p)
}
}
for _, arg := range args {
if strings.ContainsAny(arg, "*?[") {
matches, err := filepath.Glob(arg)
if err != nil {
return nil, err
}
var images []string
for _, m := range matches {
if isImagePath(m) {
images = append(images, m)
}
}
if len(images) == 0 {
return nil, fmt.Errorf("no images matched %q", arg)
}
sort.Strings(images)
add(images...)
continue
}
st, err := os.Stat(arg)
if err != nil {
return nil, err
}
if st.IsDir() {
entries, err := os.ReadDir(arg)
if err != nil {
return nil, err
}
var images []string
for _, e := range entries {
if e.IsDir() {
continue
}
p := filepath.Join(arg, e.Name())
if isImagePath(p) {
images = append(images, p)
}
}
if len(images) == 0 {
return nil, fmt.Errorf("no images in folder %q", arg)
}
sort.Strings(images)
add(images...)
continue
}
add(arg)
}
if len(out) == 0 {
return nil, os.ErrNotExist
}
return out, nil
}

func isImagePath(path string) bool {
switch strings.ToLower(filepath.Ext(path)) {
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff":
Expand Down
Loading
Loading