TicketingSystem
Internal ticketing system with CTI-based routing, severity levels, role-based access, and automation integration.
Features
- CTI routing — tickets categorised by Category → Type → Item, reroutable at any time
- Severity 1–5 — SEV 1 (critical) through SEV 5 (minimal); dashboard sorts by severity
- Status lifecycle — Open → In Progress → Pending → Resolved → Closed; resolved tickets auto-close after 14 days. Pending means waiting on someone outside the team: an open ticket everywhere (lists, My tickets, counts, reports, paging, one open ticket per fingerprint), except that its resolve SLA clock pauses; only a person moves a ticket out of it (SLA)
- Full-text search — Postgres-native tsvector search across tickets and comments
- Search query syntax — type
kind:alarm sev:<=2 route:hosts/delphinus "nvme"in the tickets list's search box; validated as you type, kept in the URL, savable as a view (syntax) - Sorting the ticket list — a Sort control (Severity, Newest, Oldest, Recently updated, Least recently updated), remembered per person on the server so it follows you across devices; a
sort=in the URL or in a saved view wins for that visit - Saved views — filter presets on the tickets list; keep one private or share it with everyone (others can use it and save a copy; only the owner or an Admin can change it)
- Ticket list on a phone — below the desktop breakpoint the search box has its own row (beside the controls in landscape), then one row with select all, a Filters button that counts the filters in effect and opens a panel (Sort, Saved views and Export head it, the filter dropdowns follow), the filters as chips (tap × to remove one; one the search query sets is removed by editing the query) and the count. Rows on the list and My tickets show the whole title (up to three lines), severity, status, paging and SLA markers and the assignee (or "Unassigned"), then the id, route item, age and up to two labels; the whole row opens the ticket
- Due dates and SLA targets — an optional due date per ticket; time-to-acknowledge and time-to-resolve targets per severity (Admin › SLA), shown on the ticket and flagged in the list when breached or close, filterable (
sla:breached,due:overdue) and exposed as metrics for Prometheus to alert on. Nothing pages or notifies on a breach (SLA targets) - Pagination + bulk actions — page through large result sets and reassign / set status / close / reprioritise in batches
- Attachments — upload files on tickets and comments (25 MB each, local disk, a storage quota per account)
- Ticket links — related, blocks / blocked by and parent / child, shown on both tickets; a parent lists its children with their status ("2 of 5 resolved"). Links are shown, never enforced, and linking is silent (audit log only)
- Merge tickets — "Merge into…" on the ticket page (Agents and Admins; a picker by V… id or title, phone too) moves a ticket's comments and attachments to another, each marked "from V…", adds its watchers and labels there, and resolves it as Merged pointing to it; later reports with its fingerprint go to that ticket (Merge)
- Copy link — a button in the ticket header copies
<origin>/<ticket id>(the icon turns to a check and "Copied" shows for two seconds); on plainhttp://(dev, staging), where browsers hide the Clipboard API, it selects and copies byexecCommand, and if that fails too it shows the link in a box to copy by hand - Route links — in the ticket header, each level of the route (Category › Type › Item) links to the ticket list's open tickets on that level, shown in the list's route filter (and as a chip on a phone) and removable as usual; the links carry ids, so same-named items under different types stay apart, and a link opens in a new tab like any other
- Back to the list — the ticket page's back link is named after the list the ticket was opened from (My tickets, All tickets, Dashboard, Reports, Notifications) and returns to it as it was: same URL (filters, sort, page, search) and scroll position. Hops to other tickets (links, merge, duplicates, references, search, ⌘K) keep it; a ticket opened directly goes back to All tickets
- Ticket page on a phone — below the desktop breakpoint the paging banner, the title and the tabs come first; the summary follows, collapsed to one row (status, severity, SLA, assignee) that opens to every field, Delete last. The tab panel runs to the screen's edges and the overview, comments and audit use 12–16px padding; a comment's avatar sits in its header (no avatar column or timeline rail), so text gets nearly the full width
- Long text — a title, URL or identifier with no break wraps anywhere (
overflow-wrap: anywhere) instead of widening or cutting off the page; in Markdown a wide table scrolls sideways in its own wrapper (with the reports' edge cue) and a code block inside itself, phone and desktop. A Markdown image opens full screen when tapped or clicked (pinch zoom, tap for full size, its alt text as caption, "Open original" in a new tab; one inside a link keeps the link); each fenced code block has a Copy button; belowmdcode is 12px with 12px padding and table cells 13px - Live updates — an open ticket, the ticket list and the notification bell update within seconds of a change, whoever made it (either server replica, the Gitea importer); a small notice shows when the connection is down (Live updates)
- Labels — free-form coloured labels, several per ticket, shown on the ticket and in the list (click one to filter by it); filter with
label:backup,plex,-label:noiseorlabel:none; Admin › Labels renames, recolours and deletes; automation labels throughreport. Labelling is silent (audit log only) (Labels) - Resolver groups — groups of Agents (human or AI) that own categories, types or items; a ticket belongs to the owner of the most specific owned level of its route, shown in its summary ("Resolver group: Media"). Admin › Groups manages them; CTI config shows each node's owner. The assignee picker offers only a route's resolvers, and the API refuses anyone else (Assignees); only the group's members (and Admins) change its tickets, and everyone signed in still reads, comments and watches (Roles, Resolver groups)
- Notifications — in-app bell + optional SMTP email on assignment, @mention, and resolution, plus watching a ticket to follow its comments and status changes; each row names the ticket (id and title) and who did what, and a tap opens the ticket (at the comment, for a mention or comment) and marks it read
- Paging — pages the owner through Pushover for open severity 1–2 tickets (emergency priority, re-page, cancel on close, quiet pushes, storm guard); a shadow mode compares it with the n8n Pager first (Paging)
- Recurring tickets — Admin › Recurring tickets: a schedule (daily, weekly, monthly or a cron expression, in a time zone) creates a ticket from a template on its own (Recurring tickets)
- Ticket templates — Templates (user menu; Agents too): a title and Markdown body with
{name}placeholders and default fields; New Ticket's "Start from template" (phone too) andPOST /api/ticketswithtemplatefill them in.deploy-releaseanddeploy-appcome seeded (Ticket templates) - Approval requests — automation asks a question on a ticket; the approver (Admins, or a named user) answers with Approve or Reject on the ticket page (phone too), recorded once as a comment and in the audit log, and the decision is POSTed back to the caller (an n8n Wait node) (Approval requests)
- Outgoing webhooks — HMAC-signed POSTs on ticket/comment events, with per-endpoint secret, a delivery queue that survives restarts and retries for about 11 hours, and a delivery log with redeliver
- @mentions — autocomplete in comments; triggers notifications and deep-links to the mentioned user's queue
- Analytics dashboard — open-by-severity, aging tickets, resolution time, queue load. The dashboard and Reports read their numbers again when the app comes back to the foreground and every minute while shown (never while hidden), and say when they were read; on a phone the number cards form a 2×2 block and wide report tables scroll inside their card, with a fade while there is more
- Reports — what is getting worse: this window against the previous one, opened vs resolved with the open backlog, alarm volume, time to resolve, noisiest fingerprints, SLA targets met; window, grouping, kind and route filters live in the URL and every number links to the ticket list (Reports)
- CSV and JSON export — stream (in batches) any filtered ticket view to CSV, or to JSON with every ticket's comments, attachment metadata and links (and, on request, its audit log)
- Command palette + keyboard shortcuts — ⌘K palette,
j/knavigation,g d/t/m/n/sleaders,?help - PWA — installable on mobile, offline app shell; on an iPhone's Home Screen it opens full screen as "Tickets" with a PNG icon, the dark app runs under the status bar (
black-translucent) and the header and page pad for the notch, home indicator and side insets (env(safe-area-inset-*), nothing changes on desktop). BumpCACHEinclient/public/sw.jswhen a shell file changes - No zoom-on-focus on phones — on touch screens (
pointer: coarse) form fields render at 16px or more, so iOS Safari does not zoom the page when one is focused; pinch zoom is unaffected (client/src/index.css) - Phone keyboard — the sign-in fields name their autofill (
username,current-password) so the iOS keychain offers the saved login, and the username is not capitalised or autocorrected; search boxes and id or name pickers are typed as is with a "search" return key, comments keep sentence capitals (client/src/lib/keyboard.ts). Sign-in ignores the username's case and surrounding spaces (Login) - Tap targets on phones — on touch screens (
pointer: coarse, not a width query) every control has a hit area of at least 44×44 px, desktop untouched. Buttons, tabs, summaries, stand-alone links (tap-target) and a label wrapping a checkbox grow an invisible::afterlayer; icon-only buttons (marked with thetap-boxclass: CSS cannot tell an icon from an icon plus a word) and text fields are 44px themselves, a button with text keeps its height; a bare checkbox is wrapped in<label class="tap-check">. Inline links in running text and Markdown are exempt. The Category/Type/Item dropdowns stack one per row, Audit cards leave out rows that are only a dash (DashinResponsiveTable) and put short values beside their label, the live-updates notice clears the home indicator, andmanifest.webmanifestis served asapplication/manifest+json(client/nginx.conf) - Comments — GitHub/Gitea-style threads with markdown, draft autosave (per ticket, kept as a note or public as written), Ctrl+Enter submit. Edit and Delete show on hover with a mouse and always on a touch screen (
hover-revealinclient/src/index.css: a hidden control can't be clicked), and Delete asks for confirmation. Moving to another ticket starts its page afresh: no edit, draft, routing picker or pending image upload carries over - Bottom bar on a phone — on a touch screen below
mda tab bar fixed above the home indicator replaces the header's menu: Tickets, Mine, Search (full screen, results as you type; a wholeV…id, its nine digits, or a#Nthat was mirrored from Gitea opens its ticket; when empty, the tickets this account last opened on the device, cleared at sign-out; the page behind is inert), Alerts (with the unread count) and More (Dashboard, Reports, Settings, Templates, the admin pages, Log out); New ticket is a + in the header. The current section is marked, tabs are 44px (labels beside the icons, 44px tall, in landscape), pages pad their end for it and it hides while the on-screen keyboard is open (useKeyboardOpen, #237). A narrow desktop window keeps the menu - Ticket actions on a phone — on the ticket page the bottom bar becomes the ticket's own: Comment (the composer, focused), Status and Assign (sheets), Latest (the newest comment) and More (severity, then the whole summary with Merge and Mark as duplicate); someone who can't work the ticket gets Comment and Latest. A status, severity or assignee change made on a phone is shown at once and sent 8 seconds later, with a "Saving…" toast and Undo meanwhile: Undo drops it unsent (no audit row, webhook or notification); leaving the ticket, putting the app in the background or changing the same field again sends it at once, and a refused change is put back with the server's reason. It is sent with the value it replaced as its precondition (
expect), so someone else's change meanwhile is never overwritten ("Not saved: Mia changed status to Pending meanwhile"); a waiting change is kept in the account's outbox in the browser, so one a reload or a closed app cut off is sent on the next start (and said so; one over 10 minutes old is dropped with a notice). Each change carries its ownIdempotency-Key, so one that reached the server although the app never saw the answer is not applied a second time over a later change. One that found no connection is tried again when the app is back online, comes back to the front, and every 30 seconds; it is kept up to a day, and after 10 minutes is refused if someone else changed that field since. A second change to a field while the first is still being sent waits for it. A raise to SEV 1–2 is sent at once (it pages), with an Undo that sends the old severity back. More also has Search. The header is compact there: the title at 18px and three lines until tapped - Menus and dialogs fit a phone — every dropdown and popover is at most the room left on screen (inside the safe areas) and scrolls itself; dialogs are at most the visible height, with the title, close button and the footer's buttons fixed and the body between them scrolling (a bottom sheet below
sm). On a touch screen the user menu puts the admin pages behind one "Admin" entry and leaves out Keyboard shortcuts; desktop is unchanged - Above the on-screen keyboard — iOS shrinks only the visual viewport for the keyboard, so
client/src/lib/viewport.tspublishes it as--vvh,--vv-topand--keyboard-insetwith<html data-keyboard="open">(anduseKeyboardOpen()/useKeyboardInset()for components); dialogs cover only the visible part, so the sheet and its buttons sit above the keyboard and the focused field scrolls into view inside them; the comment box, comment and overview editors and the approval note keep their buttons in view while typing; @mention suggestions open where there is room; the title editor grows to show the whole title. Android Chrome resizes the page itself (interactive-widget=resizes-content) - Private notes and pasted images — the editor's Note toggle (Agents and Admins) writes a note that USER accounts never see, anywhere (page, API, search, notifications and mentions, webhooks, audit); paste, drop or pick (the image button: the photo library on an iPhone) a PNG, JPEG, GIF or WebP and it is uploaded to the ticket and shown inline (Comments)
- Profile pictures — Settings › Profile: pick (Photos or the camera on a phone) or drop an image, drag and zoom (slider or pinch) it in a round preview, save; the browser crops it to 256×256 and uploads that. Shown in the same circles as the initials (comments, assignee, header, lists, mentions, Admin › Users), which stay the fallback; an Admin sets one for any account, like an automation account (Profile pictures)
- Roles — Admin, Agent, User
- Audit log — every action tracked with actor, timestamp, and expandable detail
- Stay signed in — a checkbox on the sign-in page keeps a session for 30 days instead of 24 hours (
REMEMBER_DAYS,SESSION_HOURS) - Safer sessions — the web app's session is an HttpOnly cookie page scripts can't read (CSRF-checked;
__Host-over HTTPS), Sign out ends the session on the server, Sign out of all devices in Settings (and for any user in Admin › Users, audited), and a Content-Security-Policy with the other security headers (client/nginx.conffor the app, the server for the API) - Sign-in limits — failed sign-ins are limited per client address and per username (in the database: across replicas and addresses, unknown usernames alike), an unknown username takes as long to refuse as a wrong password, and the bundled nginx never passes on a client address the client chose
- Sign-in and key-use audit — Admin › Audit shows sign-ins, failures, lockouts, password and reset-link changes, API key changes, and which keys were used from where (new addresses flagged); kept 90 days (Audit)
- Admin panel — manage users, resolver groups, CTI hierarchy, labels, webhooks, recurring tickets and the settings (auto-close days, reopen window) via UI
- On a phone the Users, Labels, SLA, Paging and Audit tables show each row as a stacked card (the first column as its heading, the others as label and value, actions at the foot); desktop keeps the tables. One shared
ResponsiveTablecomponent does both from the same cells
- On a phone the Users, Labels, SLA, Paging and Audit tables show each row as a stacked card (the first column as its heading, the others as label and value, actions at the foot); desktop keeps the tables. One shared
- Versioned API with an OpenAPI description — everything is served under
/api/v1(and still under/api);GET /api/v1/openapi.jsondescribes it, generated from the schemas the routes validate with, so clients can be generated (API versions) - n8n ready — Agents authenticate with
X-Api-Key: several named keys per account, each scoped (read, report or write) and optionally expiring
Roles
| Role | Access |
|---|---|
| Admin | Full access — manage users, CTI config, webhooks, close and delete tickets |
| Agent | Manage tickets — create, update, assign, comment, change status (not Closed). Logs in with password and can authenticate via X-Api-Key header (scoped keys) |
| User | Basic access — view tickets and add comments only |
Only Admins can manually set a ticket status to Closed.
Who works a ticket (#173). Changing a ticket needs an Admin, or an Agent who is one of its resolvers: a member of the resolver group that owns its current route (any Agent when the route is unowned). That covers the update (status, severity, kind, states, route, assignee, due date, title, overview), resolve, duplicate, merge (both tickets: it writes the one merged into too), checklist ticks, labels, links (the ticket being changed only: a link shows on both but changes neither's fields), paged and acknowledge; anything else is a 403 { "error": "Only <group> resolvers can change this ticket" }. A resolver may move a ticket to another group's route (the hand-off). Bulk edit skips the tickets the caller can't work and returns skipped. An API key acts as its owner, with the owner's groups. Open to everyone who can see the ticket: reading, comments (and private notes for Agents), watching, filing a ticket on any route, and deciding an approval asked of you. Each is checked inside the transaction that writes, with the ticket's row locked and resolver ownership held (see Resolver groups), so neither a route change nor a change of a group's nodes or members made at the same moment can slip between the check and the write. POST /api/tickets/report records a repeat on any ticket (comment, count, last reported) but escalates, reopens or labels an existing ticket only for a key whose owner may work it, and says what it didn't do (ignored); filing a new ticket by report is open to any key. Not checked, because it's the system rather than someone working the ticket: the paging engine (PAGING_ACK_USERNAME), the Gitea importer, recurring tickets and auto-close. A ticket's canWork says whether the signed-in account may change it; the page shows a non-resolver its values read-only with "Worked by ".
How changes reach production
TWS runs TicketingSystem on its Kubernetes cluster, deployed by Argo CD from josh/tws-k8s and moved between stages by Kargo. An image is built once, in CI, and the same image moves from stage to stage.
| Stage | Runs | How an image gets there |
|---|---|---|
dev |
the newest main |
automatically, minutes after a merge (Kargo Warehouse ticketing-dev) |
staging |
the newest release, vX.Y.Z |
automatically when a release tag is pushed (Warehouse ticketing-release) |
prod |
a release that passed staging | a deploy ticket, approved by josh, then a manual promotion in Kargo |
- Merging: squash merges only (one PR = one commit = one image), branches deleted after merge,
mainprotected by the three test jobs. CI (.gitea/workflows/build.yml) runs the tests on every PR and buildsmain-<commit time>-<commit>plus the full commit for every merge tomain(and only fromrefs/heads/main: a manual run on another branch runs the tests and publishes nothing); docs-only changes build nothing. There is nolatest. - Releasing: when what's in
devis ready, create a release in Gitea (Releases → New release) with a tagvX.Y.Zon thatmaincommit..gitea/workflows/release.ymladdsvX.Y.Zto the imagedevalready ran (same digest; it only builds if that commit has no image), and Kargo takes it tostaging. A tag whose commit is not onmainfails the run before anything is published. Only strictvX.Y.Ztags count: no pre-releases. - Verification after each promotion is Kargo's, in the stage itself: the server answers
/healthzand/healthz/import, and indevandstaginga smoke test reports, reads back and resolves a ticket through the API (fingerprintsmoke:kargo|<stage>).prodaccepts only a releasestagingverified. - Containers run as non-root since #207: the server as uid 1000 and the client's nginx as uid 101, still on ports 80 and 8080. The deployment must give the uploads volume to uid 1000 (without it, saving an attachment or a profile picture fails), must set the pod sysctl
net.ipv4.ip_unprivileged_port_start=0for the client (without it nginx can't bind port 80 and the pod doesn't start), and must expose port 8080 to the reverse proxy in front, which should send its traffic there (see Self-hosting). - Rollback: promote the previous release to the stage in Kargo. Hotfix: a normal PR, then a patch release (
vX.Y.Z+1). - Migrations must work with the previous release still running. A deploy rolls the two server replicas one at a time and each runs
prisma migrate deployat start, so the old replica keeps serving against the new schema for a while. Add first, remove later: never drop or rename a column or table in the same release that stops using it; make new columns nullable or give them a default.
Self-hosting with Docker Compose
Prerequisites
- Docker + Docker Compose
- Nginx Proxy Manager pointed at the host port (default
3080). It is the client container's port 8080, which takes the client address from the proxy'sX-Forwarded-For(only the last address, the one the proxy added): let only that proxy reach it. Port 80 is for browsers that connect directly; it uses the connection's address and ignores anyX-Forwarded-Forsent (#200,client/nginx.conf) - Access to your Gitea container registry
1. Copy files to your server
scp docker-compose.yml .env.example user@your-server:~/ticketing/
2. Configure environment
cd ~/ticketing
cp .env.example .env
Edit .env:
REGISTRY=gitea.thewrightserver.net
TAG=main-20261109010232-bf25971 # an image tag; there is no `latest`
POSTGRES_PASSWORD=<strong password>
JWT_SECRET=<output of: openssl rand -hex 64>
CLIENT_URL=http://tickets.thewrightserver.net
PORT=3080
# Optional — email notifications
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=apikey
SMTP_PASS=<smtp password>
SMTP_FROM=tickets@thewrightserver.net
SMTP_SECURE=false
Point NPM at http://<host-ip>:3080 for the proxy host.
3. Deploy
docker compose pull
docker compose up -d
Both images run as a non-root user on pinned base images: the server as node (uid 1000), which must be able to write the uploads volume, and the client's nginx as nginx (uid 101), still on ports 80 and 8080: Docker lets an unprivileged process bind 80 (net.ipv4.ip_unprivileged_port_start=0 is its default), so nothing changes in the compose file for it. Upgrading an existing install (its uploads volume was written by root): once, before starting the new release, docker compose run --rm --user 0 server chown -R 1000:1000 /data/uploads; without it, saving an attachment or a profile picture fails (500).
The server applies any pending database migrations (prisma migrate deploy) before it starts. It exposes an unauthenticated GET /healthz that returns {"status":"ok"} while the database answers and 503 otherwise; the compose healthcheck polls it.
4. Create the first admin (first deploy only)
No account exists until you create one, and there is no default password:
docker compose exec server npm run bootstrap -- --username admin --display-name Admin --email admin@example.com --role ADMIN
It prints a random password once (or writes it to --credentials-file <path>, mode 0600). Running it again for the same username changes nothing (one that differs from an existing account's only by case or surrounding spaces is refused, naming that account); add --rotate to set a new password. To give the account a password you chose instead (one login shared by several services), put it on the first line of a root-only file and pass --password-file <path> (12 characters or more): a new account is created with it, an existing one is moved to it without --rotate and keeps its API keys, and the password is never printed or copied. A new password for an existing account (--rotate or --password-file) signs it out everywhere and cancels its unused reset links, as a change in the app does. With --role AGENT it also prints the account's API key.
Optionally load the sample CTI hierarchy with docker compose exec server npm run db:seed (it creates no accounts).
Create further accounts in Admin → Users. An Agent gets a default API key (write scope) for n8n and scripts, and Admin → Users → the key icon creates more, narrower ones (API keys). A key is shown once, at creation, and only its SHA-256 hash is stored. With --rotate, bootstrap replaces an Agent's default key and leaves its other keys alone.
Database migrations
The schema is managed with versioned Prisma migrations in server/prisma/migrations, applied on boot by prisma migrate deploy. Nothing runs prisma db push any more, so a schema change can't silently drop data. 2_api_key_hash hashes existing Agent API keys in place, so they keep working. 8_api_keys copies each Agent's key into the new ApiKey table as its default write key, so it keeps working unchanged; see API keys › Upgrading.
Naming and rules for new migrations: name the directory mNNNN_<name> with the next number (m0010_paging, then m0011_…), and keep each one additive (see How changes reach production). Prisma applies migrations in the text order of their names: a name like 10_x would sort between 0_init and 1_search and run before the migrations it builds on, while m sorts after every digit and four digits keep the numbers in order. The first ten (0_init … 9_ticket_links) keep their names because deployed databases record them; server/src/lib/migrations.test.ts fails on a name or order that breaks this.
Release notes: Update and Retirement kinds (m0017_kinds) and rolling back. m0017_kinds adds UPDATE and RETIREMENT to the TicketKind enum (it only adds the values; PostgreSQL can't use a value in the transaction that adds it). A Kargo rollback changes the image, not the database, and enum values can't be removed, so the previous release (v1.2.0) runs against this schema as follows:
- While no ticket has either kind, it works normally, including the importer. The only difference is that it rejects
kind: "UPDATE"or"RETIREMENT"in a request (a zodinvalid_enum_valueerror, status 500 on that release). - Once a ticket has one, that release fails on every read that returns the ticket:
Value 'UPDATE' not found in enum 'TicketKind', status 500, on the unfiltered ticket list,GET /api/tickets/:id,/by-gitea/:n, search, the CSV export andPATCHof it, and on a report whose fingerprint matches it.kind=BUGfilters, other tickets, new reports, the analytics endpoints andPOSTof tickets without the new kinds keep working. The Gitea importer fails on that ticket (its read of it fails), so the mirror's last sync time stops moving,/healthz/importanswers 503stale, and Kargo verification, which checks it, fails. - Before rolling back past this release, clear the kinds:
UPDATE "Ticket" SET kind = NULL WHERE kind IN ('UPDATE', 'RETIREMENT');(this loses those kinds on tickets created here; mirrored ones come back withnpm run import:gitea -- --fullafter rolling forward).
Release notes: agent provisioning (m0028_agent_provisioning) and rolling back. It adds the nullable User.disabledAt and the PROVISION value of ApiKeyScope (only the value, as m0017_kinds does). The previous release ignores disabledAt, so on its replicas a disabled account keeps working until the rollout finishes (or after a rollback: disable it again once rolled forward). It can't read a PROVISION key: on that release, a request made with one, and GET /api/users/:id/api-keys for its account, fail with a 500 (Value 'PROVISION' not found in enum 'ApiKeyScope'), and nothing else changes. Before rolling back past this release, revoke every PROVISION key and set its scope to one the previous release knows: UPDATE "ApiKey" SET scope = 'READ', "revokedAt" = COALESCE("revokedAt", now()) WHERE scope = 'PROVISION';.
Release notes: the COMMENT scope (m0029_comment_api_key_scope) and rolling back. It adds the COMMENT value of ApiKeyScope, before WRITE (only the value, as m0028_agent_provisioning does). The previous release can't read a COMMENT key: on that release, a request made with one, and GET /api/users/:id/api-keys for its account, fail with a 500 (Value 'COMMENT' not found in enum 'ApiKeyScope'), and nothing else changes. Issue COMMENT keys once the rollout is done. Before rolling back past this release, revoke every COMMENT key and set its scope to one the previous release knows: UPDATE "ApiKey" SET scope = 'READ', "revokedAt" = COALESCE("revokedAt", now()) WHERE scope = 'COMMENT';.
Release notes: the Pending status (m0030_pending_status) and rolling back. It adds the PENDING value of TicketStatus, before RESOLVED (only the value, as m0017_kinds does), Ticket.pendingSince and Ticket.pendingSeconds (the time Pending, kept by the ticket_status_pending_time trigger on every status or severity change, whoever writes it), and a second partial unique index for one open ticket per fingerprint that covers Pending (the one from 3_automation stays). The previous release keeps working until a ticket is Pending; it can't read one (Value 'PENDING' not found in enum 'TicketStatus', a 500 wherever that ticket is returned, as with m0017_kinds), and it ignores the paused time. Rolling back is therefore not clean once any ticket is Pending: first set them to In Progress, UPDATE "Ticket" SET status = 'IN_PROGRESS' WHERE status = 'PENDING'; (the trigger records the end of each spell), then roll back.
During the rolling deploy of this release the same applies with both releases up: with two replicas, once a ticket is set Pending through a new pod, an old pod answers 500 for every list, search or page that contains it until that pod is replaced, and a report sent to an old pod for a Pending ticket's fingerprint gets a 409 (it doesn't see the Pending ticket as open, and the new index refuses a second one). Both end when the rollout does; to avoid them, don't set tickets Pending until it has finished.
Release notes: usernames unique ignoring case (m0031_username_folded_unique). It adds a unique index on lower(btrim(username)), the comparison sign-in makes, so no two accounts differ only by case or surrounding spaces, whoever creates them (the app, bootstrap, the Gitea importer, the previous release, which then gets a 409; v1.13.0's importer, off in production, would stop with an error on a Gitea login that differs from an account only by case). If the database already holds such a pair the migration stops before changing anything, listing them (these usernames differ only by case or surrounding spaces: 'Josh', 'josh'), and the server doesn't start. To check before deploying, SELECT lower(btrim(username)), count(*) FROM "User" GROUP BY 1 HAVING count(*) > 1; lists any such group. To resolve it, keep one account of each group and rename the others (UPDATE "User" SET username = 'josh-old' WHERE username = 'Josh';; or disable and rename an unused one), then npx prisma migrate resolve --rolled-back m0031_username_folded_unique and deploy again. Rolling back needs nothing: the previous release works with the index.
Upgrading a v1.0 database created by db push: mark the baseline as applied once, then deploy as usual:
docker compose exec server npx prisma migrate resolve --applied 0_init
docker compose exec server npx prisma migrate resolve --applied 1_search
docker compose up -d --force-recreate server
Set the SMTP_* env vars if you want email notifications — otherwise they're silently skipped.
Backups and restore
Back up the database with pg_dump -Fc, and the uploads volume (UPLOADS_DIR) with your file backups: attachments aren't in the database.
docker compose exec -T postgres pg_dump -Fc -U postgres ticketing > ticketing-$(date -u +%Y%m%dT%H%M%SZ).dump
Restore into a new database, migrate and check it, then swap it in:
# 1. Restore the dump into a new database
docker compose exec -T postgres createdb -U postgres ticketing_restored
docker compose exec -T postgres pg_restore -U postgres --no-owner --exit-on-error -d ticketing_restored < ticketing-20261105T023000Z.dump
# 2. Apply any migrations newer than the dump (none if it came from the running version)
docker compose run --rm server sh -c 'DATABASE_URL="${DATABASE_URL%/ticketing}/ticketing_restored" npx prisma migrate deploy'
# 3. Check it: ticket and comment counts should be what you expect
docker compose exec -T postgres psql -U postgres -d ticketing_restored \
-c 'SELECT (SELECT count(*) FROM "Ticket") AS tickets, (SELECT count(*) FROM "Comment") AS comments'
# 4. Swap it in, keeping the old database until you're satisfied
docker compose stop server
docker compose exec -T postgres psql -U postgres \
-c 'ALTER DATABASE ticketing RENAME TO ticketing_old' -c 'ALTER DATABASE ticketing_restored RENAME TO ticketing'
docker compose start server
Drop ticketing_old once the restored database checks out.
Restore check. A deployment can check every backup by restoring it. TWS's deploy role does this nightly: it restores the dump into a scratch database, migrates it, compares row counts with the live database at the moment of the dump, and records the outcome in SyncState under backup-check as { lastRun: { at, ok, file, bytes, seconds, tickets, comments, error? }, lastSuccessAt }. GET /healthz/backup (no auth) answers 200 while the last check passed within BACKUP_STALE_HOURS, and 503 with stale or failing otherwise (not-configured, 200, until a check has run). The metrics include ticketing_backup_last_success_timestamp_seconds and ticketing_backup_healthy.
Development
Requirements
- Node.js 22+
- PostgreSQL (local or via Docker)
Start Postgres
docker run -d \
--name ticketing-pg \
-e POSTGRES_DB=ticketing \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=postgres \
-p 5432:5432 \
postgres:16-alpine
Server
cd server
cp .env.example .env # set DATABASE_URL and JWT_SECRET
npm install
npm run db:migrate # applies migrations (tables, search triggers)
npm run bootstrap:dev -- --username admin --role ADMIN # prints the admin's password once
npm run db:seed # optional: sample CTI, no accounts
npm run dev # http://localhost:3000
npm test # vitest (service layer, mocked database)
npm run test:db # resets DATABASE_URL, migrates, runs src/**/*.db.test.ts
npm run typecheck
Client
cd client
npm install
npm run dev # http://localhost:5173 (proxies /api to :3000)
npm test # vitest + testing-library
npm run typecheck
After a schema change in prisma/schema.prisma, create a migration with npm run db:migrate:dev -- --name <change> and commit it.
CI runs typecheck and tests on both packages, plus the migrations and database tests against PostgreSQL, before building Docker images.
Browser tests
e2e/ holds Playwright tests (Chromium) that drive the real app: sign in and out, the ticket list with its filters and search syntax, the ticket page, comments, a report followed by a keyed comment, and the /gitea/:n redirect. They start their own stack: the server on a PostgreSQL database (migrations applied first), and the client's production build served by vite preview with /api proxied to it. Nothing external is contacted (PAGING_MODE=off, no SMTP, no Pushover). Each run creates its own accounts with the bootstrap script and tags its tickets with a run id, so an existing database is fine and nothing is reset.
cd e2e
npm ci
npx playwright install chromium # once; add --with-deps on a fresh Linux machine
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/ticketing_e2e npm test
DATABASE_URL must name an existing (empty is fine) database. The API, metrics and client ports default to 3100, 9100 and 5100; override them with E2E_API_PORT, E2E_METRICS_PORT and E2E_CLIENT_PORT. E2E_CHROMIUM_PATH points at a browser Playwright did not install itself. Install the server and client dependencies first (npm ci in server/ and client/).
CI runs them as the job "Test (browser)" on pull requests and on main, against a postgres:16-alpine service, and the image build waits for it.
API Reference
Every endpoint below is served under /api/v1 (/api/v1/tickets, …) and under the original /api prefix, with identical behaviour; the paths in this reference are written with /api and work as /api/v1 too. New integrations should use /api/v1 (API versions and the OpenAPI document).
All endpoints (except /api/auth/*, /api/version, /api/openapi.json and /healthz) require authentication via one of:
- JWT:
Authorization: Bearer <token>(obtained fromPOST /api/auth/login) - API Key:
X-Api-Key: sk_<key>(Agent accounts only; see API keys for scopes) - Session cookie (the web app):
ticketing_session, set byPOST /api/auth/loginwhen the request sendsX-Requested-With: ticketing. A request authenticated by the cookie must send that header too unless it is a GET or HEAD (403 otherwise: the CSRF check). Bearer and API-key requests don't need it. See Sessions.
Base URL: https://tickets.thewrightserver.net/api/v1 (or /api)
API versions and the OpenAPI document
The API is version 1 and is served under /api/v1. The original /api prefix stays as an alias: the same routers answer on both, so every route, status and body is identical, and nothing about a request changes except its prefix. The web client and n8n still use /api; there is no plan to remove it yet, and moving to /api/v1 is only a change of base URL. What is the same on both prefixes:
- API-key scopes: a
REPORTkey may do under/api/v1exactly what it may do under/api, and nothing more;READisGET/HEADon both. - Rate limits: one budget per client address (and per key) whichever prefix a request comes by, including the failed-login limit on
/api/auth/login,/api/v1/auth/loginand the reset endpoint, which is one shared counter.GET /api/version,GET /api/v1/versionand the OpenAPI document are the only exempt API routes. - Metrics: the
routelabel ofticketing_http_requests_totaland the duration histogram is the full route template (/api/tickets/:id, never a real id), the same for a request that succeeds and one that fails, and uses the/api/…name for both prefixes, so dashboards keep working. A request that matches no route (an unknown path, or one refused by authentication before routing) is counted underroute="unmatched".
/healthz, /healthz/import and /healthz/backup are not versioned and stay where they are; GET /api/v1/version also answers as GET /api/version.
GET /api/v1/openapi.json (also /api/openapi.json; no authentication, not rate limited) returns an OpenAPI 3.1 document describing every route: parameters, request bodies, the success response and the common errors (400, 401, 403, 404, 409, 429, all { "error": string }, plus details on a validation error), the two security schemes (bearerAuth, apiKeyAuth) and, per operation, the role (x-required-role) and the lowest API-key scope (x-api-key-scope) it needs. Request bodies and the ticket list's filters are the Zod schemas the routes validate with (shared/schemas/), converted when the server starts, so they cannot drift from validation; the response schemas are written by hand (server/src/openapi/responseSchemas.ts) and tested against real responses. A test fails when a route is added without being documented, or documented without existing (add the route to server/src/openapi/operations.ts). Query parameters the routes read without a schema are described by hand, the live-updates stream (GET /api/v1/events, text/event-stream) is documented although the server answers 404 for it when LIVE_POLL_MS=0, and the document says which operations need a signed-in session (bearerAuth only: key management, settings, the SLA policy, recurring-ticket changes). Paths are relative to the document's servers (/api/v1, or /api).
Generate a client from it, for example TypeScript types:
npx openapi-typescript https://tickets.thewrightserver.net/api/v1/openapi.json -o ticketing-api.d.ts
API keys
An Agent account can have several API keys, each with a name (say n8n, goddard, console), a scope and an optional expiry, so each consumer has its own key with no more rights than it needs. Only a key's SHA-256 hash is stored; the key is returned once, when it's created. Lists show the name, prefix (sk_ and 8 characters), scope, expiry, creation and last use (recorded at most every 5 minutes per key), never the key.
The scope is checked for every request in the authentication middleware, before any route runs, so a route added later is not writable by a narrower key unless it's added to the list below. Scopes only narrow: the account's role still applies (a key is an Agent's, so Admin-only routes stay out of reach whatever the scope).
| Scope | Allows | Refuses (403) |
|---|---|---|
READ |
GET and HEAD on anything the role can read |
Every other method |
REPORT |
READ, plus what a reporter sends: POST /api/tickets/report, POST /api/tickets/:id/resolve (clear its own alarm; the smoke test), PUT /api/tickets/:id/comments/by-key/:key (run cards), POST /api/tickets/:id/paged and POST /api/tickets/:id/acknowledge (the Pager) |
Everything else that writes: creating, editing, bulk-editing or deleting tickets, duplicate, checklist, links, ordinary comments and their edits, attachments, watching, saved views, notification state, passwords |
COMMENT |
REPORT, plus filing and discussing (#191): POST /api/tickets (file a ticket, unassigned and at severity 3 to 5: assigneeId and severity 1 or 2 are refused, and a template's default assignee is left off), POST /api/tickets/:id/comments (ordinary comments and private notes), and PATCH and DELETE on /api/tickets/:id/comments/:commentId for the key's own comments only |
Everything else that writes: editing, assigning, bulk-editing or deleting tickets, status and resolution (beyond REPORT's resolve), duplicate, merge, checklist, links, labels, someone else's comments, attachments, watching, approvals, saved views, notification state, passwords |
WRITE |
Everything the Agent role allows: what every key could do before scopes | Only what the role refuses |
PROVISION |
READ, plus provisioning Agent accounts (#190), on an Agent account that holds no PROVISION key and isn't the key's own: POST /api/users (an Agent only, groupIds allowed, created without a key), PATCH /api/users/:id with only disabled, GET, POST (scope READ, REPORT, COMMENT or WRITE, with an expiresAt) and DELETE on /api/users/:id/api-keys |
Everything else that writes, every ticket write included; creating an Admin or User; issuing a PROVISION key; acting on itself, an Admin, a User or another PROVISION holder; deleting; changing a role, password, name, email or groups; reset links, sign-outs and pictures |
- An expired, revoked or unknown key gets
401, and so does every key of a disabled account; a request outside the key's scope gets403. Signed-in sessions (JWT) have no scope. - API keys can't manage API keys: the key endpoints refuse any request made with one, and they're Admin-only besides. Managing users was already Admin-only, which no key can be. The one exception is a
PROVISIONkey, below. - Requests made with any key never auto-watch tickets.
The PROVISION scope
For the one automation that hires, rotates and offboards Agent accounts (#190), so that it needn't be an Admin. It is not nested with the others: it reads like READ and writes only on the provisioning routes, never a ticket.
- Issued only by a signed-in Admin, in Admin › Users or with
POST /api/users/:id/api-keysfrom a session. A request made with any API key can't issue one, aPROVISIONkey included. - How it reaches the provisioning routes. Those routes stay Admin-only for everyone else. The scope check lets a
PROVISIONkey write to exactly five routes (PROVISION_ROUTESinserver/src/lib/apiKeyScopes.ts, likeREPORT_ROUTES); each of those routes lets aPROVISIONkey past its Admin check explicitly (requireAdminOrProvisionKey) and then checks what it asks for and whom it acts on (server/src/lib/provisioning.ts), in the same transaction as the change, with the account's row locked. No other route lets it in: its account is an Agent, sorequireAdminstill refuses it everywhere else, andrequireSessionstill refuses it on every other session-only route. - Limits: it acts only on an Agent account that holds no
PROVISIONkey (revoked ones aside) and isn't its own. It creates Agents only, and without adefaultkey (apiKeyis absent): it issues the keys the new account needs, each with an expiry (a key withoutexpiresAtis a 400). It edits onlydisabled. Anything else is a403naming what it may not do. - Audit: everything it does is recorded in Admin › Audit with the acting account and the key's id, name and prefix (
detail.byKey):account_created,group_member_added,key_created,key_revoked,account_disabled,account_enabled. Refusals are counted askey_scope_refusedwith the reason. Its reads are counted askey_used, like any key's. - The kill switch: revoke the key, or disable its account; either takes effect on the next request.
The COMMENT scope
For staff who review, discuss and file things but don't triage or edit (#191; the agent accounts' reviewer role). It is nested between REPORT and WRITE: everything a REPORT key may do, plus the four routes in COMMENT_ROUTES (server/src/lib/apiKeyScopes.ts), checked like the other scopes before any route runs.
- Filing a ticket (
POST /api/tickets, from a template too) files it unassigned and at severity 3 to 5, never a paging severity: anassigneeIdin the request is a403(nullis fine), a template's default assignee is left off (the response'sassigneeDroppedsays so), and severity 1 or 2 is a403, a template's default included (it is refused, not changed). - Reporting (
POST /api/tickets/report, inherited fromREPORT) follows the same two rules: anassigneeIdor severity 1 or 2 is a403, before anything is applied. So a report can't create a ticket at 1 or 2, or escalate the open (or reopened) ticket its fingerprint matches to 1 or 2; a report never changes an existing ticket's assignee. Nor does it reopen a ticket at severity 1 or 2 (resolved or closed within the reopen window): that is a403naming the ticket, checked under the report's lock, and nothing is recorded or counted, because reopened it would page again. A report on a ticket already open at 1 or 2 is recorded as usual: the paging engine pages a ticket once per cycle and re-pages on time alone, never on a report, and the report's comment counts toward the quiet (silent) push after an acknowledgement like any comment the key may write.REPORTandWRITEkeys and sessions report as before. - Its own comments only: it edits and deletes comments its account wrote, and a
403for anyone else's, checked by the comment routes as well as by the role (keys belong to Agents, which can't change other people's comments). - Issued by an Admin (Admin › Users, or the API from a session), and by a
PROVISIONkey with an expiry.
Rotating without downtime: create the new key (Admin → Users → key icon, or POST /api/users/:id/api-keys), put it into whatever uses the old one, check the new key's Last used moves and the old one's stops, then revoke the old key. Both work in between.
Upgrading from one key per Agent
Before scopes, each Agent had one key, in User.apiKeyHash. Migration 8_api_keys copies every such key into ApiKey as a WRITE key named default, so it keeps working, with the same rights, without being re-issued. The old columns stay for now, because the previous release reads them while replicas roll and after a rollback; a later release drops them. Until then:
- An Agent's
defaultkey (from creating the account,regenerateApiKeyor bootstrap) is also written to those columns, so the previous release accepts it too; other keys work only on this release. - Revoking or replacing a key the columns hold clears them, so the previous release stops accepting it as well.
- A key the previous release issued (it writes only the columns) is accepted here as the account's
defaultWRITEkey and taken intoApiKeyon first use. Adefaultkey whose columns the previous release has since replaced stops working.
Authentication
POST /api/auth/login
Authenticate and receive a JWT. It is valid for SESSION_HOURS hours (default 24); with remember: true (the sign-in page's Stay signed in box), for REMEMBER_DAYS days (default 30). The username is matched exactly, else ignoring case and surrounding whitespace (spaces, tabs, no-break spaces: the same normaliser a new username goes through). Usernames are unique that way (m0031_username_folded_unique): a new account whose username differs from an existing one only by case or surrounding spaces is a 409, and a new username is stored trimmed and may not be empty or contain control characters. A password change in that session returns a token of the same length; a reset link starts a new, ordinary sign-in. The sign-in's audit event records remembered.
Failure limits (#200). Per client address, LOGIN_RATE_LIMIT failures in 15 minutes (in memory, per replica). Per username, LOGIN_ACCOUNT_LIMIT failures (default 10) in 15 minutes, counted in the database (SignInFailure, m0033_signin_hardening) so they hold across both replicas and any address: the next attempt is a 429 with Retry-After, the password unchecked, until the oldest failure is 15 minutes old. The username is folded by the database exactly as sign-in looks the account up (lower(btrim(username)), so every spelling that reaches an account, in case, spaces or any letter PostgreSQL's locale folds, shares its count), unknown usernames count the same way (the limit doesn't tell which accounts exist), and only an HMAC of it is stored. A successful sign-in clears the username's count, and so does a new password (changed, set by an Admin, or a reset link). So an account that signs in by password on a schedule (a service using a password file) gives a guesser up to LOGIN_ACCOUNT_LIMIT new tries after each of its own sign-ins; give such a service an API key instead, which isn't a sign-in and doesn't touch the count. A wrong current password in POST /api/auth/password counts too, against the username and the address; a refused new password (too short, the same) doesn't. An unknown username is checked against a dummy hash at BCRYPT_COST, so it is refused as slowly as a wrong password. Refusals are audited as login_limited (on: login, reset-password, password, or account / account-password for the per-username limit, without the username).
Body:
{ "username": "string", "password": "string", "remember": false }
remember is optional and must be a boolean (400 otherwise).
Response:
{
"token": "eyJ...",
"user": {
"id": "...",
"username": "admin",
"displayName": "Admin",
"email": "...",
"role": "ADMIN"
}
}
Sessions: cookie, CSRF, sign out
The web app never holds its token. With X-Requested-With: ticketing, POST /api/auth/login (and POST /api/auth/password) set it as a cookie instead of returning it: over HTTPS (req.secure, which follows TRUST_PROXY) __Host-ticketing_session with Secure and Path=/ (#200: a __Host- cookie can't be set or replaced by another site under the parent domain), over plain http (local dev, the browser suite, an http tailnet address) ticketing_session with Path=/api; HttpOnly, SameSite=Lax, and Max-Age equal to the token's lifetime (24 hours, or REMEMBER_DAYS with Stay signed in). Without the header (scripts, an older client) the token comes in the body as before and no cookie is set. The server reads the cookie whose name fits how the request came (over HTTPS the old name is ignored, and cleared at sign-in and sign-out) or Authorization: Bearer (Bearer wins when both are sent). The request log leaves out the Cookie, Set-Cookie, Authorization and X-Api-Key headers, so no session token or key is written to the logs (server/src/lib/logger.ts).
POST /api/auth/logout— clears the cookie and ends the session on the server (204): every session token it was sent (the Bearer token and the cookie, when both come) is refused from then on (401Signed out; sign in again), on every replica; the account's other sessions and its API keys carry on. Only the token's SHA-256 is kept (RevokedSession,m0033_signin_hardening), until the token would have expired. Needs the header (or anAuthorizationheader). A password change (#197) and disabling the account (#190) already end every session of the account.POST /api/auth/logout-all— sign out of all devices: every session of the account issued before now stops working, cookie or Bearer (User.sessionsRevokedAt,m0020_session_revocation, compared to the millisecond); API keys are not affected. This session gets a fresh token of its kind (cookie with the header,{ "token" }without). Audited assessions_revoked. Refused with an API key.POST /api/users/:id/logout-all— the same for another user (Admin, signed in; 204; audited with the Admin as actor).POST /api/auth/session— for a web app upgraded from the version that kept its token in localStorage: it sends that token once as Bearer with the header, gets it back unchanged as the cookie (same expiry) and the account (likeGET /api/auth/me), then deletes its copy. Nobody is signed out by the upgrade.
Disabling an account
An Admin switches an account off without deleting it with PATCH /api/users/:id and { "disabled": true }, and back on with { "disabled": false } (also the ban icon in Admin › Users). User.disabledAt (m0028_agent_provisioning, a nullable column) records when; it is in GET /api/users, GET /api/auth/me and the account in every users response.
- Refused everywhere, at once (
401Account disabled): every API key of the account and every session (cookie or Bearer, whenever it started), on the next request; sign-in, even with the right password (audited aslogin_failedwith reasondisabled); and reset links: using one is refused without changing the password, and creating one is a 400. Its open live-updates streams are closed at the next poll. - Assignment: it can't be newly assigned a ticket (a 400 naming it, on create, update, bulk reassign, templates and recurring tickets), and the assignee pickers show it, marked disabled, without letting it be chosen. The tickets it holds and its comments are unchanged.
- Re-enabling brings back its keys that were not revoked and have not expired (disabling changes none of them) and lets its sessions work again unless they ended for another reason.
- An Admin can't disable their own account or the last enabled Admin (400). Both changes are audited (
account_disabled,account_enabled). - During the rolling deploy of the release that adds it, the previous release ignores
disabledAt: an account disabled then still works on a replica of the previous release until the rollout finishes. - Deleting (
DELETE /api/users/:id, the trash icon) is only for an account without history: one that no ticket, comment, attachment, label, link or audit entry refers to. An account with any is a409withcode: USER_HAS_HISTORYsaying to disable it instead (#222).
GET /api/auth/me
Returns the currently authenticated user, with listSort: the ticket list's sort the web app remembers for the account (null: the default).
PUT /api/auth/me/list-sort
Remember the ticket list's sort for the account: { "sort": "created" } (any sort value; null or severity forgets it). Signed-in sessions only (403 with an API key). The web app applies it when the list's URL has no sort; GET /api/tickets never reads it. Stored in User.listSort (m0018_user_list_sort, a nullable column the previous release ignores).
Profile pictures
| Method | Endpoint | Description |
|---|---|---|
PUT |
/api/auth/me/avatar |
Set your own (multipart, field file); signed-in sessions only |
DELETE |
/api/auth/me/avatar |
Remove your own; signed-in sessions only |
GET |
/api/users/:id/avatar |
The picture, for anyone signed in (404: none) |
PUT |
/api/users/:id/avatar |
Set someone's (Admin, signed in) |
DELETE |
/api/users/:id/avatar |
Remove someone's (Admin, signed in) |
PNG, JPEG or WebP, checked by content (anything else, SVG included, is a 400), at most 512 KB (413); the web app sends a 256×256 crop. Users on tickets, comments, /auth/me and /users carry avatarUpdatedAt (null: none); link GET /api/users/:id/avatar?v=<that time in ms>, which is cached for a year, so a new picture shows at once under its new URL. One file per account on the uploads volume (UPLOADS_DIR/avatars/<id>.<ext>, replaced on change, deleted with the picture or the account). Changes are audited (avatar_changed, avatar_removed). API keys can't set pictures: an Admin sets one for an automation account.
POST /api/auth/password
{ "currentPassword", "newPassword" } (at least 8 characters). Rate limited with sign-in: the same per-address budget, and the account's per-username failure limit (a wrong current password counts; a 429 when it is reached). Changes your own password and returns { "token" } (or, with X-Requested-With: ticketing, renews the session cookie) for this session, as long as your own (a remembered session gets a remembered token); every other session signed in with the old password is signed out, as for every way of setting a password (an Admin, a reset link, the bootstrap script).
Password reset links
An Admin creates one with POST /api/users/:id/reset-link, which returns { "url", "expiresAt" }. The link (<CLIENT_URL>/reset-password#token=…) works once, expires after an hour, and a newer link or a password change cancels it; only the token's hash is stored, and the token travels in the URL fragment so it stays out of logs. The page posts { "token", "newPassword" } to POST /api/auth/reset-password (no auth; rate limited like login).
Tickets
GET /api/tickets
List tickets, sorted by severity (ASC) then created date (DESC) unless sort says otherwise. created and updated are newest first, created_asc (oldest first) and updated_asc oldest first; every sort ends with the ticket id, so the order is the same on every read and page. A text search (search, or words in q) ranks by relevance when there is no sort; an explicit sort applies.
Query parameters:
| Parameter | Type | Description |
|---|---|---|
status |
string | OPEN, IN_PROGRESS, PENDING, RESOLVED, CLOSED; several comma-separated |
severity |
number | Filter by severity: 1–5 |
categoryId |
string | Filter by category (queue) |
assigneeId |
string | Filter by assignee user ID |
createdById |
string | Filter by author |
label |
string | Label names, comma-separated: tickets carrying all of them; none: no labels |
search |
string | Full-text search (tsvector) on title, overview, and display ID |
q |
string | A search query: kind:alarm sev:<=2 "nvme" (syntax) |
sla |
string | breached, running, met, ack-breached, resolve-breached (as q=sla:…) |
due |
string | overdue or none (as q=due:…) |
sort |
string | severity (default), created, created_asc, updated, updated_asc |
page |
number | Page number, 1-indexed. When omitted the endpoint returns a bare array (v0.9 shape) |
pageSize |
number | Page size (default 25, max 100) |
q and the other parameters combine with AND. A field set both by q and by its own parameter (q=status:open&status=CLOSED, or text in q and search) is a 400, as is a query that doesn't parse. Being a GET, it works with READ API keys.
Each parameter is one text value (#205): an id, an enum value or a string, lists comma-separated. A value that isn't one, a parameter given twice, or an object or array form (status[]=…, assigneeId[…]=…) is a 400; an empty status, severity, id or search means no filter. The exports, GET /api/cti/types?categoryId=, /items?typeId= and GET /api/notifications?limit= check theirs the same way. A NUL character (%00) in any query parameter of any API route is a 400 as well, and a server failure never answers with the database's message.
Search query syntax
The tickets list's search box and GET /api/tickets?q= take the same query language (#36). The parser is shared/lib/searchQuery.ts, used by both the server and the client.
- Words and "quoted phrases" are the full-text search, as before (the same word match as
search; quotes group words and keep a colon from making a filter, they don't require the words to be adjacent). field:valuefilters. Terms are combined with AND. OR and parentheses are not supported.- What is a filter: a word is a filter only when it starts with one of the field names below (any case), directly followed by a colon, outside quotes;
-in front negates (status and label). Every other word is text, colons included:http://x,12:30,foo:bar,"status:open". One exception: a near-miss of a field name (one letter off, 4+ letters:stauts:open,kinds:bug) is an error, being almost certainly a typo; quote it to search for it as text. - Values:
field:valuewith no space after the colon; quote values with spaces (route:"hosts/proxmox node"). Inside or outside quotes,\"is a literal quote and\\a backslash. Enum values ignore case, and a space,-and_are alike, soin_progress,in-progressand"In progress"are the same; labels work too (service:decommissioned,resolution:"won't fix"). - Several values with commas mean "any of" (
status:open,in_progress), except forlabel, where they mean "all of" (label:backup,plex: tickets carrying both). Negation is for status, where it means "any other status" (-status:closed), and label, where it excludes tickets carrying any of the labels (-label:noise). A field may appear once, exceptsev,created,updatedandduedates, whose terms narrow each other (sev:>=2 sev:<=4), andlabel, which may appear once and negated once (label:backup -label:noise).
| Field | Values | Examples | Same as parameter |
|---|---|---|---|
status |
open, in_progress, pending, resolved, closed; several; -status: excludes |
status:pending, status:open,in_progress, -status:closed |
status |
sev, severity |
1–5 (1 is most severe), with <, <=, >, >=, or a range 1-3 / 1..3 |
sev:2, sev:<=2, sev:>3, sev:1-3 |
severity |
kind |
alarm, bug, enhancement, new_service, workflow, testing, update, retirement; several |
kind:alarm, kind:bug,enhancement |
kind |
route |
category[/type[/item]] by name, any case, space/-/_ alike; category/item if unambiguous |
route:hosts, route:hosts/proxmox_node, route:hosts/delphinus |
categoryId/typeId/itemId |
label |
label names, any case, space/-/_ alike; several (all of them); none; -label: excludes |
label:backup, label:backup,plex, -label:noise, label:none |
label |
assignee |
a username (any case), me, or none (unassigned) |
assignee:me, assignee:none, assignee:josh |
assigneeId |
creator |
a username, or me |
creator:me |
createdById |
resolution |
fixed, duplicate, transient, not_a_failure, merged, wont_fix; several |
resolution:fixed, resolution:wont_fix,duplicate |
resolution |
workflow |
workflow state: pending, running, success, failure, timeout; several |
workflow:failure,timeout |
workflowState |
service |
service state: development, deployed, degraded, decom; several |
service:degraded |
serviceState |
paging |
paged, acknowledged, unacknowledged |
paging:unacknowledged |
paging |
sla |
breached, running, met, ack-breached, resolve-breached (see SLA targets) |
sla:breached, sla:ack-breached |
sla |
due |
overdue (past due, still open), none, or dates as created; overdue/none stand alone |
due:overdue, due:none, due:<2026-12-01 |
due |
created |
a date YYYY-MM-DD (whole UTC days), with <, <=, >, >=, or a range a..b (inclusive) |
created:2026-11-01, created:>=2026-11-01, created:2026-10-01..2026-10-31 |
— |
updated |
as created |
updated:<2026-01-01 |
updatedSince |
fingerprint |
the exact automation fingerprint | fingerprint:n8n:backup-plex |
fingerprint |
gitea |
the mirrored Gitea issue's number | gitea:1250 |
giteaNumber |
Examples: kind:alarm sev:<=2 route:hosts/delphinus status:open "nvme"; assignee:none -status:closed; workflow:failure updated:>=2026-11-01 backup.
Errors are a 400 whose error names the term and what would be valid, for example:
| Query | error |
|---|---|
sev:banana |
"sev:banana": severity is 1–5, optionally with <, <=, >, >= or a range (sev:2, sev:<=2, sev:1-3) |
status:nope |
"status:nope": "nope" is not a status. Valid: open, in_progress, pending, resolved, closed |
stauts:open |
"stauts:open": unknown field "stauts" (did you mean status?). Fields: status, sev, … |
"nvme |
""nvme": unterminated quote; close it with " |
status: |
"status:": status needs a value: open, in_progress, pending, resolved, closed; … |
status:a status:b |
"status:b": status is given twice (also "status:a"); list several values with commas |
-kind:bug |
"-kind:bug": only status and label can be negated (-status:closed, -label:noise) |
label:bakup |
"label:bakup": no label named "bakup". Did you mean: backup? |
assignee:ghost |
"assignee:ghost": no user named "ghost" (use a username, me or none) |
route:hosts/nope |
"route:hosts/nope": no type or item named "nope" in Hosts. Types: Packages, Proxmox cluster, Proxmox node |
q=status:open&status=… |
The query sets status (status:open) and so does the status parameter; use one or the other |
| (over 500 characters) | The query is too long (612 characters; the limit is 500) |
Also refused: label:none listed with names, a label both required and excluded, label:none -label:none, an empty item in a list (status:open,), a route deeper than three names, a date that doesn't exist, ranges that together match nothing (sev:<2 sev:>3), creator:none, and several users in one term. Control characters separate words. Names (users, route, labels) are resolved once per request; an unknown label lists close matches, or the labels there are.
In the UI, the search box validates as you type (after a short pause), shows what the query means as chips (or the error), and keeps the query in the URL (?q=) once it parses, so it can be shared, bookmarked and survives a reload; the ? button lists the fields. The dropdown filters still work and are applied in addition (AND); a field the query sets takes over its dropdown, which is disabled and shows "Set in query" until the term is removed. The header search box's Enter opens the list with its text as the query. "Save current filters" stores the query with the dropdowns.
Response (paginated):
{
"data": [
/* tickets */
],
"total": 134,
"page": 1,
"pageSize": 25
}
Response (unpaginated — page omitted): Array of ticket objects with nested category, type, item, assignee, createdBy, and _count.comments. This preserves compatibility with v0.9 clients and API-key integrations.
GET /api/tickets/:id
Fetch a single ticket by internal ID or display ID (e.g. V325813929). Includes full comments array, resolverGroup: { "id", "name" } | null, its resolver group, and canWork, whether the signed-in account may change it (Roles) (both also on the ticket returned by create, update and the other ticket actions; not on list rows).
POST /api/tickets
Create a new ticket. Requires Agent or Admin role.
Body:
{
"title": "string",
"overview": "string (markdown)",
"severity": 1,
"categoryId": "string",
"typeId": "string",
"itemId": "string",
"assigneeId": "string (optional)"
}
Response: Created ticket object (201). The assigneeId must be a resolver of the route (Assignees). A new ticket is always Open: a status in the body is ignored, not refused (set it with PATCH afterwards).
From a template (Ticket templates): { "template": "deploy-app", "values": { "app": "prometheus", ... } }, every other field optional; a field given wins over the template's default.
PATCH /api/tickets/:id
Update a ticket. Accepts any combination of fields. Requires Agent or Admin role.
The route must stay consistent: the type in the category and the item in the type (400 otherwise, as on create). Changing categoryId needs typeId and itemId too, and changing typeId needs itemId (400: "Changing the category needs typeId and itemId too").
dueAt (an ISO time, or null to clear it) sets the due date: audited (DUE_DATE_CHANGED), bumps updatedAt like any field edit, and notifies no one (no notification or webhook). A READ, REPORT or COMMENT API key can't set it.
expect (optional) is a precondition: the values the caller last saw for status, severity and/or assigneeId, e.g. { "status": "RESOLVED", "expect": { "status": "OPEN" } }. Checked inside the edit's row lock: if any differs, nothing is written and the answer is 409 { "error", "code": "PRECONDITION_FAILED", "field", "fields", "current": { "status", "severity", "assigneeId", "assignee" }, "changedBy" } (changedBy: who made the latest change of that field). Without expect a PATCH applies as before. An optional Idempotency-Key header (up to 128 of A–Z a–z 0–9 . _ : -; a 400 otherwise) makes a resend safe: if this account already made an edit with that key on this ticket, nothing is applied, written or notified again, and the answer is the ticket as it is now with replayed: true.
Setting
statustoCLOSEDrequires Admin role.PENDING(waiting on someone outside the team) pauses the resolve SLA clock; a ticket leaves it only by an edit (here, bulk or the ticket page), never by a comment, a report or a date.
All changes are recorded in the audit log automatically.
GET /api/tickets/:id/watchers, PUT /api/tickets/:id/watch, DELETE /api/tickets/:id/watch
Watchers follow a ticket: they're notified of its comments and status changes. Any signed-in user can watch a ticket. PUT starts watching and DELETE stops; both are idempotent for the caller. All three return the same body:
{
"watching": true,
"count": 2,
"watchers": [{ "id": "string", "username": "string", "displayName": "string" }]
}
watching says whether the caller is one of the watchers. The creator of a ticket, anyone who comments on it and anyone @mentioned in a comment start watching it automatically. Requests made with an API key (automation accounts, including POST /api/tickets/report) never auto-watch.
GET /api/tickets/:id/links, POST /api/tickets/:id/links, DELETE /api/tickets/:id/links/:linkId
Links between tickets: related, blocks / blocked by and parent / child. A link shows on both tickets, read from each side (if V1 blocks V2, V2 is blocked by V1). "Duplicate of" is separate (POST /api/tickets/:id/duplicate). Anyone who can read the ticket can list its links; creating and removing one needs Agent or Admin, and with an API key a WRITE key (READ, REPORT and COMMENT keys can only list). Tickets are addressed by internal or display id.
POST body, where type says how this ticket relates to the other one:
{ "type": "RELATED" | "BLOCKS" | "BLOCKED_BY" | "PARENT_OF" | "CHILD_OF", "ticket": "<other ticket's id or display id>" }
All three return the ticket's links (POST with 201), grouped as they read from it:
{
"related": [],
"blocks": [],
"blockedBy": [
{
"linkId": "string",
"ticket": {
"id": "string",
"displayId": "V123456789",
"title": "string",
"status": "OPEN",
"severity": 3,
"resolution": null,
"assignee": null
},
"createdAt": "2026-11-11T10:00:00.000Z",
"createdBy": { "id": "string", "username": "string", "displayName": "string" }
}
],
"parent": null,
"children": [],
"childSummary": {
"total": 0,
"resolved": 0,
"byStatus": { "OPEN": 0, "IN_PROGRESS": 0, "PENDING": 0, "RESOLVED": 0, "CLOSED": 0 }
}
}
childSummary.resolved counts children that are Resolved or Closed. DELETE takes the linkId from either ticket's list and removes the link from both.
Rules (each refusal says why):
- A ticket can't be linked to itself (
400). An unknown ticket is a404. - Two tickets have at most one link, of any type and in either direction (
409): V1 related V2 is the same link as V2 related V1, V1 blocks V2 and V2 blocks V1 can't both exist, and V1 can't both block and be related to V2. To change how two tickets are linked, remove the link and add the new one. - A ticket has at most one parent (
409); a parent can have any number of children. - Blocks and parent links can't form a cycle of any length (
409, naming the cycle): if V1 blocks V2 and V2 blocks V3, V3 can't block V1. The two kinds are checked separately. - Each link is stored once (the inverse is derived when reading) and goes when either ticket is deleted. Concurrent requests can't slip a duplicate, a second parent or a cycle past these checks: every create runs its checks and insert in one transaction holding the same advisory lock, and the database also refuses self-links, a second link between two tickets and a second parent.
- Shown, not enforced: links never change a ticket's status. A parent isn't resolved when its children are, and a ticket can be resolved while a ticket blocking it is still open.
- Silent: creating or removing a link sends no notifications (in-app or email) and no webhooks. It is recorded in the audit log of both tickets (
LINK_ADDED,LINK_REMOVED).
Labels
Free-form labels with a colour, several per ticket (#21). Anyone who can read tickets sees them; Agents and Admins add and remove them on a ticket and create new ones (also from the ticket's label picker); only Admins rename, recolour, describe and delete them (Admin › Labels). With an API key, labelling and creating labels need a WRITE key; a REPORT key labels through report.
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/labels |
Every label by name: id, name, color, description, createdBy, ticketCount, openTicketCount |
POST |
/api/labels |
Create: { "name", "color"?, "description"? } (201; 409 if the name is taken) |
PATCH |
/api/labels/:id |
Admin: { "name"?, "color"?, "description"? }. Tickets keep the label |
DELETE |
/api/labels/:id |
Admin: deletes it and removes it from every ticket; returns { "removedFrom": n } |
GET |
/api/tickets/:id/labels |
The ticket's labels: [{ "id", "name", "color" }] by name |
POST |
/api/tickets/:id/labels |
Add { "labels": ["name", …] } (names, any case); returns the ticket's labels. One it has already is a no-op |
PUT |
/api/tickets/:id/labels |
Make { "labels": [...] } the ticket's labels |
DELETE |
/api/tickets/:id/labels/:label |
Remove one, by id or name; one the ticket hasn't is a no-op |
- Names are trimmed, 1–40 characters, unique ignoring case (409), with no comma and no leading
-, andnoneis reserved (the query syntax uses these); each refusal is a 400 saying why. Colours are one ofgray,red,orange,amber,lime,green,teal,cyan,blue,indigo,purple,pink; without one, a name always gets the same colour. - A ticket has at most 20 labels (409). An unknown name is a 400 listing close matches.
- Tickets carry
labels: [{ "id", "name", "color" }]inGET /api/tickets/:idand in each row ofGET /api/tickets(loaded for the whole page in one query). - Silent: adding or removing labels sends no notifications and no webhooks and leaves the ticket's
updatedAtalone, like links. It is recorded in the ticket's audit log (LABEL_ADDED,LABEL_REMOVED); renaming, recolouring and deleting labels are not.
DELETE /api/tickets/:id
Delete a ticket and all associated comments, audit logs, and attachments. Admin only.
POST /api/tickets/bulk
Apply an action to many tickets at once. Agent or Admin. Tickets the caller isn't a resolver of are skipped (Roles); the answer is { "updated": n, "skipped": n }, updated counting only the tickets the action changed.
{ "ids": ["..."], "action": "reassign" | "close" | "setSeverity" | "setStatus", "value": "..." }
reassign to someone who isn't a resolver of every selected ticket's route is a 400 and nothing changes (Assignees).
Status changes follow the PATCH rules (#187): close and setStatus to CLOSED are Admin only (403), while an Agent may move a closed ticket back to an open status as PATCH allows; reopening (to Open, In Progress or Pending from Resolved or Closed) clears resolution, the duplicate link and resolvedAt; leaving Resolved for Closed clears resolvedAt too (auto-close keeps it); setStatus to RESOLVED gives a ticket with no resolution FIXED, the default of /resolve. A ticket that already has the value is not written, audited or notified; audit details are <old> → <new> as for a single edit. A reopen that would give a fingerprint a second open ticket (another ticket of it is open, or a ticket in the same batch is reopened for it, the most recently resolved winning) leaves that ticket as it is and the rest of the batch goes ahead: "fingerprintConflicts": { "displayIds": ["V…"], "reason": "An open ticket already has this fingerprint; report to it instead" }. An open ticket of the fingerprint that appears during the batch (a report at the same moment) still refuses the batch with that 409, as a single reopen.
Each ticket the action changes is notified, with its webhooks, as the same change made with PATCH would be (#185): a new status sends ticket.status_changed (and ticket.resolved), a new assignee ticket.assigned, one event per ticket, queued with the change. A ticket that already had the value, a ticket skipped, unassigning and setSeverity send nothing.
GET /api/export/tickets.csv
Stream the matching tickets (same filter params as GET /api/tickets, the search query q included) as CSV, in the ticket list's default order (a search: best matches first, at most 500). Agent or Admin. Streamed in batches of 500 inside one read-only REPEATABLE READ transaction, like the JSON export, and sharing its limit of two exports at once per server (429 with Retry-After beyond that); a failure after the download has started cuts the connection off. Text cells that start with =, +, -, @ or their fullwidth forms (also after leading spaces, tabs, line breaks, no-break spaces or a byte-order mark), a tab or a carriage return get a leading ', so a spreadsheet shows them as text rather than running them as formulas; severity is a number and is never prefixed. Cells holding a comma, ;, a tab, a quote or a line break are quoted.
GET /api/export/tickets.json
Every matching ticket with its comments, as one JSON document. Agent or Admin; a READ key may use it, and it counts against the key's rate limit. Same filter parameters as GET /api/tickets (including q); sort and page don't apply: tickets come in id order. include=audit adds each ticket's audit log. The response is an attachment (tickets-YYYY-MM-DD.json).
{
"version": 1,
"exportedAt": "2026-11-11T12:00:00.000Z",
"filters": { "q": "kind:alarm sev:<=2" },
"count": 1,
"tickets": [
{
"id": "…",
"displayId": "V123456789",
"title": "…",
"severity": 2,
"status": "OPEN",
"category": { "id": "…", "name": "Hosts" },
"assignee": { "id": "…", "username": "…", "displayName": "…" },
"links": [],
"comments": [
{
"id": "…",
"author": { "id": "…", "username": "…", "displayName": "…" },
"body": "…",
"key": null,
"attachments": []
}
],
"attachments": [{ "id": "…", "name": "run.log", "type": "text/plain", "size": 1234 }]
}
]
}
Per ticket: id, displayId, title, overview, severity, status, kind, workflowState, serviceState, resolution, category/type/item (id, name), assignee, createdBy, acknowledgedBy (id, username, displayName), duplicateOf, fingerprint, reportCount, lastReportedAt, giteaNumber, externalUrl, pagedAt, acknowledgedAt, acknowledgedVia, resolvedAt, dueAt, createdAt, updatedAt, labels (names), links, comments (oldest first), attachments (metadata only, never contents) and, with include=audit, audit.
Only these fields are exported (an explicit allow-list: no password hashes, API key material, emails, file paths or internal columns). It is streamed in batches of 500 tickets (a handful of queries per batch, not per ticket), inside one read-only REPEATABLE READ transaction, so it shows the database as it was when the export began. That transaction holds a database connection until the download ends (cut off after 15 minutes), so a server runs at most two exports (CSV and JSON together) at once (429 with Retry-After beyond that). If an error happens after the response has started, the connection is closed without finishing the document: the download fails and the file is not valid JSON, and the server logs the error.
Search
GET /api/search?q=<query>&limit=10
Cross-resource search over tickets and comments using Postgres plainto_tsquery with rank ordering: the best limit tickets and the best limit comments (25 unless given, at most 50; below 1 or not a whole number is a 400).
Response:
{
"tickets": [
/* ticket summaries */
],
"comments": [
/* comment snippets with ticket context */
]
}
Analytics
GET /api/analytics/summary?window=30
Agent or Admin. Queue figures now, plus the median resolution time over the window (window: 14, 30 or 90 days; anything else means 30). Open means Open, In Progress or Pending.
{
"windowDays": 30,
"openBySeverity": [
{ "severity": 1, "count": 2 },
{ "severity": 3, "count": 14 }
],
"statusCounts": [
{ "status": "OPEN", "count": 9 },
{ "status": "CLOSED", "count": 412 }
],
"queueByAssignee": [
{ "assigneeId": "clx…", "count": 6 },
{ "assigneeId": null, "count": 3 }
],
"ageBuckets": { "d1": 2, "d7": 5, "d14": 1, "older": 4 },
"medianResolutionHours": 9.4
}
openBySeverity and queueByAssignee count open tickets (only severities and assignees that have any; assigneeId: null is unassigned); statusCounts counts every ticket by status; ageBuckets counts open tickets by age: up to 1 day, 7 days, 14 days, older; medianResolutionHours is the median from creation to resolvedAt of the tickets resolved in the window (null when none).
Reports
The Reports page (/reports, linked from the Dashboard) and these read-only endpoints, open to any signed-in user and to READ keys. Days and weeks are cut in UTC (weeks start Monday) and every bucket is present, zero-filled. "Resolved" means resolvedAt, or the last update of a ticket closed without one. Answers are cached for 5 seconds per parameter set (reads only, so safe with two replicas).
| Endpoint | Returns |
|---|---|
GET /api/analytics/trend |
opened, resolved and open backlog at the end of each bucket |
GET /api/analytics/time-to-resolve |
median and 90th percentile (hours) and count, by kind and by route, for tickets resolved in the window |
GET /api/analytics/alarm-volume |
tickets opened per kind per bucket, and the top routes |
GET /api/analytics/noisy-fingerprints |
fingerprints with the most tickets or repeat reports: tickets, total reportCount, last seen, an example ticket, how many were resolved transient / not a failure |
GET /api/analytics/compare |
this window against the previous one of the same length, per kind and route: opened, resolved, median, the change, worst first |
GET /api/analytics/sla |
SLA targets met and missed per severity, window against previous, and open tickets past a target |
Parameters (all optional): days (7, 30 or 90, ending today; default 30) or from and to (YYYY-MM-DD, inclusive, at most 366 days); group (day or week); kind (comma list); categoryId, typeId, itemId; routeLevel (category, type or item: how routes are listed); limit (1–50, default 10) and sort (tickets or reports) for fingerprints; excludeResolutions (comma list; default DUPLICATE,MERGED,NOT_A_FAILURE, which are not work on the ticket and are left out of time to resolve; an empty value leaves nothing out). A bad value is a 400 with a message.
"Worse" means more tickets opened than in the previous window, or a slower median time to resolve; a change of +10% or more. A change is only reported when the previous window had at least 5 tickets (for the median, at least 5 resolved in each window); below that the row reads "too few to compare". Resolved numbers link to the closest list the search language can express (resolved or closed, updated in the window), which can differ from the count.
The SLA targets section (/api/analytics/sla, same window, kind and route filters) counts each ticket once, by when it was created, for each target its severity has now: changing a target in Admin › SLA changes these numbers for past windows too, as it does on the ticket list. It uses the same SQL as the list's sla: filter, so "breached" is exactly what sla:ack-breached and sla:resolve-breached list. The met share is met ÷ (met + breached); tickets still inside their target are shown as running and left out, so a fresh window is not marked down for tickets that have not had time to miss. It is "worse" when the share fell by 10% or more (relative, as above) and judged only when the previous window had at least 5 settled tickets, else "too few to compare". Tickets resolved as one of excludeResolutions are left out; a query cannot exclude them, so a breached count with some reads (+n) and its list shows n more. "Open past it now" counts open tickets of any creation date past the target and links to status:open,in_progress,pending sla:…-breached.
Saved Views
Filter presets. A view belongs to its owner, who can share it with every signed-in user. A view is only filters: applying one sends them to the ordinary ticket list with your own credentials, so it never shows you a ticket you could not already list.
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/saved-views |
The caller's views and every shared view, each with shared, owner (id, username, displayName), mine and canEdit |
POST |
/api/saved-views |
Create — { name, filters, shared? } (a copy of a shared view is just a create) |
PATCH |
/api/saved-views/:id |
Rename, edit filters, share or unshare — { name?, filters?, shared? } |
DELETE |
/api/saved-views/:id |
Delete |
Changing or deleting a view is for its owner, or an Admin when it is shared; anyone else gets 403 on a shared view and 404 on a private one (its existence isn't revealed). Names are unique per owner only. Deleting a user deletes their views, shared ones included. API keys follow their scope: READ, REPORT and COMMENT keys can list views but not create, share or delete.
filters holds the list's parameters as set in the UI (status, severity, assigneeId, categoryId, …) and, for a typed query, q (syntax). A q that doesn't parse is a 400; names in it (users, route) are resolved each time the view is used. Views saved before q existed keep working unchanged.
Notifications
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/notifications |
Caller's notifications, newest first |
POST |
/api/notifications/read |
Mark specific or all — returns { updated } |
Notifications are created on assignment, @mention, and status → RESOLVED, and for watchers of a ticket on each new comment and status change (kinds watch.comment and watch.status; anyone already notified of the same event another way is skipped). Whoever made the change is never notified of it, whatever the kind (an Admin assigning themself, the resolver of their own ticket), in the app or by email. Retention: a daily job on every replica deletes read notifications more than 90 days old and any notification more than 365 days old (idempotent, so two replicas running it at once just share the work). Watcher notifications are on in-app and off by email by default (watching in User.notificationPrefs). Email delivery is attempted when SMTP is configured and the target user has email notifications enabled in User.notificationPrefs. Each row's data holds the ticket's displayId and title when it was sent and byName, the display name of whoever acted (absent for a change no one made; watch.status adds from and to); each row also comes with its current ticket (id, displayId, title), which the client uses for rows from before data was filled (#225). A link to /<displayId>#comment-<commentId> opens the ticket's Comments tab at that comment.
Live updates
GET /api/events
A server-sent event stream for the caller (any signed-in user, or an API key of any scope). Events carry ids and kinds only, never ticket text; a client refetches through the normal API:
| Event | Data | Sent when |
|---|---|---|
ready |
{ resumed } |
First; resumed: false means "refetch what you show" (no cursor, or it couldn't be replayed) |
ticket.changed |
{ id, displayId } |
The ticket's own fields or status changed, or it was deleted |
comment.changed |
{ ticketId, displayId } |
A comment was added, edited or deleted |
ticket.activity |
{ ticketId, displayId } |
Its links, watchers, attachments or audit log changed |
notification |
{} |
Only to its user: a notification was added or marked read |
superseded |
{} |
Closed for the same user's newer stream (at most 5 per user; the oldest goes) |
A USER account's stream is never told about private notes: a note added, edited or deleted, or its attachments (Agents, Admins and API keys are; the account's role is read on every check). The stream ends, without an event, once its credential stops working, checked on every poll as each request is: the session signed out, ended by a password change or Sign out of all devices, or expired; the API key revoked or expired; the account disabled or deleted (#202).
Each server replica with at least one stream open checks the database every 2 seconds (LIVE_POLL_MS) and sends at most one event per ticket per check; with none open it doesn't check. Changes are found by PostgreSQL's xmin (the transaction that last wrote each row), so writes from the other replica, the Gitea importer (which keeps Gitea's timestamps) or anything else are seen like the replica's own; deletes are found by counting. Every event's id is a cursor: send it back as Last-Event-ID (or ?cursor=) when reconnecting, to either replica, and what changed in between is replayed (within 5 minutes and 200 changes; otherwise ready says resumed: false). A replay can't see a delete that left no audit entry (the importer's comment deletions, unwatching). A : heartbeat comment with the current cursor comes every 20 seconds. The response sets X-Accel-Buffering: no, and the bundled nginx passes /api/events through unbuffered. A replica refuses streams beyond LIVE_MAX_STREAMS with 503 and Retry-After. A request whose Sec-Fetch-Dest is anything but empty (a browser loading it as an image, a frame or a page, rather than fetch or EventSource) is refused with 403 and opens no stream. Opening a stream counts as one request against the rate limits. Metrics: ticketing_live_streams, ticketing_live_events_total{kind}, ticketing_live_poll_seconds.
The web client keeps one stream per tab (read with fetch, so it sends the usual Authorization header), reconnects with backoff (1 s doubling to 30 s, with jitter), closes it after a minute in a hidden tab and reopens it with a refetch when the tab is shown again. While it is up, the notification polls slow from every minute to every five.
Attachments
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/tickets/:id/attachments |
Upload (multipart, field file) |
POST |
/api/comments/:id/attachments |
Upload on a comment: its author, an Agent or an Admin |
GET |
/api/attachments/:id |
Stream with original filename |
DELETE |
/api/attachments/:id |
Uploader or Admin |
An upload with the form field internal=true (Agents and Admins; for an image pasted into a private note) is hidden from USERs, and so is a file on a private note: a 404 for them, in the list and the download. Size limit 25 MB per file (413). Each account's attachments may take at most ATTACHMENT_QUOTA_MB (default 200 MB, the sum of their recorded sizes, across replicas): an upload past it is a 413 saying how much is in use. Responses carry the file's metadata, never where it is stored. Deleting an attachment, a comment or a ticket removes the files once the delete has committed (a file already missing is logged, not an error). npm run attachments:sweep in server/ lists files in UPLOADS_DIR that no attachment row names (left behind by earlier versions' deletes, or by a crash between a delete and its file removal): a dry run unless given --delete. It only considers files named like stored uploads, at the top of the folder, older than --min-age-minutes (default 60), so it never touches profile pictures or an upload in progress. The last line is SWEEP {json} with the counts. Storage path is controlled by UPLOADS_DIR (defaults to ./uploads in dev, /data/uploads in the Docker image backed by the uploads volume).
Paging
Admin-only, read-only. A background job on every server replica pages the owner through Pushover for every ticket that is open (OPEN, IN_PROGRESS or PENDING) at severity 1 or 2 (#67; this moves the n8n Pager into TicketingSystem). It looks at the tickets as they are every 10 seconds, so tickets the Gitea importer writes (late, with Gitea's createdAt) page like any other.
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/paging/status |
Requested and effective mode and why, credentials configured (yes/no only), baseline time, counts, last run, last error |
GET |
/api/paging/log |
Everything the engine did or would have done, newest first (?page, ?pageSize ≤ 200, ?mode, ?ticket) |
GET |
/api/paging/comparison |
Shadow's page decisions against the n8n Pager's pages (ticket.pagedAt): per ticket, the difference, and disagreements both ways |
There is no endpoint that sends anything (no test page). API keys belong to Agents, so no key can read these.
Modes (PAGING_MODE): off does nothing; shadow (the default) runs every rule and records what it would have done in its own tables, sends nothing and never changes a ticket (the n8n Pager stays the real pager and keeps writing pagedAt/acknowledgedAt through POST /paged and /acknowledge); live sends through Pushover and records pages and acknowledgements on tickets with the same calls the Pager uses, so the paging filters, the audit log and the ticket.acknowledged webhook work as before. live without PUSHOVER_TOKEN, PUSHOVER_USER or a valid PAGING_ACK_USERNAME logs an error at startup and runs as shadow, and Admin › Paging, the status API and ticketing_paging_mode{effective="shadow",requested="live"} say so. If the database doesn't answer when the server starts, the account can't be checked: the server runs as shadow, says it is waiting (not misconfigured), retries every 30 seconds and switches to live on its own when the check succeeds; an account that doesn't exist is a configuration problem and stays one until fixed. PUSHOVER_FAKE=true makes live use an in-process fake that sends nothing, for trying live locally; it is shown as live_fake in ticketing_paging_mode and as a red "FAKE Pushover client" banner, and in production (NODE_ENV=production) it is refused: the server logs an error and runs as shadow.
Rules: a page is Pushover emergency priority, titled Sev N · <displayId> <title> with a link to the ticket (title, severity, display id and link only, never the body), retry 30 s (severity 1) or 60 s (severity 2), expire 3 h, tag ticket-<displayId>. Receipts are polled at most every 5 s; an acknowledgement on the phone is recorded for PAGING_ACK_USERNAME via Pushover (<device>), and one made with the Acknowledge button cancels the Pushover page by tag. A page still unacknowledged after 3 hours pages again. A ticket resolved, closed, deleted or lowered below severity 2 has its unacknowledged page cancelled (an acknowledged one is just forgotten). Its page has ended, so the ticket also forgets that page's acknowledgement (audited ACKNOWLEDGEMENT_CLEARED; pagedAt stays) wherever severity or status changes (edit, bulk, /resolve), in every mode and with paging off: raised back to 1–2 or reopened, it pages again and shows the new page unacknowledged. The engine looks every 10 s, so lowered and raised back between two runs is still the same page. After an acknowledgement, new comments (not the n8n Pager's own) send one priority −1 push at most every 30 minutes, counting what arrived in between. More than 3 pages in one run (first pages and re-pages) go out as one Sev N · M tickets opened at once summary covering them all. At most one Pushover request a second. A failed request (network, timeout, 429, 5xx) is retried after 5 s, 15 s, 30 s, 1 min, 2 min, then every 5 min, until the ticket stops paging; another 4xx (bad credentials) is not retried, and shows as the last error and in ticketing_paging_pushover_failures_total{kind="client"} (pages refused that way are queued once more when the server starts, in case the credentials were fixed).
Baseline: when a mode first takes over (the first run, or after off), every ticket open at severity 1–2 joins its baseline and never pages, so turning paging on doesn't page the backlog; a ticket leaves the baseline when it closes or is lowered, and pages normally if raised again. When one mode takes over from the other (shadow → live), it starts from that mode's view instead: its baseline carries over, a ticket it was paging is taken over without a new page if the real Pager's page (ticket.pagedAt) shows on it, and every other qualifying ticket pages. A replica of the other mode that ran in the last 2 minutes (a rolling deploy) is waited for, so the switch happens once. A page taken over becomes live's own when live re-pages it: that page's receipt is polled like any other, so acknowledging it on the phone is recorded. A replica running as shadow only while its live check waits for the database never takes the engine over from live.
Two replicas: one run at a time holds a lease on the engine's row (database time, 60 s, renewed after each request; a dead replica's lease expires and another takes over). A decision and everything it changes are one transaction; a ticket can have one open cycle per mode (a unique index) and a page per cycle and page number is a unique row, claimed before it is sent. A page left mid-send by a replica that died is cancelled by tag before it is sent again, so at worst a page is delivered twice with the first one silenced; it is never lost.
Metrics: ticketing_paging_mode{effective,requested}, ticketing_paging_actions_total{mode,action}, ticketing_paging_pushover_failures_total{kind} and ticketing_paging_oldest_unacknowledged_seconds.
Heartbeat: ticketing_paging_last_run_timestamp_seconds is the Unix time this replica last finished an engine run, ok or failed (0 before its first; a run that found the lease taken, or waited for the other mode, doesn't count), and ticketing_paging_run_errors_total counts runs that failed (an error during the run, a lost lease, or the database not answering when the run started). The engine runs every 10 s on whichever replica holds the lease, so with two replicas the one that doesn't hold it keeps an old timestamp: read it only as the max across replicas, never per replica (a lease is released at the end of each run, so a "lease held" gauge would be 0 at almost every scrape and was left out). Suggested alerts (the rules live in TWS-Semaphore); off also runs, so gate on the mode:
# Stalled: no replica has finished a run for 5 minutes while the pager is live (for: 2m)
(time() - max(ticketing_paging_last_run_timestamp_seconds) > 300)
and on() (max(ticketing_paging_mode{effective="live"}) == 1)
# Failing: more than half of the ~60 runs in 10 minutes failed (for: 5m)
(sum(increase(ticketing_paging_run_errors_total[10m])) > 30)
and on() (max(ticketing_paging_mode{effective="live"}) == 1)
5 minutes is 30 missed runs and five lease lengths: a crashed leader's lease expires after 60 s and the other replica takes over, so a failover or a rolling deploy never trips it. If every replica is down the series vanish and time() - max(...) returns nothing; that case is the up alert's (or add or absent(ticketing_paging_last_run_timestamp_seconds)).
Moving from the n8n Pager to live:
- Deploy with
PAGING_MODEunset (shadow). Nothing else is needed. - Leave it running for a while and read Admin › Paging: the verdict (e.g. "37 of 37 pages match within 6 minutes; 0 disagreements") and both disagreement lists. A storm summary the Pager recorded on one ticket matches its other tickets too.
- Put
PUSHOVER_TOKENandPUSHOVER_USER(the values the n8nPushovercredential holds) in the server's Kubernetes Secret, and setPAGING_ACK_USERNAME(e.g.josh). - Check that nothing is paging unacknowledged (Admin › Paging, "Would be paging now"), then turn the n8n Pager workflow off.
- Set
PAGING_MODE=liveand roll the servers. Admin › Paging should show the green live banner; the log shows the switch, what was taken over and what was paged.
Never run the n8n Pager and live at once: every ticket would page twice. To go back, set PAGING_MODE=shadow (or off) and turn the n8n Pager on again.
Audit
Admin-only, read-only (#42). Security events, in Admin › Audit:
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/audit |
Entries, newest activity first (?page, ?pageSize ≤ 200, ?kind one or several comma-separated, ?user the account concerned or acting, ?key a key's id or prefix, ?from/?to ISO times; a per-hour row matches when its first..last use overlaps the range) |
GET |
/api/audit/summary |
Last 24 hours and 7 days: sign-ins, failures, lockouts, keys used and their requests, new key addresses, refused keys and scope refusals |
Kinds: login_succeeded, login_failed (wrong password, or an unknown account), login_limited (refused by LOGIN_RATE_LIMIT, on sign-in, reset-link use or a password change, or by the per-username limit: on says which), password_changed, reset_link_created, reset_link_used, sessions_revoked (sign out of all devices; byAdmin), account_created, account_disabled and account_enabled (#190), avatar_changed and avatar_removed (profile pictures; setBy), key_created, key_revoked, key_replaced (regenerate), keys_revoked_role_change, key_used, key_new_address, key_refused (unknown, revoked or expired key, or a disabled account's) and key_scope_refused (403; a PROVISION key's refusal on a provisioning route adds its reason). An event made with an API key (a PROVISION key's) carries that key's id, name and prefix in detail.byKey. Each has the time, the account and the acting account, the key's id, name and prefix at the time, the client address (req.ip, through TRUST_PROXY), the user agent (120 characters) and a small detail. Never stored: passwords, tokens, API keys or their hashes, reset tokens, anything derived from an unknown key, and the username typed into a failed sign-in unless it is an existing account's.
Key use is one row per key, address and hour with a request count and first/last time, updated in place; the first use of a key from an address it hasn't used within the retention adds a key_new_address entry. Refused keys (per address), scope refusals (per key) and lockouts (per address) are counted the same way. Requests only count in memory; each server process adds its counts to the rows every 10 seconds (an upsert that adds, so replicas don't overwrite each other), so a process that dies loses at most its last 10 seconds of these counts. Other events are written as they happen without delaying the request, and a failed write is logged, never returned. Entries whose last activity is older than AUDIT_RETENTION_DAYS (90) are deleted hourly by every replica (idempotent). Sign-ins are also counted in ticketing_sign_ins_total{result="succeeded"|"failed"|"limited"}.
Settings
Admin-only, with a session (an API key is refused). Both apply on the next run or report, with no restart:
autoCloseDays(whole number, 0 to 3650, default 14): resolved tickets are closed this many days after they were resolved, by the hourly job. 0 turns auto-close off.reopenWithinHours(whole number, 0 to 8760, defaultREOPEN_WINDOW_HOURS, else 24): a repeatPOST /api/tickets/reportof a fingerprint resolved less than this long ago reopens that ticket. 0 always opens a new ticket.
Neither is per route. Nothing is saved until an Admin changes a setting, so the defaults are today's behaviour.
GET /api/settings:{ "settings": [{ key, value, default, saved, updatedAt, updatedBy }], "history": [{ key, oldValue, newValue, changedBy, createdAt }] }(the last 30 changes).PUT /api/settings: partial update, e.g.{ "autoCloseDays": 30 }. 400 with the reason for an invalid value or an unknown key (nothing is saved). Each change is recorded as old → new, with who and when.
In the UI: Admin › Admin settings (not the per-user Settings page).
Recurring tickets
Admin-only; changes need a signed-in session (no API key). A schedule is a 5-field cron expression (minute hour day-of-month month day-of-week; when both days are set, either matches, as in cron) read in an IANA time zone (default UTC), plus a ticket template: title, overview, severity, category/type/item, optional assignee and kind. {date} (YYYY-MM-DD), {month} (e.g. November 2026) and {year} in the title and overview are filled in with the run's date in the schedule's zone; other braces are left as typed.
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/recurring-tickets |
List, with next run, last run and its result or error |
GET |
/api/recurring-tickets/preview?schedule=…&timeZone=… |
The next 3 runs and the schedule in words, or 400 saying what is wrong |
POST |
/api/recurring-tickets |
Create — { name, schedule, timeZone?, enabled?, title, overview, severity, categoryId, typeId, itemId, assigneeId?, kind? } |
GET |
/api/recurring-tickets/:id |
Read |
PATCH |
/api/recurring-tickets/:id |
Update (any of the fields) |
DELETE |
/api/recurring-tickets/:id |
Delete; tickets it created stay |
POST |
/api/recurring-tickets/:id/run |
Create one ticket now (201, as GET /api/tickets/:id returns it), enabled or not; the next run doesn't move |
Runs: every server replica checks for due schedules every RECURRING_POLL_MS; a schedule's row is locked while its ticket is created and its next run set, in one transaction, so each occurrence creates exactly one ticket. The ticket is created like any other (audit entry CREATED with "From schedule: ", the owner — who created the schedule — as creator and watcher, notifications and webhooks) and keeps a link to its schedule. Missed runs are not backfilled: if the servers were down, one ticket is created when they are back and the schedule moves to its next future occurrence; a schedule turned back on (or given a new expression or zone) starts from its next occurrence. A run that fails (say its category was deleted) records the error on the schedule and waits for its next occurrence. Across DST, a time skipped by the clock change runs an hour later that day and a repeated time runs once.
Due offset: dueOffsetMinutes (optional, whole minutes, 1 to 525600 = a year; null or absent: none) gives each ticket the schedule creates a due date that long after the moment it is created, in the same transaction, by a scheduled run (a single ticket after an outage is counted from when it is created, not from the missed occurrence) or by Run now. The form's "Due" field takes none or N minutes, hours or days and shows the due time the next run's ticket would get. The date counts as due/overdue like a hand-set one and, as with one, notifies no one. Schedules saved before this have no offset and behave as before.
Metrics: ticketing_recurring_runs_total{result,trigger} (created/failed; schedule/manual) and ticketing_recurring_schedules_enabled.
Ticket templates
A template has a unique name (deploy-release: lowercase words and hyphens), a title and a Markdown body with placeholders, the placeholders it asks for (name, label, required (default true), optional default, multiline for a text area), and optional defaults: kind, severity, a route (categoryId, typeId, itemId, all or none) and assigneeId. Placeholders: {name} (letters, digits, underscore) is filled with the value given; {{name}} is the literal text {name}; every other brace stays as typed. A value is inserted as is, never read for placeholders; there is nothing else (no conditionals or loops). Every placeholder used must be listed (400 otherwise). Creating templates is for Agents and Admins, with a session or a WRITE API key; editing and deleting one is for its owner (createdById, who created it) or an Admin (#201), so Goddard keeps its own deploy templates and no one else's; READ, REPORT and COMMENT keys and Users can't. The seeded templates have no owner, so only Admins change them until an Admin hands one over (PATCH with createdById: an enabled Agent or Admin; only an Admin changes the owner). Listing them and creating tickets from them is for anyone who can create tickets, API keys included. Who created and last changed a template is recorded (createdById, updatedById).
From a template: POST /api/tickets with "template": "<name>" and "values": { ... }. A required placeholder without a value (blank counts as none) or default, a value for a placeholder the template doesn't list, an unknown template, or a ticket still without a severity or route is a 400. Fields given in the request win over the template's (a route is taken whole; "assigneeId": null leaves it unassigned). The CREATED audit entry says "From template: ". Seeded by migration m0022_ticket_templates, from the deploy tickets in use: deploy-release ("Deploy TicketingSystem {version}") and deploy-app ("Update {app} to {version}"), Enhancement, severity 5, no route (no category is certain to exist), editable afterwards.
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/ticket-templates |
List, by name (Agents and Admins) |
GET |
/api/ticket-templates/:id |
Read, by id or name |
POST |
/api/ticket-templates |
Create (Agent or Admin; WRITE key) — { name, title, overview, description?, placeholders?, kind?, severity?, categoryId?, typeId?, itemId?, assigneeId? }; 409 for a taken name |
PATCH |
/api/ticket-templates/:id |
Update (owner or Admin; any of the fields, createdById Admin only); tickets already made don't change |
DELETE |
/api/ticket-templates/:id |
Delete (owner or Admin); tickets made from it stay |
Approval requests
Automation asks a person a question on a ticket and waits for the answer, instead of polling comments for "approve". The ticket page shows an open request above the title with Approve and Reject (and an optional note) to whoever may decide, each confirmed once; everyone else sees it read-only. Once closed, the page shows the latest outcome in one line.
- Who decides:
approver(a username or user id) only, or any Admin when none is named, and only with a signed-in session: an API key never decides. The approver named must be an Admin or a resolver of the ticket (an Agent who may work it), enabled, and not the requester (400 otherwise, #201); the requester never decides their own request, not even as one of the Admins. - Who asks: Agents and Admins, and a
WRITEAPI key;READ,REPORTandCOMMENTkeys can only read. The creator or an Admin may cancel an open request. One open request per ticket (409 for a second; ask again once it is closed). - Recorded once: a decision stores who, when, approve or reject and the note, adds a comment by the decider (
**Approved.** <note>with the question quoted) and audit entries (APPROVAL_APPROVEDorAPPROVAL_REJECTED); it can't be changed afterwards (409). Creating and cancelling are audited too. - Delivery: with a
callbackUrl, closing the request (decided or cancelled) POSTs to it through the webhook delivery queue: same retries,X-Ticketing-Event(approval.decidedorapproval.cancelled),X-Ticketing-Deliveryto dedupe, andX-Ticketing-SignaturewhenAPPROVAL_CALLBACK_SECRETis set. Redirects are not followed. The body is a webhook body whose payload is{ ticketId, approval: { id, status, decision ("approve", "reject" or null), question, note, approver, requestedBy, closedBy, closedAt, createdAt }, ticket }. A decision also fires theapproval.decidedwebhook event for subscribed webhooks. Metric:ticketing_approval_callbacks_total{result}(sent,retry,failed,refused). - Allowed hosts: an API key chooses the URL, so the server only calls hosts listed in
APPROVAL_CALLBACK_HOSTS(comma-separated host names, each optionally with:port; exact matches, no wildcards). Empty, the default, refuses everycallbackUrl(400). The host is checked again before each attempt, so removing it stops what is queued. The URL is never returned by the API;hasCallbackandcallback(status, attempts, response, error) show how delivery went. - Polling (a fallback):
GET /api/approvals/:idorGET /api/tickets/:id/approvals, untilstatusis notOPEN.
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/tickets/:id/approvals |
The ticket's requests, newest first, each with canDecide and canCancel for the caller |
POST |
/api/tickets/:id/approvals |
Ask — { question (Markdown), approver?, callbackUrl? } (201; 409 while one is open) |
GET |
/api/approvals/:id |
One request |
POST |
/api/approvals/:id/decide |
{ decision: "approve" | "reject", note? } (signed in: the approver, or an Admin when none is named; 409 once closed) |
POST |
/api/approvals/:id/cancel |
{ note? } (its creator or an Admin; 409 once closed) |
With n8n (the Decom Instance pattern): an HTTP Request node asks, then a Wait node set to Resume: On Webhook Call with HTTP Method: POST waits for the answer (set a Limit Wait Time as a backstop, and allow n8n's host in APPROVAL_CALLBACK_HOSTS):
POST /api/tickets/{{ $json.displayId }}/approvals
X-Api-Key: sk_… (a WRITE key)
{
"question": "Decommission **{{ $json.instance }}**? Replication is stopped and the last backup is verified.",
"approver": "josh",
"callbackUrl": "{{ $execution.resumeUrl }}"
}
After the Wait node, {{ $json.body.payload.approval.decision }} is approve, reject or null (cancelled). If the wait times out, GET /api/approvals/<id> (the id the first call returned) says where it stands.
Webhooks
Admin-only. Outgoing webhooks fire on ticket.created, ticket.status_changed, ticket.assigned, ticket.resolved, ticket.acknowledged, comment.created (public comments only: a private note sends none, since a receiver may pass on what it gets) and approval.decided (payload approval: see Approval requests).
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/webhooks |
List |
POST |
/api/webhooks |
Create — { name, url, events, secret? } |
PATCH |
/api/webhooks/:id |
Update |
DELETE |
/api/webhooks/:id |
Delete |
POST |
/api/webhooks/:id/rotate-secret |
Rotate secret |
GET |
/api/webhooks/:id/deliveries |
Delivery log, newest first (?limit ≤ 200) |
POST |
/api/webhooks/deliveries/:deliveryId/redeliver |
Send a delivery again (202) |
Delivery: each event is queued in the database, one delivery per subscribed webhook, in the same transaction as the change that caused it (an edit and its events are saved together or not at all, and never wait for notification emails), and sent at once by a background job that every server replica runs (a delivery is claimed by one replica at a time, so it isn't sent twice in parallel). A delivery that gets no 2xx within 10 seconds is retried after 10 s, 30 s, 2 min, 10 min, 30 min, 1 h, 3 h and 6 h (9 attempts, about 11 hours), then marked failed. Pending deliveries survive restarts and deploys. Delivery is at least once: a server stopped mid-send leaves the delivery to be sent again a minute later, so a receiver that must not act twice should dedupe on X-Ticketing-Delivery. Disabling a webhook fails what's queued for it, including a delivery being sent at that moment (its outcome isn't recorded, so it isn't retried when the webhook is enabled again) and events a change is queueing at that moment (the disable waits for it). Admin › Webhooks › Deliveries shows each delivery's status, attempts, response and payload, and redelivers one (same id, same body, a fresh set of attempts). Sent deliveries are kept 14 days, failed ones 30.
Destinations (#204): only public addresses, unless the host is in WEBHOOK_ALLOWED_HOSTS. A URL whose host is, or resolves to, a loopback, private (RFC 1918), CGNAT 100.64.0.0/10 (Tailscale addresses), link-local, unique-local, multicast or reserved address, or that names an internal host (localhost, *.local, *.internal, *.lan, *.home.arpa, *.svc, *.cluster.local, a single-label name such as n8n), is refused with a 400 when the webhook is saved, and again when each delivery is sent: the name is resolved then, and the connection goes to the address that was checked. A refused delivery fails at once with no retries (redeliver it once the host is allowed); a name that doesn't resolve is retried as usual. Redirects are never followed: a 3xx is a failed attempt. WEBHOOK_ALLOWED_HOSTS takes the format of APPROVAL_CALLBACK_HOSTS (host names or IP literals, each optionally :port, exact matches); a listed host is not checked further, so a webhook to n8n by tailnet name or address needs that name or address listed.
Headers: X-Ticketing-Event (the event name), X-Ticketing-Delivery (the delivery id, the same on retries and redeliveries), X-Ticketing-Timestamp: <unix seconds> and X-Ticketing-Signature: sha256=<hex>, the HMAC-SHA256 of <timestamp>.<raw request body> using the webhook's secret. The timestamp is the attempt's, so a retry hours later is signed fresh.
Body: { "event", "timestamp" (when it happened, ms), "payload" }. The payload carries the event's ids (ticketId, and commentId, assigneeId, from/to, acknowledgedById/via where they apply) plus ticket, a snapshot taken when the event happened: { id, displayId, title, severity, status, kind, cti: { category, type, item }, assignee (username), fingerprint, url }. url needs CLIENT_URL; without it, it's null.
Metrics: ticketing_webhook_deliveries_total{result} (sent, retry, failed, refused: destination not allowed), ticketing_webhook_deliveries_pending, and ticketing_webhook_oldest_pending_seconds (0 when the queue is empty; rising means a receiver is down or the queue is stuck).
Comments
POST /api/tickets/:id/comments
Add a comment. Markdown body. @mentions are parsed and fire notifications to matched users.
{ "body": "string (markdown)", "internal": false }
"internal": true writes a private note (#29): Agents and Admins (and Agents' API keys) only, 403 for a USER. A USER never sees a note: not on the ticket (nor in its comment count), the attachments list or downloads, search, the audit log, notifications or @mention emails (a USER @mentioned in a note is neither told nor made a watcher); it sends no comment.created webhook. Live updates carry ids only, so a USER's open ticket may refetch when a note is added and finds nothing new. A comment stays a note or public for good; the exports (Agents only) mark notes "internal": true. Images the body references as /api/attachments/<id> that the author uploaded to this ticket and no comment holds yet (pasted ones) become the comment's attachments and take its visibility; the same on PATCH. A note is a 404 for a USER on PATCH and DELETE too.
DELETE /api/tickets/:id/comments/:commentId
Delete a comment. Authors may delete their own; Admins may delete any.
Audit Log
GET /api/tickets/:id/audit
Retrieve the full audit log for a ticket, ordered newest first.
Action types:
| Action | Detail |
|---|---|
CREATED |
— |
STATUS_CHANGED |
e.g. Open → In Progress |
SEVERITY_CHANGED |
e.g. SEV 3 → SEV 1 |
ASSIGNEE_CHANGED |
e.g. Unassigned → Josh |
REROUTED |
e.g. OldCat › OldType › OldItem → NewCat › NewType › NewItem |
TITLE_CHANGED |
New title |
OVERVIEW_CHANGED |
— |
COMMENT_ADDED |
Comment body |
COMMENT_DELETED |
Deleted comment body |
ATTACHMENT_ADDED |
Filename |
ATTACHMENT_REMOVED |
Filename |
LINK_ADDED |
The link as this ticket reads it, e.g. Blocked by V123: title |
LINK_REMOVED |
The removed link, as for LINK_ADDED |
LABEL_ADDED |
The labels added, e.g. backup, plex |
LABEL_REMOVED |
The labels removed |
APPROVAL_REQUESTED |
From <approver or Admins>: <question> |
APPROVAL_APPROVED |
The decider's note, if any |
APPROVAL_REJECTED |
The decider's note, if any |
APPROVAL_CANCELLED |
The note, if any |
CTI (Category / Type / Item)
GET /api/cti/categories
GET /api/cti/types?categoryId=<id>
GET /api/cti/items?typeId=<id>
Read the CTI hierarchy. Used to resolve IDs when creating/rerouting tickets.
Admin-only write operations:
| Method | Endpoint | Body |
|---|---|---|
POST |
/api/cti/categories |
{ "name": "string" } |
PUT |
/api/cti/categories/:id |
{ "name": "string" } |
DELETE |
/api/cti/categories/:id |
— |
POST |
/api/cti/types |
{ "name": "string", "categoryId": "string" } |
PUT |
/api/cti/types/:id |
{ "name": "string" } |
DELETE |
/api/cti/types/:id |
— |
POST |
/api/cti/items |
{ "name": "string", "typeId": "string" } |
PUT |
/api/cti/items/:id |
{ "name": "string" } |
DELETE |
/api/cti/items/:id |
— |
Deleting a category cascades to all child types and items, and to what groups own of them.
Resolver groups
A resolver group (#172) has a name (unique ignoring case, at most 60 characters), a description, members (Agent and Admin accounts) and owned CTI nodes: categories, types or items, each with at most one owner. A ticket's group is the owner of its route's most specific owned level (item, then type, then category); with none it is unowned. Admin only; each change is an event in Admin › Audit (group_*, kept for AUDIT_RETENTION_DAYS).
| Method | Endpoint | Body / notes |
|---|---|---|
GET |
/api/groups |
Every group with members and routes (owned nodes, with their path) |
POST |
/api/groups |
{ "name", "description"? } (201; 409 if the name is taken) |
GET |
/api/groups/:id |
One group |
PATCH |
/api/groups/:id |
{ "name"?, "description"? } |
DELETE |
/api/groups/:id |
204; 409 while it owns anything (move its nodes to another group first). Memberships go with it |
POST |
/api/groups/:id/members |
{ "userId" }: an Agent or Admin (a User is a 400) |
DELETE |
/api/groups/:id/members/:userId |
Remove a member |
POST |
/api/groups/:id/routes |
Exactly one of { "categoryId" }, { "typeId" }, { "itemId" }; another group's node is a 409 unless "move": true. "unassignNonMembers" (default false): see below |
DELETE |
/api/groups/:id/routes/:routeId |
Give a node up (it inherits its parent's owner again, or is unowned). ?unassignNonMembers=true: as when moving, below |
GET |
/api/groups/:id/routes/preview?categoryId= (or typeId, itemId) |
What giving it the node would do: { owner, tickets, openTickets, assignedOutside, assignees } (tickets: open or resolved) |
GET |
/api/groups/:id/routes/:routeId/preview |
What giving it up would do: { after, tickets, openTickets, assignedOutside, assignees } (after: null: unowned) |
GET |
/api/groups/unowned |
The nodes nobody owns, with their unowned open tickets (Admin › Groups › "Needs an owner") |
- The migration (
m0027_resolver_groups) creates one group, TWS, owning every category that existed then, with every Admin and Agent (not Users) as members, so nothing changes on day one. Categories created afterwards are not owned by TWS: they are unowned until an Admin assigns them (CTI config shows them as "Unowned"). - Deleting a CTI node removes its ownership; deleting an account removes its memberships. A member made a User keeps the membership but is not a resolver.
- Only a group's members (and Admins) change its tickets (Roles).
- Moving a node to another group moves its open and resolved tickets with it (closed ones stay as they were). Their assignees who aren't resolvers there keep them unless the request says
"unassignNonMembers": true, which unassigns them in the same transaction, each audited on the ticket as a hand-off (Mia → Unassigned (moved Services › Media from TWS to Media)); the response then hasunassigned. Giving a node up (DELETE …/routes/:routeId?unassignNonMembers=true) does the same for the tickets that pass to the group above. Admin › Groups confirms every change that takes tickets from another group with the count ("3 open or resolved tickets are assigned to people not in Media") and the choice, Unassign them (the default) or Keep assignees; giving a group an unowned node, or giving one up so it falls back to another group, asks the same whenever someone outside the new owner holds one of its tickets, and is one click otherwise. - Giving a node up with nothing owned above it makes it unowned: any Agent can work its tickets. The confirmation says so with the ticket count and points to Move for handing it to another group. Admin › Groups lists every category with no owner under Needs an owner (collapsed: each opens to the types and items under it that inherit no owner), with their open tickets and a group picker (hidden when there are none).
- Changes of ownership and ticket writes don't overlap. Every change of who owns a node or who is in a group (and an account's role) takes one database lock exclusively; every ticket write that checks work rights or an assignee (update, create, bulk, resolve, duplicate, merge, labels, links, checklist, paged, acknowledge, report) takes it shared before locking the ticket's row. So a move waits for an assignment in flight and then sees (and, with
unassignNonMembers, unassigns) it, and a write after the move is judged on the new owner. The lock order is documented inserver/src/lib/locks.ts. A ticket's row lock lets comments, audit entries and watchers be added meanwhile; a write that waits more than 3 s for a lock gets503 { "error": "Busy with another change to the same thing; try again in a moment" }withRetry-After: 1. - Admin › Users shows each Agent's and Admin's groups, flags an Agent in none ("In no resolver group: can't change tickets in owned CTIs"), and picks groups in the create and edit form (
groupIdsonPOST /api/users; an edit sends only what changed,addGroupIdsandremoveGroupIdsonPATCH, so a page out of date doesn't undo memberships added elsewhere). - The server has
owningGroups(routes)(one query for any number of routes) andresolversOf(ticket): the owning group's Agents and Admins, or every Agent and Admin for an unowned route. Admins who aren't members are not listed as resolvers.
Assignees
Who can be a ticket's assignee (#174) is its route's resolvers: the members of the owning group that are Agents or Admins, or, for an unowned route, every Agent and Admin ("Any Agent (no resolver group)"). An Admin who isn't a member is not offered to others and is refused, but an Admin can take any ticket themself (#181): the lists returned to an Admin add them last, marked "outsideGroup": true ("You (not in Media)" in the pickers), and create, update and bulk reassign accept an Admin assigning themself. Agents and Admins.
| Method | Endpoint | Notes |
|---|---|---|
GET |
/api/tickets/:id/assignees |
{ group, label, resolvers }: the picker's list for the ticket's route |
GET |
/api/assignees?categoryId=&typeId=&itemId= |
The same for a route with no ticket yet (the new-ticket form, a route being changed) |
- Refused: every way of setting an assignee (create, update, bulk
reassign, saving a template or recurring ticket with a route) is a 400{ "error": "<name> is not a <group> resolver" }for anyone else. An assignee left unchanged is not checked again. Templates, recurring tickets and the automation never get the Admin exception. - Automation doesn't fail:
POST /api/tickets/report, a template's default assignee and a recurring ticket create the ticket unassigned instead. The response (assigneeDropped, on a report or a ticket made from a template) and theCREATEDaudit entry say why. - Moving a ticket to a route another group owns (a hand-off) clears an assignee who isn't a resolver of the new route in the same update: audited as an unassignment with the reason, and returned as
assigneeClearedon the update's response. The ticket page asks first ("This moves the ticket to Network. Mia isn't in Network and will be unassigned."). Within the same group, or to a route the assignee also resolves, nobody is unassigned. - An Admin who took a ticket outside their groups counts as a non-member for later hand-offs and group moves, like anyone else.
- Leaving a group doesn't unassign: a person removed from a group keeps the tickets they hold; the picker just stops offering them (and they can't be assigned anew).
- In the web app the ticket page, the new-ticket form (following its route), bulk edit (those who resolve every selected ticket), and the template and recurring ticket forms all use these lists. Who may change a ticket at all: Roles.
Users
GET /api/users
List all users (id, username, displayName, email, role, disabledAt: when it was disabled, null while enabled, groups: the resolver groups each is in).
Admin-only operations (and, within its limits, a PROVISION key):
POST /api/users
Create a user.
{
"username": "string",
"email": "string",
"displayName": "string",
"password": "string (min 8 chars)",
"role": "ADMIN | AGENT | USER",
"groupIds": ["optional resolver group ids (Agents and Admins)"]
}
The username is stored without surrounding whitespace (tabs and no-break spaces included), up to 50 characters, no control characters (400); one that differs from an existing username only by case or surrounding spaces is a 409. Agent accounts receive an auto-generated API key returned in the response (apiKey): the account's default key, scope WRITE. Copy it immediately — it is not shown again. An Agent created with a PROVISION key gets no key (no apiKey); a PROVISION key can only create Agents. Audited as account_created.
PATCH /api/users/:id
Update a user — including notificationPrefs and regenerateApiKey. { "regenerateApiKey": true } replaces an Agent's default key (the old one stops working at once; its other keys are kept) and returns the new one once as apiKey. Changing the role to Agent gives an account with no key a default one; changing it away from Agent revokes all its keys. groupIds, when given, makes those exactly the account's resolver groups (each addition and removal is audited, as on the group page); addGroupIds and removeGroupIds instead change only the groups named (not with groupIds). Adding a User, or an unknown group, is a 400, and the whole edit is refused: the account and its groups change in one transaction. { "disabled": true | false } disables or re-enables the account. A PROVISION key may send only disabled. Setting password signs the account out everywhere, as a password change does: every session (cookie or Bearer) signed in with an earlier password is refused at once, however close in time, while a sign-in with the new password works; it also cancels the unused reset links. Its API keys keep working.
API keys of an Agent
Admin only, with a signed-in session (an API key gets 403), except for a PROVISION key within its limits. See API keys.
| Method | Endpoint | Body / response |
|---|---|---|
GET |
/api/users/:id/api-keys |
[{ "id", "name", "prefix", "scope", "expiresAt", "lastUsedAt", "createdAt" }]: the keys not revoked (expired ones included); never the key or its hash |
POST |
/api/users/:id/api-keys |
{ "name": "n8n", "scope": "READ" | "REPORT" | "COMMENT" | "WRITE" | "PROVISION", "expiresAt"?: iso | null } → 201 with the listed fields plus key, the only time it's returned. 400 if the account isn't an Agent or expiresAt is past |
DELETE |
/api/users/:id/api-keys/:keyId |
Revokes the key at once → 204; 404 if it isn't this account's or is already revoked |
DELETE /api/users/:id
Delete a user. Cannot delete your own account.
Automation
Endpoints for n8n and other automation (Agent or Admin, usually with X-Api-Key). A REPORT key can use report, resolve, comments/by-key, paged and acknowledge, not duplicate (scopes).
POST /api/tickets/report
Report a problem by fingerprint, a stable key for "the same problem" (for example smart:delphinus|health|S41GNX0M591197). If a ticket with that fingerprint is open (Open, In Progress or Pending), the report is added to it as a comment (and may escalate it); a Pending ticket stays Pending. Otherwise, if one was resolved within the reopen window (reopenWithinHours in the report, else the setting, default 24) and not as a duplicate, the most recently resolved one is reopened; failing that, a ticket is created. If the most recently resolved one was merged into another ticket, the report goes there instead (with a note naming the merged ticket). At most one open ticket per fingerprint is allowed (a partial unique index), and concurrent reports of one fingerprint are serialised, so they produce one ticket. A report that arrives while its ticket is being resolved (alone or in a bulk action) waits for the resolve and then reopens it, or creates a ticket, as it would have a moment later; it never comments on a ticket that was resolved meanwhile.
{
"fingerprint": "smart:delphinus|health|S41GNX0M591197",
"title": "SMART error (Health: Reliability) detected on host: delphinus",
"overview": "markdown",
"severity": 2,
"kind": "ALARM",
"cti": { "category": "Hosts", "type": "Proxmox node", "item": "delphinus" },
"repeatComment": "**Reported again** · …",
"minRepeatMinutes": 60,
"escalate": true,
"reopenWithinHours": 6
}
ctiroutes by name and creates missing levels;categoryId/typeId/itemIdwork too (the type must be in the category and the item in the type: a 400 otherwise).- On a ticket the key's owner can't work (Roles): the repeat is recorded (comment,
reportCount,lastReportedAt) but the ticket isn't escalated, reopened or labelled (a resolved ticket stays resolved and gets the comment). The response lists what wasn't done,"ignored": ["escalate", "reopen", "labels"], withignoredReason, and so does theREPORTED_AGAINaudit entry. A key whose owner is in the ticket's group (goddard is in every group) is unaffected. repeatCommentis posted on the open ticket for a repeat (default**Reported again**). InsideminRepeatMinutesof the last comment a repeat is only counted (reportCount), not commented. Withescalate(default true) a more severe repeat raises the ticket's severity.- Optional:
kind,workflowState,serviceState,assigneeId(not a resolver of the route: the ticket is created unassigned and the response hasassigneeDroppedwith the reason, see Assignees). - Optional
reopenWithinHours(whole number, 0 to 8760) overrides the reopen window for this report only: 0 never reopens (a new ticket is opened). Without it the setting applies. labels(optional, up to 20 names): labels, created if missing. Applied to a new ticket; added to (never removed from) the ticket a report repeats on or reopens. A name that breaks the label rules is a 400; past a ticket's 20 the rest are skipped, so a report is never lost over labels.- Reopening sets the ticket Open, clears its resolution, comments Reopened · reported again N hours after it was resolved (followed by
repeatComment, or the report's overview), counts the report, escalates like a repeat, and recordsREOPENEDin the audit log. - Response:
{ "action": "created" | "commented" | "suppressed" | "reopened", "ticket": {…}, "commentId"?: "…" }, 201 when created, else 200.tickethas the same shape asGET /api/tickets/:id(withsla). The metrics count each outcome inticketing_reports_total{action}.
POST /api/tickets/:id/resolve
{ "resolution": "FIXED" | "DUPLICATE" | "TRANSIENT" | "NOT_A_FAILURE" | "MERGED" | "WONT_FIX", "comment"?: "markdown" }. Resolves the ticket (Agents can resolve; only Admins close) and records why. Returns the ticket as GET /api/tickets/:id does (with sla).
POST /api/tickets/:id/duplicate
{ "of": "<master id or display id>", "comment"?: "markdown" }. Links the ticket to its master, resolves it as a duplicate and comments (default Duplicate of V…). The master lists its duplicates. Refused with a 400 when the master is, through any chain of duplicate or merge links, a duplicate of this ticket (a loop); links are made one at a time, so two made at once can't close a loop either. Returns the ticket as GET /api/tickets/:id does (with sla). Reopening a ticket (a PATCH to an open status, alone or with any other fields) clears its resolution, duplicate link and resolvedAt, and so does giving it a resolution other than Duplicate or Merged (resolve or PATCH): it is no longer one of the master's.
POST /api/tickets/:id/merge
{ "into": "<id or display id>", "comment"?: "markdown" } (Agent or Admin; a WRITE key). Merges this ticket (B) into into (A) in one transaction: B's comments and attachments move to A as they are (same rows, authors and times; each gets mergedFrom: "V…B", and moved comments lose their automation key), B's watchers and labels are added to A (labels past A's limit of 20 are skipped and listed), B is linked to A through the duplicate link (duplicateOf, so A lists it under "Merged here") and resolved as MERGED with a comment (default Merged into V…), and A gets a comment saying what arrived. Both get audit entries (MERGED_INTO, MERGED_FROM). B keeps its audit log, fingerprint and links; a page it had ends because it is resolved. Refused: into itself (400); into a merged or closed ticket, a ticket already merged, or a loop of duplicate links (409); either ticket one the caller can't work (403 naming its group: the merge writes both). Returns { ticket, into, moved: { comments, attachments, watchers, labels, labelsSkipped } }. A later report with B's fingerprint goes to A: a comment while A is open, a reopen of A within the reopen window, otherwise a new ticket. That holds while B is the fingerprint's most recently finished ticket (resolved, or closed by hand, which clears resolvedAt: its last change counts then). Reopening B, or resolving it again for another reason, clears the link, and reports then go to B again.
PUT /api/tickets/:id/comments/by-key/:key
{ "body": "markdown", "meta"?: {…} }. Creates the comment with this key, or replaces it (one per key per ticket), for comments automation edits in place such as run cards. 201 when created, 200 when updated. Comments can also be edited with PATCH /api/tickets/:id/comments/:commentId { "body" } (author or Admin).
POST /api/tickets/:id/paged and POST /api/tickets/:id/acknowledge
Paging (severity 1–2 tickets page someone until it's acknowledged; the pages themselves are sent by automation, n8n's Pager).
paged(Agent/Admin), body{ "at"?: iso }: records that the ticket paged someone. A new page clears the previous acknowledgement. So does the ticket stopping paging (resolved, closed or lowered below severity 2:ACKNOWLEDGEMENT_CLEARED).acknowledge(Agent/Admin), body{}from the UI, or{ "username": "josh", "via": "Pushover (iphone)", "at": iso }from automation reporting an acknowledgement made elsewhere. It is recorded as the caller:usernamenaming someone else is a 403 unless the caller is theACK_RELAY_USERNAMEaccount (#198), whose relayed acknowledgement names that user, with the audit entry "reported by ". 409 if the ticket hasn't paged anyone oratis older than the current page; 400 for an unknown user. Acknowledging an acknowledged page changes nothing. It fires theticket.acknowledgedwebhook so the page can be stopped at once.- The ticket carries
pagedAt,acknowledgedAt,acknowledgedByandacknowledgedVia; the audit log recordsPAGEDandACKNOWLEDGED. A ticket that's still paging (open at severity 1–2, paged, unacknowledged) shows a banner with an Acknowledge button, and a Paging badge in the list.
SLA targets and due dates
Each severity has an optional time to acknowledge and time to resolve, in minutes from severitySince: when the ticket took its current severity, so createdAt (for imported tickets, the Gitea issue's creation time) unless the severity changed since. Every severity change (the ticket page, bulk edits, PATCH, a report's escalation) restarts both clocks for the new severity's targets, raising or lowering; the ticket page says when they started. Defaults, until an Admin changes them in Admin › SLA: SEV 1 15 min / 4 h, SEV 2 30 min / 8 h, SEV 3 none / 3 days, SEV 4–5 none. The SlaPolicy table holds a row per severity an Admin has saved (with who and when); a severity without a row uses its default, so an empty table means the defaults. A change applies at once to every ticket, past ones included. Every ticket and list row carries severitySince, dueAt and sla: { ack, resolve, breached }, each target { targetMinutes, state, deadline, metAt, secondsLeft, secondsOver, paused, pausedSeconds }.
- States per target:
none(no target),met(done at or before the deadline),running(not done, now at or before the deadline),breached(not done and past the deadline, or done after it). A ticket is breached if either target is.sla:runningmeans none breached and one running;sla:met, none breached or running and one met. - Acknowledged is the earliest of the following, counting only those at or after
severitySince(raising a ticket asks for a fresh acknowledgement):acknowledgedAt(a page acknowledged);resolvedAt; the first audit-log status change to anything but Open; anACKNOWLEDGEDaudit entry (a later page clearsacknowledgedAt, not the entry); anASSIGNEE_CHANGEDentry to a person (not "→ Unassigned", nor a hand-off's "→ Unassigned (reason)" when a route change or a node move takes the assignee off). An assignee given at creation, comments, edits and pages don't count. Imported tickets have no such audit entries, so for them onlyacknowledgedAtandresolvedAt(both Gitea times) count. Audit times are when TicketingSystem recorded the change. - Resolved is
resolvedAtfor a Resolved or Closed ticket. An Admin closing a resolved ticket clearsresolvedAt(existing behaviour), so then it is the first move to Resolved or Closed in the audit log after the last reopening, and failing thatupdatedAt. An open ticket is still running; one already resolved when its severity changed met the new targets at once. - Reopened tickets keep their original clock (from
severitySince): the reopen time is only in the audit log (for imported tickets only as the sync time), whileseveritySinceis always reliable. A ticket reopened after its deadline is breached again at once. - Pending pauses the resolve clock (#194): the time a ticket spends Pending after
severitySinceis added to its resolve deadline, so it counts neither toward the target nor toward a breach; several spells add up (pendingSeconds, plus the current spell frompendingSince). While Pending the target ispausedwith its time left standing still, and the ticket page says "Paused"; a target already breached when the ticket went Pending stays breached, by as much as then. The acknowledge clock never pauses (moving to Pending acknowledges). The list'ssla:filters, the metrics and Reports' SLA targets use the same rule in SQL. A new severity drops the time Pending before it: an escalation (or any severity change) of a Pending ticket restarts both clocks from that moment (#150), the acknowledge clock included, so a ticket raised while Pending asks for a fresh acknowledgement and its earlier Pending time no longer counts; the current spell counts from the change. - Overdue: a due date in the past on an open (Open, In Progress or Pending) ticket.
- Computed when read, never stored: the list filter and the metrics in SQL (the policy's thresholds are query parameters; the audit log is read through correlated subqueries on its
(ticketId, createdAt)index), and the rows'slawith one extra query per page. Nothing pages, notifies or sends a webhook on a breach.
| Method | Path | Description |
|---|---|---|
GET |
/api/sla/policy |
Admin: { targets: [{ severity, ackMinutes, resolveMinutes, isDefault, updatedAt, updatedBy }], defaults } |
PUT |
/api/sla/policy |
Admin, signed in (not an API key): { targets: [{ severity, ackMinutes, resolveMinutes }] }; whole minutes 1–525600 (365 days), or null |
Metrics: ticketing_sla_breached_tickets{severity, target="ack"|"resolve"} (open tickets breaching each target) and ticketing_overdue_tickets, from one query over open tickets only.
More list filters
GET /api/tickets also takes kind, workflowState, serviceState, fingerprint, giteaNumber, updatedSince (ISO time) and paging (unacknowledged: open at severity 1–2 and still paging; acknowledged; paged), and sort=severity|updated|updated_asc|created|created_asc. GET /api/tickets/by-gitea/:n returns the ticket mirrored from Gitea issue #n.
Ticket fields
Besides title, overview, severity, status and CTI, a ticket has kind (ALARM, BUG, ENHANCEMENT, NEW_SERVICE, WORKFLOW, TESTING, UPDATE, RETIREMENT), workflowState (PENDING, RUNNING, SUCCESS, FAILURE, TIMEOUT), serviceState (DEVELOPMENT, DEPLOYED, DEGRADED, DECOM), resolution, duplicateOf/duplicates, fingerprint, reportCount, lastReportedAt, and for mirrored tickets giteaNumber and externalUrl. All but the last two can be set with PATCH /api/tickets/:id.
In ticket and comment markdown, #123 links to the ticket mirrored from Gitea issue 123, V123456789 links to that ticket, and external links open in a new tab (any address but a plain /path, so //host too, with rel="noopener noreferrer"). Only the app's own images are shown: an attachment (/api/attachments/<id>) and a profile picture (/api/users/<id>/avatar), under either API prefix. An image from anywhere else is never loaded, as loading it would tell that site the address of everyone viewing the ticket, and neither is any other address on the app's own origin, which the viewer's browser would request as them: each shows as a link, its alt text or address, that opens it in a new tab (#208). The app's Content-Security-Policy allows images from the app and blob: only. A table whose header cells are all empty (| | |, as automation writes for a table without headings) is shown without its header row; the stored text is unchanged.
When shown, hidden HTML comments (<!-- fingerprint: ... -->, as automation writes them) are left out and a plain HTML link <a href="URL">text</a> (http, https, mailto or a /path) is shown as a link in a new tab; any other HTML is shown as text and never run, and code blocks and inline code are left as written. This only changes what is displayed: the stored text, the API, the exports and the editors keep the original bytes. So hidden <!-- --> text is still in what the API returns: anyone who can comment can write a marker that automation reading comment text would see, so automation acting on a marker or other comment text must check the comment's author (#208).
Gitea import (shadow mode)
npm run import:gitea mirrors the issues of a Gitea repository into TicketingSystem while Gitea stays the system of record. It's idempotent (tickets are matched by Gitea number, comments by Gitea comment id), so it can run on a timer:
GITEA_URL=https://gitea.example GITEA_REPO=josh/TheWrightServer GITEA_TOKEN=… npm run import:gitea
npm run import:gitea -- --full # every issue, not only those changed since the last run
npm run import:gitea -- --issue 1252 # one issue
npm run import:gitea -- --since 2026-11-01T00:00:00Z
- Reads issues changed since the last run (stored in
SyncState, with 10 minutes of overlap), and every issue the first time. Overlapping runs skip. - Tickets mirrored before the Update and Retirement kinds existed have no kind, and an unchanged issue is not read again. So the first run after that release also reads every issue once (without comments) and sets only
kindon mirrored tickets labelledkind/updateorkind/retirement(updatedAtis kept, oneSYNCEDaudit entry each);SyncStaterecords that it was done (kindsBackfilled), so it never repeats. It runs under the import lock, so two replicas or overlapping runs can't clash. - Writes straight to the database, keeping Gitea's created and updated times and authors, and sends no notifications or webhooks. Gitea authors without an account here get a
USERaccount that can't log in until an Admin sets a password. Changes are logged in the audit log asIMPORTEDandSYNCEDbygitea-sync. - Labels map to fields and CTI:
severity/Nto severity (4 when missing);kind/*to kind (kind/updateis Update andkind/retirementis Retirement;kind/tailnetis an alarm;kind/duplicatemarks a duplicate);workflow-state/*andservice-state/*to the state fields. CTI comes from the title family, for exampleWorkflow Failure - X→ Control plane › n8n workflow › X,SMART error … host: H→ Hosts › Proxmox node › H,[Sonarr] …→ Services › Media › Sonarr; otherwise from thescope/*label (Unsorted without one). - Open issues are Open. Closed issues are Resolved if closed in the last 14 days, else Closed, and keep their Gitea close time. Within the same open or closed state, a status changed here is kept. Resolutions come from closing comments (
Duplicate of #N, transient failure, Not a bug, Merged, Resolved/Cleared); duplicate links are made once both tickets exist. - Fingerprints follow the matching rules of the workflows that file those tickets: workflow failures by their
failure-key, *arr Watchdog tickets by theirarr-watchdogkey, SMART alarms by host, category and disk serial, Tailscale key events by device, and fence, host backup, replication and package news tickets by title. A hidden<!-- fingerprint: … -->line in an issue's body (written by n8n's Goddard - Report Ticket helper) sets the fingerprint directly and wins over those rules. Only one open ticket gets a given fingerprint. - Bodies are converted for this renderer: HTML links become markdown links,
<details>folds become a bold heading, and credentials are masked the way n8n's error handler masks them. Hidden<!-- -->markers (fingerprint,failure-key,canary,update-key,log-watchdog,ticketing-watchdogand the rest) are kept in the overview and in comments, byte for byte and in place, because the automation finds its open tickets by searching bodies for them; they are also still read into fields (the fingerprint above, a run card's key and data become the comment'skeyandmeta). What the other conversions do around a marker still applies: spaces and tabs at the end of a line are dropped, three or more newlines become two, and the whole body is trimmed. A credential inside a marker is masked like any other. Markers add nothing to full-text search (PostgreSQL's parser skips HTML comments) and the importer builds no excerpts. Until the client hides them when rendering (#107) a marker shows as text. - Markers on tickets mirrored before this release come back on their own: the first run after deploying reads every issue once and restores them in the overview and comment bodies of the tickets already mirrored (the run's
markersRestoredandmarkerCommentsRestoredcounts;SyncStaterecordsmarkersKeptwhen done, a failed pass is retried, and it runs under the import lock so two replicas can't overlap). It changes only those bodies:updatedAt, fingerprint and every other field stay as they were, nothing is notified, delivered or paged, and each changed ticket gets oneSYNCEDaudit entry. A body is replaced only if it is exactly what the old importer wrote for the Gitea text; one edited here is left alone (markersSkipped), and a normal sync of that issue overwrites it as it always has. - Comments deleted in Gitea are deleted here; comments made here are left alone.
- Gitea's labels are not mirrored into labels: the importer creates none (whether to do so is a separate decision).
- The Pager's comments (by
goddard: Paged, Paged again, Acknowledged · on ) setpagedAt,acknowledgedAtandacknowledgedVia. A newer page replaces what's here and clears its acknowledgement; an acknowledgement made here is kept. - The last stdout line is
IMPORT {json}with the counts; it exits 2 if any issue failed. - Each run's outcome is recorded.
GET /api/import/status(Agent/Admin) returns the last run and whether the mirror is current.GET /healthz/import(no auth) answers 200 while it is, and 503 withstaleorfailingonce there's been no successful run forIMPORT_STALE_MINUTESor the last run failed, for an outside monitor. The dashboard shows the same. - Retiring the mirror (
IMPORT_RETIRED=true, for when Gitea's issues are a frozen archive):GET /api/import/statusaddsretired: trueand is neverstaleor unhealthy (lastRunandlastSuccessAtstay as history),GET /healthz/importanswers 200retired(so health checks and probes keep passing), the dashboard shows no mirror line except one muted line for Admins ("Gitea mirror retired · last synced "), andnpm run import:giteaprints that it is retired and exits 0 without running. Mirrored tickets keep their Gitea number, link and the/gitea/:nredirect. Unset orfalseis the behaviour above; the server refuses to start on any other value.
n8n Integration
Create an Agent account via Admin → Users. Its default key (scope WRITE) is shown once in a modal at creation; for n8n, prefer a key of its own with the narrowest scope that works (usually REPORT; WRITE to create tickets as below), from Admin → Users → the key icon. Copy it into n8n's credentials as the X-Api-Key header value. Every Agent can authenticate via both password (for the UI) and API key (for automation).
Create a ticket from n8n:
POST /api/tickets
X-Api-Key: sk_<agent api key>
Content-Type: application/json
{
"title": "[Plex] Backup - 2026-03-30T02:00:00",
"overview": "Automated nightly Plex backup completed.",
"severity": 5,
"categoryId": "<TheWrightServer category ID>",
"typeId": "<Automation type ID>",
"itemId": "<Backup item ID>",
"assigneeId": "<agent user ID>"
}
CTI IDs can be fetched from:
GET /api/cti/categoriesGET /api/cti/types?categoryId=<id>GET /api/cti/items?typeId=<id>
To rotate an Agent's API key without downtime: Admin → Users → key icon next to the Agent → New key, switch n8n to it, then revoke the old key (API keys).
Environment Variables
| Variable | Required | Description |
|---|---|---|
DATABASE_URL |
Yes | PostgreSQL connection string. Any session time zone works: times are stored and compared as UTC whatever the server's TimeZone setting |
JWT_SECRET |
Yes | Secret for signing JWTs — use openssl rand -hex 64; under 32 bytes the server refuses to start (except under NODE_ENV=test) |
CLIENT_URL |
Yes | Allowed CORS origin (your domain) |
PORT |
No | Server port (default: 3000) |
HOST |
No | Address to listen on, e.g. 127.0.0.1 behind a reverse proxy on the same machine (default: all) |
UPLOADS_DIR |
No | Attachment and profile picture storage path (default /data/uploads in Docker) |
ATTACHMENT_QUOTA_MB |
No | Attachment storage per account, in MB (default 200; 0 turns it off). A whole number; the server refuses to start otherwise |
TRUST_PROXY |
No | Express trust proxy: the proxies in front of the server, so rate limits see client addresses. 1 behind the bundled nginx, which sends one address (2 gives the same). Unset trusts none. |
SESSION_HOURS |
No | Length of a sign-in without Stay signed in, in hours (default 24). A positive whole number; the server refuses to start otherwise |
REMEMBER_DAYS |
No | Length of a sign-in with Stay signed in ticked, in days (default 30). A positive whole number; the server refuses to start otherwise |
BCRYPT_COST |
No | bcrypt cost for new password hashes, 4 to 15 (default 12; any other value refuses to start, below 12 warns outside tests); the tests use 4. A lower-cost hash is renewed at sign-in |
GITEA_URL |
Import | Gitea base URL for import:gitea (default https://gitea.thewrightserver.net) |
GITEA_REPO |
Import | Repository to mirror (default josh/TheWrightServer) |
GITEA_TOKEN |
Import | Token with read access to the repository's issues |
GITEA_PUBLIC_URL |
Import | Address for links when GITEA_URL is internal (Gitea builds html_url from the host it's asked on); a change relinks every ticket on the next run |
METRICS_PORT |
No | Serve Prometheus metrics on this port at /metrics (off when unset) |
METRICS_HOST |
No | Address for the metrics listener (default: all) |
REOPEN_WINDOW_HOURS |
No | Default of the reopenWithinHours setting: hours a resolved ticket still reopens on a repeat report (default 24; 0 off) |
IMPORT_STALE_MINUTES |
No | Minutes without a successful Gitea import before /healthz/import answers 503 (default 30) |
IMPORT_RETIRED |
No | true marks the Gitea mirror retired: /healthz/import answers 200 retired, the dashboard line is hidden (Admins get a muted one), import:gitea does nothing (default false) |
BACKUP_STALE_HOURS |
No | Hours without a passing backup restore check before /healthz/backup answers 503 (default 26) |
LOGIN_RATE_LIMIT |
No | Failed logins allowed per client address per 15 minutes (default 10); password changes count too |
LOGIN_ACCOUNT_LIMIT |
No | Failed sign-ins allowed per username per 15 minutes, across replicas and addresses (default 10; 0 turns it off) |
AUDIT_RETENTION_DAYS |
No | Days the sign-in and key-use audit keeps entries (Audit; default 90, at least 1) |
API_KEY_RATE_LIMIT |
No | Requests per minute allowed per API key (default 300; 0 turns it off). See Rate limits |
RATE_LIMIT |
No | Requests per minute allowed per client address for everything not authenticated with an API key (default 120; 0 turns it off). See Rate limits |
LIVE_POLL_MS |
No | How often each replica checks for changes while live-update streams are open (default 2000, at least 500; 0 turns live updates off: GET /api/events is 404) |
LIVE_MAX_STREAMS |
No | Live-update streams allowed per replica (default 500) |
APPROVAL_CALLBACK_HOSTS |
No | Hosts an approval request's callbackUrl may name: comma-separated, each optionally host:port. Empty (default) refuses every callback |
WEBHOOK_ALLOWED_HOSTS |
No | Webhook destinations allowed although they are not public (a tailnet or LAN n8n): comma-separated, each optionally host:port. Empty (default): public destinations only |
APPROVAL_CALLBACK_SECRET |
No | Signs approval callbacks like webhooks (X-Ticketing-Signature); unsigned when unset |
RECURRING_POLL_MS |
No | How often each server checks for due recurring tickets, in ms (default 60000) |
PAGING_MODE |
No | Paging (Paging): off, shadow (the default: records what it would do, sends nothing) or live. live missing the three below runs as shadow |
PUSHOVER_TOKEN |
Live | Pushover application token, from a Kubernetes Secret. Never logged, returned or stored |
PUSHOVER_USER |
Live | Pushover user key of the person paged, from the same Secret |
PAGING_ACK_USERNAME |
Live | Account acknowledgements from Pushover are recorded for (and live's pages in the audit log); must exist |
ACK_RELAY_USERNAME |
No | The one account (e.g. goddard, for the n8n Pager) that may acknowledge a page on someone else's behalf (username); unset, everyone acknowledges as themselves |
PUSHOVER_FAKE |
No | true: live sends to a fake that only logs, for local tries. Refused in production (runs as shadow, with an error) |
SMTP_HOST |
No | SMTP host — when set, email notifications are sent |
SMTP_PORT |
No | SMTP port (default 587) |
SMTP_USER |
No | SMTP username |
SMTP_PASS |
No | SMTP password |
SMTP_FROM |
No | From address (default noreply@localhost) |
SMTP_SECURE |
No | true for implicit TLS (port 465), else false |
REGISTRY |
Deploy | Container registry hostname |
POSTGRES_PASSWORD |
Deploy | Postgres password |
TAG |
Deploy | Image tag to deploy (default: latest) |
Rate limits
Every request is counted per minute, in one of two budgets:
- Per API key (default 300/minute,
API_KEY_RATE_LIMIT): a request authenticated with a validX-Api-Key. Each key has its own budget (two keys of one account don't share), and many keys behind one address (n8n) don't use the address budget. - Per client address (default 120/minute,
RATE_LIMIT): everything else, signed-in sessions and unauthenticated requests, including requests with an invalid, expired or revoked key (anX-Api-Keyheader alone doesn't earn the per-key budget). The address is the one Express sees throughTRUST_PROXY: set it correctly behind a reverse proxy, or every client shares the proxy's address.
GET /healthz and its sub-paths, GET /api/version and the metrics port are never limited. Login keeps its own stricter limit (LOGIN_RATE_LIMIT), and login attempts also count against the address budget.
A refused request gets 429 with { "error": "Too many requests: … retry in N seconds" }, a Retry-After header and the RateLimit-Policy and RateLimit headers (also sent on allowed requests). The web client shows one "Too many requests; retry in N seconds" notice and doesn't retry a 429 straight away. 0 turns a limiter off; a value that isn't a whole number logs a warning and uses the default. Refusals are counted in ticketing_rate_limited_total{kind="api_key"|"address"}, and the first refusal per key or address in each minute is logged at warn level with the key id or address (never the key).
Counters live in memory in each server process and reset on restart. With two replicas behind a load balancer the effective limit is up to twice the configured one; a shared store is not part of this.
Ticket Severity
| Level | Label | Meaning |
|---|---|---|
| 1 | SEV 1 | Critical — immediate action required |
| 2 | SEV 2 | High — significant impact |
| 3 | SEV 3 | Medium — standard priority |
| 4 | SEV 4 | Low — minor issue |
| 5 | SEV 5 | Minimal — informational / automated |
Tickets are sorted SEV 1 → SEV 5 on the dashboard.
Ticket Status Lifecycle
OPEN ⇄ IN_PROGRESS ⇄ PENDING open statuses: any to any, by hand only
│ │ │
└──────────┴─────┬─────┘
▼
RESOLVED ──(autoCloseDays, 14)──→ CLOSED
│ │
└─ reopen: back to an open ────┘
status, clears resolution
CLOSED status can only be set manually by an Admin (single or bulk); any open status can be set from any other, and reopening resets the auto-close timer. PENDING pauses the resolve SLA clock and is left only by hand. The auto-close job runs hourly (after
autoCloseDays, default 14: see Settings).
Keyboard Shortcuts
| Context | Keys | Action |
|---|---|---|
| Global | ⌘K / Ctrl+K |
Command palette |
| Global | ? |
Shortcuts help |
| Global | c |
Create ticket (Agent/Admin) |
| Navigate | g then d / t / m / n / s |
Dashboard / Tickets / My Tickets / Notifications / Settings |
| List | j / k |
Move cursor |
| List | Enter |
Open focused ticket |
| List | x |
Toggle selection |
| Detail | e |
Edit title |
| Detail | r |
Reply (focus composer) |
| Detail | Ctrl+Enter / ⌘Enter |
Submit comment |