Configuration Manual · Revision 2

Dornorium Configuration Reference

Every constant, binding, override path, and access-control rule that governs the Dornorium ticketing platform — rebuilt line-by-line from the current config.js, shared.js, and ticketworker.js, including the roles, locking, realtime, and multi-language systems that v1 of this doc missed.

App Dornorium v1.1.0 Runtime Cloudflare Workers + D1 + KV + Durable Objects Frontend Vanilla JS, no frameworks, 6 pages

01 Architecture

Dornorium is six static pages backed by one Cloudflare Worker. Pages call the Worker over fetch through a shared API helper; the Worker fans out to D1 (relational data), KV (settings cache + version key), and a Durable Object — TICKET_HUB — for everything that needs shared, consistent state at the edge: WebSocket fan-out, ticket locks, and login rate limiting.

CLIENT
dashboard · settings · users · newsletter · order-reply · reports
config.js + shared.js load first, on every page
→
EDGE
ticketworker.js
Auth, ACL, routing, JSON API, email parsing
→
STATE
D1 · KV · TICKET_HUB (DO)
Storage, cache, locks, live push

Two Worker files ship in this repo: worker.js, an earlier and considerably lighter route set with no RBAC, no locking, and no WebSocket support; and ticketworker.js, the current, full implementation. Only ticketworker.js is production-accurate — every section below documents it specifically.

02 Script Load Order

Every page must load scripts in this exact order. shared.js reads getConfigValue() at module-eval time, so config.js has to exist on window first.

<!-- required order, every page -->
<script src="config.js"></script>
<script src="shared.js"></script>
<script> /* page-specific inline logic */ </script>
⚠ Common regression

Reordering these two breaks every getConfigValue() call silently — it falls through to the hardcoded default instead of throwing, so the bug surfaces as "wrong toast duration" or "API calls going to the wrong host" rather than a console error. Check load order first when a config value seems ignored.

03 config.js — Core Values

All static defaults live under window.DORNORIUM_CONSTANTS and are read exclusively through getConfigValue(key, fallback) — page code never touches the object directly.

Application meta

KeyValueNotes
APP_NAME'Dornorium'Display name only
VERSION'1.1.0'Bump on release; not enforced anywhere
API_BASEhttps://dornori-ticketing.dornori-info.workers.devRoot for every apiCall() request in shared.js

Product data feeds (order-reply)

KeyValueResolves to
PRODUCTS_DATA_BASE_URLhttps://cdn.example.com/data{base}/{lang}/products.json — per-language product names
PRODUCTS_IMAGES_BASE_URLhttps://cdn.example.com/products{base}/products.json — shared images/metadata
Now editable live

These two URLs are also exposed as Product Data Base URL / Product Images Base URL on Settings → General — see §5. The config.js values are the bootstrap defaults; the Settings-table value wins once set.

Reviews module NEW

Settings keyCategoryNotes
request_delay_daysreviewsDays after order close before the scheduled worker sends a review request
worker_send_timereviewsDaily UTC time the review-request worker runs
worker_enabledreviews'1' / '0' — master on/off switch for the scheduled worker
company_namereviewsUsed in review-request emails and reply signatures
review_submit_urlreviewsPublic review-page URL; resolves the {{review_link}} tag
email_subject / email_bodyreviewsThe single platform-wide review-request template (not per-language)
reply_signature / small_printreviewsAppended to review replies / available as tags

Software Updates NEW

KeyValueNotes
SW_UPDATE_API_URLvendor update-server base URLCalled for /api/update-info and vendor phone-home; not the customer's own Worker
serial_numbergenerated by installer or /api/admin/serial/registerRequired to check for or apply updates — an unregistered instance can't check

UI timing (ms)

KeyDefaultUsed by
TOAST_DURATION_MS3500success / error / info toasts
TOAST_WARNING_DURATION_MS8000warning toasts (also get a manual ✕ close button)

04 Environment Overrides

getConfigValue(key, fallback) checks a window.DORNORIUM_<KEY> global before falling back to DORNORIUM_CONSTANTS, then to the caller's own fallback.

// resolution order inside getConfigValue(key, defaultValue)
1. window[`DORNORIUM_${key}`]          // JSON.parse'd if possible, else raw string
2. window.DORNORIUM_CONSTANTS[key]     // config.js baseline
3. defaultValue                     // caller-supplied fallback

// example: override toast duration for staging only, before config.js loads
<script> window.DORNORIUM_TOAST_DURATION_MS = "1500"; </script>
<script src="config.js"></script>

