API inputs go in the JSON body, never in query parameters (owner,
2026-12-01; design.md, "Inputs go in the JSON body"). The module routes
took copies and printer in the query, beside a body that was the
module's payload alone.
The body of POST /api/v1/print/{module} and /api/v1/preview/{module}
now holds the payload under payload, with copies and printer beside it:
{"payload": {...}, "copies": 2, "printer": "default"}. A module may name
its payload's fields as it likes, since none can collide with copies or
printer; that matters for ntfy's messages and for any module that takes
another system's JSON. The body is decoded strictly, and its problems
are answered at once as invalid_payload, each named by its path in the
body: copies, or, once the body is right, payload.done[0] for one the
module finds. A field named body is quoted, "body", so it is never
taken for a problem with the whole body. copies takes 0-5, as a job's
does, 0 meaning one. A query string on these routes gets 400
invalid_query, now worded "query parameters are not accepted".
The ntfy client recipes in docs/api.md wrap $NTFY_RAW in the body. The
Windows command was run here through cmd.exe and PowerShell, and the
printf of the Linux one in sh, each with a message holding quotes, & and
%; neither ran under an ntfy client. No tag carries the module query, so
the 0.2.0 entries in the CHANGELOG change in place (owner, 2026-12-01).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
350 lines
13 KiB
Go
350 lines
13 KiB
Go
package server
|
|
|
|
import (
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
|
|
"uberbringer/internal/pkg/printqueue"
|
|
"uberbringer/internal/pkg/receipt"
|
|
)
|
|
|
|
// BasePath prefixes the routes that need a bearer token.
|
|
const BasePath = "/api/v1"
|
|
|
|
// Media types the routes answer with.
|
|
const (
|
|
mediaJSON = fiber.MIMEApplicationJSON
|
|
mediaText = fiber.MIMETextPlainCharsetUTF8
|
|
)
|
|
|
|
// Route is one route of the HTTP API. The server registers it from this
|
|
// table and tools/genopenapi documents it in docs/swagger.json, so the two
|
|
// cannot differ.
|
|
type Route struct {
|
|
Method string
|
|
// Path is in OpenAPI form, e.g. /api/v1/jobs/{id}.
|
|
Path string
|
|
OperationID string
|
|
Summary string
|
|
Description string
|
|
Tag string
|
|
// Auth routes are under BasePath: they need a bearer token, are rate
|
|
// limited per client and answer with Cache-Control: no-store.
|
|
Auth bool
|
|
// NoStore adds Cache-Control: no-store to a route without Auth.
|
|
NoStore bool
|
|
// Request is the zero value of the JSON request body's type, or nil.
|
|
Request any
|
|
// Params are the route's path, query and header parameters.
|
|
Params []Param
|
|
Responses []Response
|
|
|
|
// errors are the codes the handler answers with itself;
|
|
// DocumentedErrors adds those of the middleware.
|
|
errors []errorCode
|
|
// scope says which tokens limited to modules may use the route.
|
|
scope routeScope
|
|
handle func(*Server, fiber.Ctx) error
|
|
}
|
|
|
|
// Response is one documented answer of a route that is not an error.
|
|
type Response struct {
|
|
Status int
|
|
Description string
|
|
// Content lists the bodies by media type; none for an empty answer.
|
|
Content []Content
|
|
// Headers are the headers it carries besides Content-Type.
|
|
Headers []Header
|
|
}
|
|
|
|
// Content is a response body in one media type.
|
|
type Content struct {
|
|
MediaType string
|
|
// Body is the zero value of the body's type; a string is a text body.
|
|
Body any
|
|
}
|
|
|
|
// Header is a response header a route documents.
|
|
type Header struct {
|
|
Name string
|
|
Description string
|
|
// Integer headers carry a whole number, the rest a string.
|
|
Integer bool
|
|
}
|
|
|
|
// Param is a path, query or header parameter of a route.
|
|
type Param struct {
|
|
Name string
|
|
// In is "path", "query" or "header".
|
|
In string
|
|
Description string
|
|
Required bool
|
|
}
|
|
|
|
// ErrorDoc is an error code a route can answer with.
|
|
type ErrorDoc struct {
|
|
Status int
|
|
Code string
|
|
Message string
|
|
}
|
|
|
|
// ErrorBody returns the zero value of the body every error answers with.
|
|
func ErrorBody() any { return errorResponse{} }
|
|
|
|
// DocumentedErrors returns the codes the route can answer with: its own and
|
|
// those of the middleware it runs behind.
|
|
func (r Route) DocumentedErrors() []ErrorDoc {
|
|
codes := append([]errorCode(nil), r.errors...)
|
|
if r.Request != nil {
|
|
codes = append(codes, codeBodyTooLarge)
|
|
}
|
|
if r.Auth && r.scope != scopeAny {
|
|
codes = append(codes, codeTokenScope)
|
|
}
|
|
if r.Auth {
|
|
codes = append(codes, codeUnauthorized, codeRateLimited)
|
|
}
|
|
codes = append(codes, codeInternal)
|
|
return errorDocs(codes)
|
|
}
|
|
|
|
// ServerErrors returns the codes the HTTP server itself can answer any
|
|
// request with: for a malformed or slow request, for an unknown route or
|
|
// method, and for an unsupported transfer coding.
|
|
func ServerErrors() []ErrorDoc {
|
|
return errorDocs([]errorCode{codeBadRequest, codeNotFound, codeMethodNotAllowed, codeRequestTimeout,
|
|
codeHeadersTooLarge, codeNotImplemented})
|
|
}
|
|
|
|
func errorDocs(codes []errorCode) []ErrorDoc {
|
|
docs := make([]ErrorDoc, len(codes))
|
|
for i, c := range codes {
|
|
docs[i] = ErrorDoc{Status: c.status, Code: c.code, Message: c.message}
|
|
}
|
|
return docs
|
|
}
|
|
|
|
// Routes returns the route table.
|
|
func Routes() []Route {
|
|
return []Route{
|
|
{
|
|
Method: http.MethodGet,
|
|
Path: "/",
|
|
OperationID: "getInfo",
|
|
Summary: "Version information",
|
|
Description: "The project's name, description and authors, and the version and build of the running daemon.",
|
|
Tag: "meta",
|
|
Responses: []Response{{Status: http.StatusOK, Description: "The running build",
|
|
Content: []Content{{MediaType: mediaJSON, Body: indexResponse{}}}}},
|
|
handle: (*Server).handleIndex,
|
|
},
|
|
{
|
|
Method: http.MethodGet,
|
|
Path: "/robots.txt",
|
|
OperationID: "getRobots",
|
|
Summary: "Robots exclusion file",
|
|
Tag: "meta",
|
|
Responses: []Response{{Status: http.StatusOK, Description: "A robots.txt that allows everything",
|
|
Content: []Content{{MediaType: mediaText, Body: ""}}}},
|
|
handle: func(_ *Server, c fiber.Ctx) error { return handleRobots(c) },
|
|
},
|
|
{
|
|
Method: http.MethodGet,
|
|
Path: "/openapi.json",
|
|
OperationID: "getOpenAPI",
|
|
Summary: "This API's OpenAPI document",
|
|
Description: "The OpenAPI 3.1 document of this API, generated from its route table, as the running " +
|
|
"build serves it.",
|
|
Tag: "meta",
|
|
Responses: []Response{{Status: http.StatusOK, Description: "The document",
|
|
Content: []Content{{MediaType: mediaJSON, Body: openAPIDocument{}}}}},
|
|
handle: (*Server).handleOpenAPI,
|
|
},
|
|
{
|
|
Method: http.MethodGet,
|
|
Path: "/healthz",
|
|
OperationID: "getHealth",
|
|
Summary: "Printer, queue and subscription health",
|
|
Description: "Reads the printer's real-time status. A printer that looks not ready is read again " +
|
|
"750 ms later, and only a problem that is still there gives 503. A printer that does not " +
|
|
"answer status requests is reported as status unknown with 200. The ntfy subscriptions, " +
|
|
"when any are configured, are listed with their state; the status code depends on the " +
|
|
"printer alone.",
|
|
Tag: "health",
|
|
NoStore: true,
|
|
Responses: []Response{
|
|
{Status: http.StatusOK, Description: "The printer is reachable and ready, or does not report status",
|
|
Content: []Content{{MediaType: mediaJSON, Body: healthResponse{}}}},
|
|
{Status: http.StatusServiceUnavailable, Description: "The printer is unreachable, not ready, " +
|
|
"or did not answer in time", Content: []Content{{MediaType: mediaJSON, Body: healthResponse{}}}},
|
|
},
|
|
handle: (*Server).handleHealth,
|
|
},
|
|
{
|
|
Method: http.MethodPost,
|
|
Path: BasePath + "/print",
|
|
OperationID: "printJob",
|
|
Summary: "Queue a print job",
|
|
Description: "Validates the whole job and queues it. The worker renders it in full before anything " +
|
|
"is sent to the printer, and fetches its images then, so a broken image URL shows up as a " +
|
|
"failed job. A job with raw elements needs a token issued with uberbringer token --raw, " +
|
|
"and a token limited to modules cannot use this route.",
|
|
Tag: "print",
|
|
Auth: true,
|
|
Request: receipt.Job{},
|
|
Responses: []Response{{Status: http.StatusAccepted, Description: "The job is queued",
|
|
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}},
|
|
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers with " +
|
|
"its status."}}}},
|
|
errors: []errorCode{codeInvalidJob, codeQueueFull, codeShuttingDown},
|
|
scope: scopeFull,
|
|
handle: (*Server).handlePrint,
|
|
},
|
|
{
|
|
Method: http.MethodPost,
|
|
Path: BasePath + "/preview",
|
|
OperationID: "previewJob",
|
|
Summary: "Show the lines a job prints, without printing it",
|
|
Description: "Validates the job as /api/v1/print does, renders it and reads the lines back from " +
|
|
"the rendered bytes. It prints nothing and fetches no images. The answer is JSON with the " +
|
|
"lines' styles when the Accept header prefers application/json to text/plain (for example " +
|
|
"application/json or application/*), and plain text otherwise.",
|
|
Tag: "print",
|
|
Auth: true,
|
|
Request: receipt.Job{},
|
|
Responses: []Response{{Status: http.StatusOK, Description: "The lines the printer would print",
|
|
Content: []Content{
|
|
{MediaType: mediaText, Body: ""},
|
|
{MediaType: mediaJSON, Body: previewResponse{}},
|
|
}}},
|
|
errors: []errorCode{codeInvalidJob, codeTooManyLines},
|
|
scope: scopeFull,
|
|
handle: (*Server).handlePreview,
|
|
},
|
|
{
|
|
Method: http.MethodGet,
|
|
Path: BasePath + "/jobs/{id}",
|
|
OperationID: "getJob",
|
|
Summary: "Job status",
|
|
Description: "The status of a queued, printing or finished job. The last queue.history finished " +
|
|
"jobs are kept.",
|
|
Tag: "print",
|
|
Auth: true,
|
|
Params: []Param{{Name: "id", In: "path", Required: true, Description: "The job's ID, a job_ TypeID."}},
|
|
Responses: []Response{{Status: http.StatusOK, Description: "The job's status",
|
|
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}}}},
|
|
errors: []errorCode{codeJobNotFound},
|
|
scope: scopeAny,
|
|
handle: (*Server).handleJob,
|
|
},
|
|
{
|
|
Method: http.MethodPost,
|
|
Path: BasePath + "/print/{module}",
|
|
OperationID: "printModule",
|
|
Summary: "Queue the receipt a module builds from its payload",
|
|
Description: "The module named in the path builds a receipt from the body's payload, a JSON " +
|
|
"object whose fields the module defines; copies and printer sit beside it. The body is " +
|
|
"decoded strictly, and so are the payloads of note and notify: an unknown field or one of " +
|
|
"the wrong type is refused, with every problem listed. ntfy ignores the payload fields it " +
|
|
"does not know. The receipt is then validated and queued as on /api/v1/print. A module with " +
|
|
"nothing to print answers 204. A token limited to modules (uberbringer token --modules) may " +
|
|
"use only the modules it names.",
|
|
Tag: "modules",
|
|
Auth: true,
|
|
Request: moduleRequest{},
|
|
Params: moduleParams,
|
|
Responses: []Response{
|
|
{Status: http.StatusAccepted, Description: "The receipt is queued",
|
|
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}},
|
|
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers " +
|
|
"with its status."}}},
|
|
{Status: http.StatusNoContent, Description: "The module had nothing to print"},
|
|
},
|
|
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
|
|
codeModuleFailed, codeQueueFull, codeShuttingDown},
|
|
scope: scopeModule,
|
|
handle: (*Server).handlePrintModule,
|
|
},
|
|
{
|
|
Method: http.MethodPost,
|
|
Path: BasePath + "/preview/{module}",
|
|
OperationID: "previewModule",
|
|
Summary: "Show the lines a module's receipt prints, without printing it",
|
|
Description: "Builds the receipt from the same body as /api/v1/print/{module} and answers as " +
|
|
"/api/v1/preview does: JSON with the lines' styles when the Accept header prefers " +
|
|
"application/json to text/plain, and plain text otherwise. It prints nothing and fetches " +
|
|
"no images.",
|
|
Tag: "modules",
|
|
Auth: true,
|
|
Request: moduleRequest{},
|
|
Params: moduleParams,
|
|
Responses: []Response{
|
|
{Status: http.StatusOK, Description: "The lines the printer would print",
|
|
Content: []Content{
|
|
{MediaType: mediaText, Body: ""},
|
|
{MediaType: mediaJSON, Body: previewResponse{}},
|
|
}},
|
|
{Status: http.StatusNoContent, Description: "The module had nothing to print"},
|
|
},
|
|
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
|
|
codeModuleFailed, codeTooManyLines},
|
|
scope: scopeModule,
|
|
handle: (*Server).handlePreviewModule,
|
|
},
|
|
{
|
|
Method: http.MethodGet,
|
|
Path: BasePath + "/modules",
|
|
OperationID: "listModules",
|
|
Summary: "List the modules",
|
|
Description: "Every module the module routes take, sorted by name.",
|
|
Tag: "modules",
|
|
Auth: true,
|
|
Responses: []Response{{Status: http.StatusOK, Description: "The modules",
|
|
Content: []Content{{MediaType: mediaJSON, Body: moduleList{}}}}},
|
|
scope: scopeAny,
|
|
handle: (*Server).handleModules,
|
|
},
|
|
}
|
|
}
|
|
|
|
// moduleParams are the parameters of the module routes.
|
|
var moduleParams = []Param{
|
|
{Name: "module", In: "path", Required: true,
|
|
Description: "The module's name, e.g. note. GET /api/v1/modules lists them."},
|
|
}
|
|
|
|
// pathParam finds the {name} parameters in a route path.
|
|
var pathParam = regexp.MustCompile(`\{([^/{}]+)\}`)
|
|
|
|
// fiberPath turns an OpenAPI path into Fiber's form: {id} becomes :id.
|
|
func fiberPath(path string) string {
|
|
return pathParam.ReplaceAllString(path, ":$1")
|
|
}
|
|
|
|
// registerRoutes adds every route of the table to the app. api is the group
|
|
// at BasePath that holds the bearer token, rate limit and no-store
|
|
// middleware; its routes refuse the tokens their scope leaves out.
|
|
func (s *Server) registerRoutes(api fiber.Router) {
|
|
for _, r := range Routes() {
|
|
handler := func(c fiber.Ctx) error { return r.handle(s, c) }
|
|
path := fiberPath(r.Path)
|
|
switch {
|
|
case r.Auth:
|
|
scoped := func(c fiber.Ctx) error {
|
|
if err := checkScope(c, r.scope); err != nil {
|
|
return err
|
|
}
|
|
return handler(c)
|
|
}
|
|
api.Add([]string{r.Method}, strings.TrimPrefix(path, BasePath), scoped)
|
|
case r.NoStore:
|
|
s.app.Add([]string{r.Method}, path, noStore, handler)
|
|
default:
|
|
s.app.Add([]string{r.Method}, path, handler)
|
|
}
|
|
}
|
|
}
|