Refactor to Go standards; add print queue and own ESC/POS library
CI / Lint, test and scan (push) Successful in 1m41s
CI / Lint, test and scan (push) Successful in 1m41s
Restructure the daemon to follow the project's Go coding standards and
expand its features.
Layout and tooling
- cmd/uberbringer/main.go is now thin; all logic lives under internal/.
- Module path is git.anomalous.dev/57_Wolve/uberbringer, go 1.26, every
dependency upgraded, vendor/ removed.
- staticcheck, govulncheck and goimports pinned as go tools; add a
Makefile, CI workflow, goreleaser v2 config and Alpine Dockerfile.
Features
- Background print queue with job status (GET /api/v1/jobs/:id), send
retries with backoff, and graceful shutdown.
- New {"elements": [...]} job format on POST /api/v1/print. Breaking:
replaces {"data": [...]}, and the response is now JSON 202.
- In-house ESC/POS library replacing justinmichaelvieira/escpos: sizes
1-8, Font B, CODE39/CODE128, QR, banded raster images, DLE EOT status.
- UTF-8 text transcoded to CP437 (configurable) with word-aware wrapping.
- Images from URL or base64, scaled and dithered; URL fetches refuse
internal addresses (SSRF guard).
- Fiber v3 HTTP server, TypeID (UUIDv7) job and request IDs, /healthz
with live printer status, `secret` and `token` subcommands.
Fixes
- Jobs are validated before anything is sent; a failed printer dial no
longer panics.
- Request logs never contain tokens; Sentry no longer receives the
Authorization header or print contents.
- Rate limiting is per client behind nginx (X-Real-IP).
- install.sh writes the [printer] section, runs the service as a
dedicated user and uses a current nginx TLS config.
config.toml is no longer tracked; start from configs/config.example.toml.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bb73348433
commit
6502d9551d
807 files changed
+6659
-500291
No files matched your search
@@ -0,0 +1,165 @@
|
||||
// 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"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/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)
|
||||
}
|
||||
Reference in new issue
Block a user