05 Live System Config NEW

Settings → System Config is a genuinely new capability: several values that used to live only in config.js can now be edited from the UI and take effect immediately, no redeploy. This tab writes to the settings table under category system.

FieldOverrides config.js key
CORS Allowed OriginsCORS_ORIGINS
Login Rate Limit Window (minutes)RATE_LIMIT_WINDOW_MS
Session Timeout (minutes)SESSION_TIMEOUT_MINUTES
Max Failed LoginsMAX_FAILED_LOGINS
Account Lockout Duration (minutes)LOGIN_LOCKOUT_MINUTES

Treat the config.js values as bootstrap defaults for a brand-new deployment before anyone has touched Settings — once a row exists in the settings table, that's authoritative.

06 Cloudflare Bindings

Referenced directly in the Worker as env.*. None of these live in config.js — they're wrangler bindings, configured per environment.

BindingTypePurpose
env.DBD1 DatabaseUsers, tickets, settings, newsletters, subscribers, email addresses
env.KVKV NamespaceSettings cache, config-version key for client cache-busting
env.TICKET_HUB NEWDurable ObjectWebSocket fan-out, ticket locks, login rate-limit counters (§7)
env.JWT_SECRET NEWSecretSigns/verifies admin session tokens
env.SCRIPT_URLSecret / varGoogle Apps Script email relay endpoint
⚠ Secrets

JWT_SECRET must be set via wrangler secret put JWT_SECRET, never a plaintext var. Rotating it invalidates every issued session token immediately — every logged-in user is signed out.

07 Durable Object Routes NEW

These are pseudo-URLs — the Worker runtime intercepts them for Durable Object stub calls; none are real network requests. This entire subsystem is new since v1 and is what powers realtime updates, locking, and rate limiting.

Config keyRoutePurpose
DO_TICKET_CACHE_URL/ticket-listCached ticket list snapshot
DO_RATE_LIMIT_CHECK/rl-checkCheck a login attempt against the rate window
DO_RATE_LIMIT_FAIL/rl-failRecord a failed login attempt
DO_RATE_LIMIT_CLEAR/rl-clearClear lockout state on a successful login
DO_BROADCAST/broadcastPush an event to every connected WebSocket client
DO_CONNECT/connectUpgrade to WebSocket, register the client, scope by language/category
DO_USER_LOCKS/user-locksList every lock currently held by a given user
DO_LOCK/lockAcquire a ticket edit lock
DO_CHECK_LOCK/check-lockCheck current lock holder
DO_RELEASE/releaseRelease a held lock — also fired via sendBeacon on tab close

08 D1 Schema

Eight tables in the current build — one more than v1's seven, plus schema additions on two existing tables. Inferred directly from the Worker's SQL, not a design doc, so treat this as the ground truth for what the code actually reads and writes.

tickets CHANGED

id · ticket_number · category · language · status · priority · sender_name · sender_email · sender_phone · order_number · subject · message · assigned_to · created_at · updated_at · last_action · last_updated_by · sla_response_due · sla_resolution_due · metadata

Bold columns are new since v1. Ticket numbers now embed the language code directly: TKT-{LANG}{YY}-NNNNN.

users NEW TABLE

email (primary key) · name · role · password_hash · allowed_languages (JSON array) · allowed_emails (JSON array) · allowed_categories (JSON array) · team_id · page_permissions (JSON object, per-resource overrides)

settings

Key/value rows grouped by category. Categories in active use: system (§5), general, sla, category, language, auto_reply, order_template, and per-address footers under outgoing. Categories and languages are not separate tables — each is a set of settings rows (e.g. category / <slug>_description, <slug>_color), the same pattern v1 already used for SLA values.

email_addresses CHANGED

id · email · label · action (category slug) · language · is_active · created_at · updated_at. Each inbound address now resolves both a category and a language.

newsletter_subscribers, unsubscribe_tokens, newsletters, ticket_comments

Structurally unchanged from v1, with one addition: newsletter_subscribers and newsletters both gained a language column to support per-language campaigns.

09 Authentication NEW

v1 of this manual stated there was no role-based access and anyone with valid credentials had full admin access. That is no longer true. Dornorium now runs full JWT-based session auth with per-role and per-user access control.

01
POST /api/admin/login
Rate-limited via TICKET_HUB; 5 fails → 15 min lockout
→
02
JWT issued
Signed with env.JWT_SECRET, 24h expiry (TOKEN_EXPIRY_SECONDS)
→
03
Every request
Bearer token verified, resolves to a users row + effective_permissions

