Breaking: a job with a raw element prints only with a token issued with uberbringer token --raw. Every other token, every existing one included, gets 403 token_scope for it, with the raw elements in details, and keeps every other route. The notify module prints a notification card from a title, message, priority and tags, with topic, click, up to three actions, image, markdown and time as options; it decodes strictly and refuses a payload over its length caps. The ntfy module takes one ntfy message as ntfy sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does not know, cuts text over the caps, and answers 204 for other events and binary bodies. Both print every message plain: one message cannot tell the first of a sequence from a replacement, since a publisher may choose the sequence ID. internal/pkg/ntfy holds ntfy's message types. Both print the same card. The priority picks the form: a dark URGENT rule and a double box, a double box headed HIGH, a single box with the title in its border, or a rule with no box. Tags print as markers in front of the title, the rest on a Tags row; links print as QR codes with their labels; attached PNG, JPEG, GIF and WebP images print after the card. A line-level markdown subset is laid out without a dependency, keeping marks inside code spans and URLs, and emoji are removed after a few typed ones become markers. A card that cannot be laid out prints as a plain receipt, and the server logs the fault once at ERROR and reports it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the markers table is a setting with the user's own keys, also settable as UBERBRINGER_NTFY_MARKERS=name=value,... uberbringer token --modules issues a token limited to those modules' print and preview routes, job status and the module list; each route in the table says which tokens it takes, and a scope claim that could read as absent makes the token invalid. image elements take optional, which also shrinks a too-wide image to the paper; a QR code that could be too wide for the paper prints with smaller modules; box takes title_bold. Submit takes a Meta whose source shows in job status and, with a copy of the request ID, in every worker log line of the job. The four ntfy cards passed on the TM-T88IV, posted as the client recipe posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md describes the modules, the card and the client recipe, with tokens read from a header file; docs/swagger.json is regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
158 lines
6.5 KiB
Go
158 lines
6.5 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"runtime/debug"
|
|
"strconv"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/gofiber/fiber/v3/middleware/requestid"
|
|
)
|
|
|
|
// errorCode is a stable, machine-readable error identifier together with its
|
|
// HTTP status and the message sent when no more specific one is given.
|
|
// Clients match on code; the message is for people and may change.
|
|
type errorCode struct {
|
|
status int
|
|
code string
|
|
message string
|
|
}
|
|
|
|
// The codes the API answers with.
|
|
var (
|
|
codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"}
|
|
codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"}
|
|
codeInvalidPayload = errorCode{fiber.StatusBadRequest, "invalid_payload", "invalid payload"}
|
|
codeInvalidQuery = errorCode{fiber.StatusBadRequest, "invalid_query", "invalid query parameter"}
|
|
codeUnknownPrinter = errorCode{fiber.StatusBadRequest, "unknown_printer", "unknown printer"}
|
|
codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"}
|
|
codeTokenScope = errorCode{fiber.StatusForbidden, "token_scope", "the token does not allow this request"}
|
|
codeNotFound = errorCode{fiber.StatusNotFound, "not_found", "not found"}
|
|
codeJobNotFound = errorCode{fiber.StatusNotFound, "job_not_found", "job not found"}
|
|
codeModuleNotFound = errorCode{fiber.StatusNotFound, "module_not_found", "module not found"}
|
|
codeMethodNotAllowed = errorCode{fiber.StatusMethodNotAllowed, "method_not_allowed", "method not allowed"}
|
|
codeRequestTimeout = errorCode{fiber.StatusRequestTimeout, "request_timeout", "request was not received in time"}
|
|
codeBodyTooLarge = errorCode{fiber.StatusRequestEntityTooLarge, "body_too_large", "request body is too large"}
|
|
codeRateLimited = errorCode{fiber.StatusTooManyRequests, "rate_limited", "too many requests, try again later"}
|
|
codeHeadersTooLarge = errorCode{fiber.StatusRequestHeaderFieldsTooLarge, "headers_too_large", "request headers are too large"}
|
|
codeTooManyLines = errorCode{fiber.StatusUnprocessableEntity, "too_many_lines", "receipt would print too many lines"}
|
|
codeModuleFailed = errorCode{fiber.StatusUnprocessableEntity, "module_failed", "module built an invalid receipt"}
|
|
codeInternal = errorCode{fiber.StatusInternalServerError, "internal_error", "internal server error"}
|
|
codeNotImplemented = errorCode{fiber.StatusNotImplemented, "not_implemented", "not implemented"}
|
|
codeQueueFull = errorCode{fiber.StatusServiceUnavailable, "queue_full", "print queue is full, try again shortly"}
|
|
codeShuttingDown = errorCode{fiber.StatusServiceUnavailable, "shutting_down", "server is shutting down"}
|
|
)
|
|
|
|
// fiberCodes are the codes for the statuses Fiber and fasthttp answer with on
|
|
// their own, e.g. for an unknown route or a body over the limit.
|
|
var fiberCodes = []errorCode{
|
|
codeBadRequest, codeNotFound, codeMethodNotAllowed, codeRequestTimeout, codeBodyTooLarge,
|
|
codeRateLimited, codeHeadersTooLarge, codeInternal, codeNotImplemented,
|
|
}
|
|
|
|
// fiberCode returns the code for a status Fiber raised itself, or http_<status>
|
|
// for one without its own code.
|
|
func fiberCode(status int) errorCode {
|
|
for _, c := range fiberCodes {
|
|
if c.status == status {
|
|
return c
|
|
}
|
|
}
|
|
return errorCode{status, "http_" + strconv.Itoa(status), http.StatusText(status)}
|
|
}
|
|
|
|
// withMessage returns c with message in place of its default message.
|
|
func (c errorCode) withMessage(message string) errorCode {
|
|
c.message = message
|
|
return c
|
|
}
|
|
|
|
// apiError is a refusal: an answer the client caused or has to wait out. It
|
|
// is sent with its code and is not logged as a failure.
|
|
type apiError struct {
|
|
errorCode
|
|
details []string
|
|
}
|
|
|
|
func newAPIError(code errorCode, details ...string) *apiError {
|
|
return &apiError{errorCode: code, details: details}
|
|
}
|
|
|
|
func (e *apiError) Error() string { return e.message }
|
|
|
|
// errorResponse is the JSON body of every error.
|
|
type errorResponse struct {
|
|
// Error says what went wrong, for people. It may change.
|
|
Error string `json:"error"`
|
|
// Code is stable and meant for clients to match on.
|
|
Code string `json:"code"`
|
|
// Details lists every problem when a job fails validation (invalid_job),
|
|
// a module payload is invalid (invalid_payload) or a module builds an
|
|
// invalid receipt (module_failed). A job problem names the element by
|
|
// its path, e.g. elements[0].children[3] (qr); a payload problem names
|
|
// the field, e.g. done[0].
|
|
Details []string `json:"details,omitempty"`
|
|
}
|
|
|
|
// panicError carries a value recovered from a panic in a handler.
|
|
type panicError struct{ value any }
|
|
|
|
func (e *panicError) Error() string { return fmt.Sprintf("panic: %v", e.value) }
|
|
|
|
// handleError is the Fiber error handler: it answers every error with an
|
|
// errorResponse. Refusals, the server's own and Fiber's, are expected, so the
|
|
// request line is their only log. Any other error is a failure the server
|
|
// did not expect; it is logged and reported to Sentry here, once. Fiber's own
|
|
// message is never sent, since it can quote bytes of the request.
|
|
func (s *Server) handleError(c fiber.Ctx, err error) error {
|
|
var (
|
|
panicErr *panicError
|
|
apiErr *apiError
|
|
fiberErr *fiber.Error
|
|
)
|
|
switch {
|
|
case errors.As(err, &panicErr):
|
|
// reportPanic has already logged and reported it.
|
|
apiErr = newAPIError(codeInternal)
|
|
case errors.As(err, &apiErr):
|
|
case errors.As(err, &fiberErr):
|
|
apiErr = newAPIError(fiberCode(fiberErr.Code))
|
|
default:
|
|
s.logger.LogAttrs(c.Context(), slog.LevelError, "request failed",
|
|
slog.String("method", c.Method()),
|
|
slog.String("path", c.Path()),
|
|
slog.String("request_id", requestid.FromContext(c)),
|
|
slog.Any("err", err),
|
|
)
|
|
hubFrom(c).CaptureException(err)
|
|
apiErr = newAPIError(codeInternal)
|
|
}
|
|
return c.Status(apiErr.status).JSON(errorResponse{
|
|
Error: apiErr.message,
|
|
Code: apiErr.code,
|
|
Details: apiErr.details,
|
|
})
|
|
}
|
|
|
|
// reportPanic logs a recovered panic with its stack and reports it to Sentry.
|
|
// The recover middleware calls it from its deferred function, before the
|
|
// stack unwinds, so both show where the panic happened.
|
|
func (s *Server) reportPanic(c fiber.Ctx, r any) {
|
|
s.logger.LogAttrs(c.Context(), slog.LevelError, "panic",
|
|
slog.String("method", c.Method()),
|
|
slog.String("path", c.Path()),
|
|
slog.String("request_id", requestid.FromContext(c)),
|
|
slog.String("panic", fmt.Sprint(r)),
|
|
slog.String("stack", string(debug.Stack())),
|
|
)
|
|
hubFrom(c).Recover(r)
|
|
}
|
|
|
|
// recoveredPanic turns a recovered panic into the error handleError answers.
|
|
func recoveredPanic(_ fiber.Ctx, r any) error {
|
|
return &panicError{value: r}
|
|
}
|