Files
uberbringer/internal/app/uberbringer/cli.go
T
57_WolveandClaude Opus 5.5 9b91109550
Test / Lint, test and build (push) Successful in 3m17s
Adopt norn's CI, release, API and docs practices; bare module path
Module
- The module path is now the bare "uberbringer"; imports read
  uberbringer/internal/... The banner keeps the Gitea URL.

CI and releases
- Workflows move to .gitea/workflows: test.yml (every branch push:
  gofmt, goimports, tidy, vet, staticcheck, race tests, goreleaser
  snapshot), security.yml (govulncheck weekly and on main) and a hardened
  release.yml (v* tags on main only, tags fetched, goreleaser pinned to
  2.20.3). The broken labeler workflow is removed.
- go.mod pins toolchain go1.27.4, which fixes GO-2026-6859; workflows
  check that the running Go matches it.
- .goreleaser.yaml: tidy check that never writes, reproducible file times,
  prerelease: auto, a release header linking CHANGELOG.md, and archives
  that ship CHANGELOG.md, the example config and the systemd unit.
- Makefile mirrors the CI gate; .dockerignore is an allowlist.

API and tests
- Every error answers {"error", "code", "details"} with a stable code from
  server/errors.go; the framework's own error text is never sent.
- Panics and unexpected errors are logged and reported to Sentry once;
  refusals are not logged as failures. /healthz sends no-store.
- TestRoutesConform requires auth, rate limiting and the body limit on
  every /api/v1 route.
- Race-prone tests no longer rely on freed ports or sleeps; serve takes
  an injected listener.
- The test config uses a placeholder secret instead of a real one.

Install and packaging
- install.sh resolves the latest release through the Gitea API, verifies
  checksums, requests a certificate only when none exists, installs the
  hardened packaging/uberbringer.service and writes the first token to a
  0600 file instead of printing it. It is now executable in git.

Docs
- CLAUDE.md, CHANGELOG.md (0.2.0 with breaking changes and upgrade
  steps), docs/design.md, and docs/plans/formatters.md for the planned
  CP437 blocks, modules and ntfy printing. README updated throughout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:27:48 -06:00

166 lines
4.9 KiB
Go

// Package uberbringer wires the Überbringer daemon together and provides its
// command-line interface.
package uberbringer
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/liamg/tml"
"github.com/spf13/cobra"
"uberbringer/internal/pkg/config"
)
// Project information shown by the banner, the version command and the API
// index route.
const (
Project = "Überbringer"
Description = "EPSON Receipt Printer Server"
Authors = "https://git.anomalous.dev/57_Wolve/uberbringer"
copyright = "William Gill"
)
// secretBytes is the size of generated API secrets: 256 bits, the HS256 hash
// size.
const secretBytes = 32
// BuildInfo is injected at build time through -ldflags.
type BuildInfo struct {
Version string
Commit string
// SentryDSN is the default DSN for release builds; sentry.dsn in the
// config and the SENTRY_DSN environment variable take precedence.
SentryDSN string
}
// Execute runs the command line given by args.
func Execute(ctx context.Context, build BuildInfo, args []string) error {
root := newRootCommand(build)
root.SetArgs(args)
return root.ExecuteContext(ctx)
}
func newRootCommand(build BuildInfo) *cobra.Command {
var configPath string
root := &cobra.Command{
Use: "uberbringer",
Short: "Runs the Überbringer receipt printer daemon.",
SilenceUsage: true,
SilenceErrors: true,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return serve(cmd.Context(), configPath, build, cmd.OutOrStdout())
},
}
root.PersistentFlags().StringVarP(&configPath, "config", "c", "config.toml", "path to the daemon config file")
root.AddCommand(
newVersionCommand(build),
newSecretCommand(),
newTokenCommand(&configPath),
)
return root
}
func newVersionCommand(build BuildInfo) *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Prints the version and exits.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
_, err := fmt.Fprintln(cmd.OutOrStdout(), versionLine(build))
return err
},
}
}
func newSecretCommand() *cobra.Command {
return &cobra.Command{
Use: "secret",
Short: "Prints a new random API secret for api.secret in the config.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
_, err := fmt.Fprintln(cmd.OutOrStdout(), newSecret())
return err
},
}
}
func newTokenCommand(configPath *string) *cobra.Command {
var (
subject string
ttl time.Duration
)
cmd := &cobra.Command{
Use: "token",
Short: "Prints a bearer token signed with the config's api.secret.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load(*configPath)
if err != nil {
return err
}
token, err := signToken([]byte(cfg.API.Secret), subject, ttl, time.Now())
if err != nil {
return err
}
_, err = fmt.Fprintln(cmd.OutOrStdout(), token)
return err
},
}
cmd.Flags().StringVar(&subject, "subject", "uberbringer", "token subject, e.g. the client's name")
cmd.Flags().DurationVar(&ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
return cmd
}
// newSecret returns a random base64 API secret. crypto/rand.Read never fails
// on supported platforms; it crashes the program rather than return weak bytes.
func newSecret() string {
b := make([]byte, secretBytes)
_, _ = rand.Read(b) // documented to never return an error
return base64.StdEncoding.EncodeToString(b)
}
// signToken returns an HS256 JWT for subject. A zero ttl means no expiry.
func signToken(secret []byte, subject string, ttl time.Duration, now time.Time) (string, error) {
if ttl < 0 {
return "", fmt.Errorf("ttl must not be negative")
}
claims := jwt.RegisteredClaims{
Subject: subject,
IssuedAt: jwt.NewNumericDate(now),
}
if ttl > 0 {
claims.ExpiresAt = jwt.NewNumericDate(now.Add(ttl))
}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
if err != nil {
return "", fmt.Errorf("signing token: %w", err)
}
return signed, nil
}
func versionLine(build BuildInfo) string {
return fmt.Sprintf("%s | Version: %s Build: %s | Copyright © %d %s",
Project, build.Version, build.Commit, time.Now().Year(), copyright)
}
// printBanner writes the startup banner.
func printBanner(w io.Writer, build BuildInfo) {
const rule = "-----------------------------------------------------------------------------------------------"
// The banner is cosmetic; a failed write to the terminal is not worth
// stopping the daemon for.
_ = tml.Fprintf(w, "%s\n\n", rule)
_ = tml.Fprintf(w, "<bold> <lightblue>%s</lightblue></bold>\n\n", versionLine(build))
_ = tml.Fprintf(w, "<bold> <lightblue>Project:</lightblue> %s</bold>\n", Project)
_ = tml.Fprintf(w, "<bold> <lightblue>Description:</lightblue> %s</bold>\n", Description)
_ = tml.Fprintf(w, "<bold> <lightblue>Authors:</lightblue> %s</bold>\n\n", Authors)
_ = tml.Fprintf(w, "%s\n", rule)
}