There is no self-serve signup. The first admin account must be inserted directly into the users table — see the Setup Manual.

10 Roles & Resources

ROLE_RESOURCES in the Worker is the single source of default access, for six resources: tickets, users, settings, newsletter, reports, order_reply.

Resourceadminmanagertlagent
ticketsread, writeread, writeread, writeread, write
usersread, writereadread—
settingsread, writeread——
newsletterread, writeread, writeread—
reportsread, writeread, writeread—
order_replyread, writeread, writereadread
reviews NEWread, writeread, writeread—

Role-specific write restrictions (users resource)

  • admin — unrestricted; the only role that can create or grant other admins.
  • manager — cannot edit users with role admin.
  • tl — can only edit users on their own team_id who hold role agent.
  • agent — no write access to the users resource at all.

11 Permission Resolution

Two layers, resolved into one flat object the frontend trusts without re-implementing logic: buildEffectivePermissions(user).

01
Role defaults
from ROLE_RESOURCES[role]
→
02
Per-user override
user.page_permissions[resource]
→
03
effective_permissions
{view, edit, create, delete} per resource

A boolean set in page_permissions always wins over the role default for that action. role === 'admin' is hard-forced to full access on every resource at the end of buildEffectivePermissions, so an override can never lock an admin out.

Action → resource mapping

PERM_ACTION_MAP = {
  view: 'read',   read:   'read',
  edit: 'write',  create: 'write',  delete: 'write',
  update: 'write', comment: 'write',  reply:  'write',
  assign: 'write', send:   'write',   write:  'write'
}

Frontend (shared.js) mirrors this via hasAccess(page, action), reading user.effective_permissions[page][action] straight from the login/me response — it never recomputes the ACL client-side, so it can't drift from the Worker's decision.

12 Per-User Scoping NEW

Independently of role, three JSON-array fields on the users row scope what an account can see, set from the Users page:

  • allowed_languages — which language-tagged tickets, newsletters, and order-reply templates the user can see. Empty means zero results, not "all".
  • allowed_emails — which inbound support addresses the user can see tickets from, and which "reply from" addresses appear for them.
  • allowed_categories — which ticket categories the user can see.
⚠ Empty scope = no data

A new user with an empty allowed_languages array sees nothing on the dashboard even with role agent and full tickets permission — this is the most common "why can't they see anything" support question. Check scope before ACL.

13 SLA Thresholds

KeyDefaultMeaning
SLA_WARNING_THRESHOLD_PERCENT80Ticket flips to at_risk at 80% of allotted SLA time elapsed
SLA_CRITICAL_THRESHOLD_PERCENT95Flips to critical at 95%
⚠ v1 documented the wrong model

v1 of this manual described SLA in terms of "time remaining" bands (>50% = on track, 25–50% = at risk, <25% = critical). The code measures percentage elapsed, not remaining, and the actual thresholds are 80%/95% as above — not 50%/25%. Use this page as the source of truth.

Per-category grace windows are stored in settings as <category>_resolved_grace and <category>_closed_grace (hours), letting auto-close timing vary by category instead of the fixed 3-day rule v1 described. A category left at 0 never auto-closes.

Status → color mapping (shared.js)

StatusClassLabelColor
on_tracksla-on-track✅ On Track#22c55e
at_risksla-at-risk⚠️ At Risk#eab308
criticalsla-critical🔴 Critical#f97316
breachedsla-breached❌ Breached#ef4444
pausedsla-paused⏸️ Paused#8892b0

14 Caching & TTLs

KeyDefaultScope
CACHE_TTL_SECONDS86400 (24h)Generic fallback TTL
CACHE_TICKET_TTL_SECONDS86400 (24h)Ticket list cache in the DO
CACHE_USER_TTL_SECONDS3600 (1h)In-memory user lookup cache, keyed by lowercased email
CACHE_CONFIG_TTL_SECONDS1800 (30m)Settings/config cache, invalidated early by version bump on write

Any write to a Settings tab bumps a config-version key in KV; clients compare it against their cached appConfigVersion in localStorage and refetch on mismatch, rather than waiting out the TTL. POST /api/admin/cache/purge forces this immediately.

15 Rate Limiting & Ticket Locking NEW

Login rate limiting

MAX_FAILED_LOGINS 5 attempts

LOGIN_LOCKOUT_MINUTES 15 min lockout

RATE_LIMIT_WINDOW_MS 60000 (1 min window) — enforced via the DO's /rl-check / /rl-fail / /rl-clear routes, editable live from Settings → System Config

Ticket locking

LOCK_STALE_WRITE_MS 45000 — write lock considered stale

LOCK_STALE_READ_MS 30000 — read/viewing lock considered stale

LOCK_CLEANUP_THRESHOLD_MS 15000 — stale-lock sweep interval

Locks release automatically on stale timeout, on explicit POST /api/admin/ticket/:id/release, or via navigator.sendBeacon firing on tab close so a crashed browser doesn't hold a lock for the full stale window. Admins can force-release any lock; other roles only their own.

16 WebSocket Config NEW

KeyDefaultBehavior
WS_RECONNECT_DELAY_MS5000Initial delay before first reconnect attempt
WS_MAX_RECONNECT_DELAY_MS30000Ceiling for exponential backoff
WS_PING_INTERVAL_MS30000Keepalive ping cadence
WS_MAX_RECONNECT_ATTEMPTS5Attempts before giving up and surfacing a "disconnected" state
WS_EXPONENTIAL_BACKOFF_ENABLEDtrueToggles backoff vs. fixed-delay retry

Connection path: GET /api/admin/ws upgrades through the Worker to the DO's /connect route, passing allowed_languages and allowed_categories as query params so the DO only broadcasts events the connecting user is scoped to see.

17 CORS

CORS_ORIGINS in config.js is a fallback only. Since §5, the authoritative list lives in Settings → System Config → CORS Allowed Origins; treat the DB value as production truth.

CORS_ORIGINS // config.js fallback = [
  'https://dornori.com',
  'https://www.dornori.com',
  'https://dornori.github.io',
  'https://dornori-ticketing.dornori-info.workers.dev'
]

18 Languages & Categories NEW

Both are managed entirely through Settings, stored as rows in the settings table — no separate tables.

Categories

Stored under category category, keys <slug>_description and <slug>_color. Deleting a category never touches existing tickets — they keep the slug. Category colors are assigned from a fixed 10-value palette, round-robin, first-seen order: #5aa9ff, #ffb347, #a78bfa, #34d399, #f87171, #fbbf24, #60a5fa, #4ade80, #fb923c, #c084fc.

Languages

Stored under category language. The first language configured is the default applied to any ticket created without an explicit language — most commonly inbound email to an address with no language mapping. Every language-aware page (dashboard filters, newsletter, order-reply, email routing, auto-reply) reads from this same list.

19 Product Data Feeds

Used by applyOrderTags server-side rendering when composing order-reply payment-confirmation emails.

  • {PRODUCTS_DATA_BASE_URL}/{lang}/products.json — localized product display names, one file per language.
  • {PRODUCTS_IMAGES_BASE_URL}/products.json — single shared file for images and non-text metadata.

20 Deployment Checklist

StepDetail
1Set secrets: wrangler secret put JWT_SECRET, wrangler secret put SCRIPT_URL (+ SCRIPT_SECRET/USERNAME/PASSWORD)
2Bind D1 (DB), KV (KV), and the Durable Object class for TICKET_HUB, with a new_classes migration
3Deploy ticketworker.js as the production Worker (not worker.js)
4Confirm API_BASE in config.js matches the deployed Worker URL
5Replace placeholder cdn.example.com product feed URLs with production values
6Verify config.js loads before shared.js on every page
7Insert the first admin user directly in D1 — no self-serve admin signup exists
8Populate Settings → Languages and → Categories before Email Routing / Auto-Reply
9Purge cache once via POST /api/admin/cache/purge after any settings migration

21 Changelog vs v1 Documentation

What actually changed in the code since the last configuration manual, so nothing here gets missed again.

  • Full JWT-based auth and role-based access control replaced the "anyone with a login is a full admin" model.
  • New users table, new Users page, per-user language/category/email/permission scoping.
  • New TICKET_HUB Durable Object: ticket locking, WebSocket realtime push, edge-enforced login rate limiting.
  • New KV binding for settings cache + config-version cache-busting.
  • Multi-language support threaded through tickets, email routing, auto-reply, newsletter, and order-reply.
  • New Order Reply page for payment-confirmation templates and payment-ticket replies.
  • Settings reorganized into 8 tabs, including a new System Config tab exposing live-editable CORS/rate-limit/session values.
  • SLA auto-close changed from a fixed global 3-day timer to per-category, configurable grace windows.
  • SLA color thresholds corrected: 80%/95% elapsed, not the 50%/25%-remaining bands previously documented.
Dornorium Powered by Dornorium · © Dornori