Queue Manager: Product Spec (Contract)
Virtual waiting room / traffic management, CrowdHandler & Queue-it class.
Stack (fixed, do not change)
- Node.js >= 18. The runtime is zero-dependency: nothing under
server.js,lib/,snippet/orpublic/may import a package fromnode_modules; node builtins only (node:http,node:crypto,node:fs, …).dependenciesinpackage.jsonstays empty. - Vitest is the dev-only test runner (
devDependencies, the single permitted npm package).npm test→vitest run,npm run test:watch→vitest. Config invitest.config.js; suites intest/*.test.jsuse the Vitest globals (describe/it/expect/beforeAll/afterAll), so no test file imports it either. Shipping or deploying the product never installs it. - Single process:
node server.js. Port8080(envPORT). - Realtime: Server-Sent Events (SSE). No websockets.
- Persistence:
STORE=valkey+SIDESTORE=pgin production (NODE_ENV=productionrefuses anything else): the live queue in Valkey, every change journaled per room to Postgres, everything else in Postgres. State survives a restart.STORE=memory(development and tests) is in-process and diskless: nothing is written to disk, and every boot starts empty. The file journal (data/) was removed in step 5. - Event ordering (QM-449, normative for the port): every room's events MUST carry a monotonic per-room sequence number so replay can detect a gap or a reordering. The Valkey store does: every row of the Postgres journal carries its room's
seq, and a rebuild detects a gap. The memory store keeps no journal. - Admin auth:
ADMIN_KEYenv (defaultadmin-dev), sent asAuthorization: Bearer <key>. With the default key the server binds127.0.0.1whenHOSTis unset and refuses to start whenHOSTis not loopback. Other admin credentials: named operator keys (qmo_…, roleowner | operator | viewer,403 insufficient_rolewhen the role is short), the read-only monitor token, and the console session cookieqm_console(below). Wrong credentials count againstADMIN_AUTH_FAIL_PER_MIN; a locked-out address gets429 too_many_auth_failuresbefore any credential is read. See OPERATIONS.md, Two keys, two blast radii, and Operators, roles and the audit trail. A query-string credential lands in access logs, inRefererheaders, and, on an inline host (where/__qm/*is rewritten before auth runs), in the CUSTOMER's access and CDN logs. So no key is ever accepted from a URL. The SSE route is the one placeEventSourcecannot send a header:POST /api/admin/sse-ticket(Bearer) returns a single-use ticket, valid 30s, spent on first use, scoped to the minting credential, redeemed asGET /api/admin/events?ticket=<t>. The shareable monitor link carries its viewer token in the URL fragment, which no browser sends to any server. - Tokens:
base64url(JSON) "." base64url(HMAC-SHA256), root secret fromSECRETenv (default random per boot; required withSIDESTORE=pg). QM-352, two forms, both always verified. Legacy (signed by default): HMAC key SECRET, nokid, accepted for any purpose whose payload checks pass. v2 (signed whenTOKEN_SIGN_V2=1): key per purpose = HKDF-SHA256(SECRET, salt empty, infoqm:visitor|qm:monitor|qm:session|qm:operator, 32 bytes), payload carrieskid= hex(HKDF-SHA256(SECRET, salt empty,qm:kid, 4 bytes)), unknown kid refused, never valid for another purpose.SECRET_PREVIOUSkeeps the previous SECRET verifying (either form) during a rotation; new tokens useSECRET. Operator verifiers follow the same rule and are never downgraded from v2. See OPERATIONS.md, Signing keys and rotating SECRET. - Visitor token payload (purpose
visitor):{r, n, g, iat}for a place in line, or{r, q, g, iat}for a pre-queue entry. Exactly one ofn/q, never both; v2 addskid.rroom id;nticket number (integer >= 0,0= bypass pass holding no slot);qpre-queue handle (integer >= 1, not a position);groom generation (integer >= 1; a deleted and re-created room gets a new one, so an old ticket cannot claim a place in the new line);iatissued-at epoch ms. Refused pastTOKEN_MAX_AGE_SEC(default 86400, minimum 60) afteriat, or withiatmore than 60 s in the future. The token carries no waiting/passed status: that lives in the engine, keyed byr+n. Other purposes (monitor,session,operator) have their own payloads and are never accepted as a visitor token under v2.
File ownership (builders stay in their lane)
| Path | Owner |
|---|---|
server.js, lib/engine.js, lib/roomstore/, lib/token.js | engine builder |
public/waiting.html (+ inline CSS/JS) | visitor-UI builder |
public/admin.html (+ inline CSS/JS) | dashboard builder |
snippet/qm.js, INTEGRATION.md | integration builder |
test/*.test.js | each builder adds own |
PROGRESS.html, SPEC.md | orchestrator only |
Core concepts
- Room (waiting room): id, name, target URL,
ratePerMinute(outflow),maxConcurrent(optional), configured state:active | paused | bypass(bypass = queue off, all pass). A room whoseopensAtis still in the future reports the effective statescheduledon the visitor wire while its configured state remains one of the three; admin listings carry both, plusopensAtand apreQueuecount. - Visitor token: signed; holds room id, ticket number or pre-queue handle, room generation and issued-at (payload above). Whether that ticket is waiting or has passed is engine state, not token state.
- Ownership cookie
qms_<roomId>: an opaque random session id (16 to 128 chars), set HttpOnly beside the token on/api/joinand bound to the ticket engine-side (only its hash is stored). A token presented without the browser that queued for it does not carry the place; a join without the cookie mints a fresh one. See OPERATIONS.md, How a pass is bound to a visitor. - Queue cookie scope (QM-504, QM-526, normative): the per-room cookies
qm_<roomId>,qms_<roomId>andqm_dk_<roomId>stayPath=/. Path is not narrowed: connectors on the customer origin read them onPath=/, and narrowing would leave duplicate cookies beside the oldPath=/ones. Instead the queue host keeps at most 8 rooms' cookies per browser (ROOM_COOKIE_CAP); setting a room's cookies when more are present expires the excess rooms' cookies in the same response, lowest-value first (539): rooms the server does not have, then rooms whose queue token fails signature or expiry (or which hold no token and a malformed session id; never a room with a door key), then rooms holding only a session id (no queue token, no door key: most often a finished visit), then live rooms newest first, so a place held before a hostile walk starts survives a walk of any length; the room being set in that response is never evicted. Ranking uses local checks only, no store read. Residual risks: a walk seeded before the visitor joins can still evict that place with one more room (inherent to any fixed order; the session-only tier keeps finished rooms from serving as cheap seeds); a visitor really queued in more than 8 live rooms on one host loses the most recently joined ones, not the oldest. - Generation
g: bumped when a room is deleted and re-created. A token from an earlier generation is not honoured by/api/join(the caller gets a new place),/api/notifyanswers409 stale_ticket, and/api/statusand the event stream answer{expired:true, reason:"room_reset"}. - Fairness: strict FIFO by ticket number. Re-visits keep position (token in cookie/localStorage, plus the ownership cookie). Lost token = back of line.
- Token refresh (QM-391): a wait may outlast the token (
TOKEN_MAX_AGE_SEC) and the queue cookies (QUEUE_COOKIE_MAX_AGE_SEC), above all a pre-queue for anopensAtdays away. Once a presented visitor token is at least half the shorter of the two old,/api/statusand the event stream re-sign the same place ({r, n|q, g}with a newiat, signed with the keyring in force, so v2 andkidfollowTOKEN_SIGN_V2) and re-set bothqm_<roomId>andqms_<roomId>(same session id), only when all hold: the room exists andgis its generation; the place is still waiting (status neitherexpirednorpassed; a pre-queue handle counts); and the request'sqms_<roomId>proves the place engine-side. A fingerprint match never earns one./api/statusreturns the new token astoken; a stream opened with a due token carries it astokenin every frame and sets the cookies on its response, and an open stream whose token falls due is ended so the browser reconnects and refreshes. The waiting page stores atokenonly when it names the place it already holds. A token already pastTOKEN_MAX_AGE_SECis refused as before: the refresh cannot resurrect one. - Outflow: engine promotes
ratePerMinutewaiting→passed per minute, smooth (per-second slices, not bursts). A passed ticket is validpassedTtlSec(default 600) to enter the target site. - Scheduled drop: a room may carry
opensAt. Before it there is no line at all: joiners are held in a pre-queue and issued an opaque handle, not a ticket number. AtopensAtthe pre-queue is drawn into FIFO order using a crypto-grade random permutation, round-robin across identities so a second entry from one identity never outranks any other identity's first. The permutation is recorded, so a restart across the open instant replays it instead of drawing again.preQueueMaxPerIp(default 16,null= unlimited, 1..100000) caps entries per identity; a join over it is429 prequeue_identity_limitwith no token, handle or cookie returned, and a pre-queue at its hard ceiling is503 prequeue_full. Invariant: arrival order within the pre-queue must not correlate with drawn position. Arriving early buys nothing. Taking the schedule away while entries are held means "open now":opensAt: nullonPOST /api/admin/rooms/:id/schedule,opensAt: nullin a room save (POST /api/admin/rooms, which is what the console sends), or removing abranding.opensAtthat was the only schedule. The pre-queue is drawn at once in the same random order and becomes the front of the line (recorded as anopenwithfor: null); it is never discarded. A schedule moved to an instant already past opens the same way, except that the instant the room last opened for opens it again only when a pre-queue has collected since (an empty pre-queue records no second open; a pre-queue that collected after a re-arm is drawn once), and a save that leaves a future schedule in place draws nothing. - Ghost tickets (QM-345): a pass reserves a
maxConcurrentslot only for a holder seen (join,/api/status, or the/eventsheartbeat) withinpresenceSec(default 30,null= rule off). An absent holder's ticket is still promoted in FIFO order, but its pass owns no slot (a pass past its claim window: usable at the door withinpassedTtlSec), and on the clock it costs no outflow; a pass whose holder was never told they are through gives its slot back afterpresenceSecunseen. Thepasslog event lists those tickets innsso replay restores them slotless.queueMaxPerIp(default 16,null= unlimited, 1..100000) caps waiting-line places per client address; a new join over it is429 queue_identity_limitwith nothing spendable returned. Tickets with no recorded holder (engine-internal callers) are exempt from both.
HTTP API (contract: UI builders code against this)
Versioning policy
Every route below is served at /api/v1/<route> (canonical, pinned) and at the unversioned /api/<route> (permanent alias, same handler, byte-identical response). The snippet is deployed on third-party origins that cannot be upgraded in lockstep with this server, so it asks for /api/v1/* and falls back to /api/* once per page if the server 404s the prefix.
- Breaking changes ship as
/api/v2/*; v1 keeps its shapes. Additive optional fields stay in v1. - The unversioned aliases are not deprecated and are never removed; they track the newest contract, which is why pinned integrations must not use them.
- Unversioned surface (not part of the contract):
/healthz,/w/:roomId,/snippet/*,/,/progress,/metrics,/events(the permanent bare alias of the contract route/api/events, see Visitor below; listed here so a build generating its path set from this section does not drop it),/docs(+/docs/:name, which rendersINTEGRATION.md,OPERATIONS.mdand this file for readers who only ever see the running server),/docs/th(+/docs/th/:name, the same guides in Thai fromdocs/th/<file>). - Wrong verb on a contract path →
405+Allowheader +{"code":"method_not_allowed"}. OPTIONSpreflight runs the same CORS decision as the real method: it must never advertise an origin the actual response would refuse.
Visitor
POST /api/join {roomId, token?, challenge?}→{token, position, ahead, etaSec, state}(sets cookieqm_<roomId>with the token and the HttpOnly ownership cookieqms_<roomId>). A same-generation token in the body or cookie keeps its place (a pre-queue handle is exchanged for its drawn ticket once the doors open). Refusals:429 rate_limited(JOIN_LIMIT_PER_MIN),400 invalid_room_id/invalid_token_field,404 room_not_found,403 blocked_by_protection(room protection in enforce mode),403 firewall_blocked(the room's firewall, below),403 challenge_required/403 challenge_failed/503 challenge_unavailable/400 invalid_challenge_field(the room's optional Turnstile challenge, below),429 queue_identity_limit,429 prequeue_identity_limit,503 prequeue_full,503 storage_unavailable(the join could not be flushed to disk, so no ticket is handed out).- Turnstile challenge (Notion 742; room field
challenge: null | {mode:"off"|"turnstile", failOpen:boolean}, default off). NeedsTURNSTILE_SITE_KEYandTURNSTILE_SECRET_KEY. For a room withmode:"turnstile"(and not inbypass), a/api/jointhat would mint a place (a ticket or a pre-queue entry) must carrychallenge, a Turnstile response, verified server-side at Cloudflare's siteverify with the secret and the client address (remoteip). Without one:403 challenge_required; a rejected one:403 challenge_failed; both carrychallenge: {provider:"turnstile", siteKey, src}and mint nothing (no ticket, no pre-queue entry, no cookie). A caller whoseqms_<roomId>cookie proves it holds a live place in the room is not asked (the token alone never exempts). Siteverify unreachable, slow, 5xx or refusing our secret:failOpen:trueadmits the join unverified,failOpen:falseanswers503 challenge_unavailablewithRetry-After; a response siteverify rejected is never admitted. Responses are single use and nothing is cached. A request carrying a validLOADTEST_KEYis not asked. The server-side join that serves the waiting page to a script-less visitor does not run for such a room. Counted inqm_challenge_total{result}. See OPERATIONS.md, Turnstile challenge. - Room firewall (Notion 743; room field
firewall: null | {mode:"deny"|"allow", ips:[cidr…], countries:[code…], message?}, defaultnull= no rules).denyrefuses the listed addresses and countries,allowadmits only them. A caller the rules refuse gets, fromPOST /api/join,POST /api/redeem(the code is not spent and the place does not move),POST /api/notify(no address is filed or replaced and no mail is sent; a withdrawal, an emptyemail, is let through so nobody's address is kept against their wish),GET /api/status,GET /api/eventsand (as a page, status403, for a browser navigation; as JSON otherwise)GET /w/<room>and an inline room's gate:403 firewall_blocked(body carries the operator'smessage{en?, th?}when set). It mints nothing: no ticket, no pre-queue entry, no cookie. The rules are also the door's:GET /api/checkanswers200 {action:"queue", reason:"firewall_blocked", blocked:true, waitingRoomUrl, message?}(a200queue verdict, not a403, because every connector reads a403as a wrong key and fails open), admits nothing and issues nosess; an inline gate and a WebSocket upgrade answer403and forward nothing. So a place held from before a rule does not pass it, and a stream already open when the rules change is ended withevent: firewall. A page outside the room's URL targeting is not refused. A room inbypassis still enforced. The address judged isrealClientIp(never theLOADTEST_KEYidentity), IPv6 ranges are matched as written (not atIPV6_PREFIX_BITS), and a vouched/api/check(?ip=) is judged on the vouched address and its optional&country=(absent = unknown country; a vouched check without it for a room with country rules is counted inqm_firewall_vouched_without_country_totaland named in healthfirewall.vouchedWithoutCountry). The country isCF-IPCountry, believed only on a request that passed theEDGE_SECRETcheck; otherwise it is unknown. An unknown country (absent,XX, malformed) is in no list:denylets it in,allowturns it away unless an address rule admits it. Counted inqm_firewall_blocked_total{reason:"ip"|"country"|"allowlist"}. See OPERATIONS.md, Room firewall. GET /api/status?token=→{position, ahead, etaSec, state, passed, redirectUrl?, transport?, pollMs?, soldOut?, peopleInside?}.peopleInside(Notion 882) is on a waiting place only (also in the join answer and every SSE frame of one): how many people are inside now, the room'soccupancy(sessions on the site plus passes still inside their claim window), exact below 100 and rounded down to a ten from 100 up, so a change of a few sessions is not a new frame for every waiting stream. It is never sent with the room's capacity (maxConcurrentis not sent to a visitor). It is notinside, which/api/joinsets totruefor a caller already on the site.soldOut: true(Notion 745) appears only on a waiting place of a room that has a stock and whose stock is 0: the line is held, not ended,etaSecisnull, and the place is kept. The count itself is never sent to a visitor. Token from?token=(not on an inline host) or theqm_<roomId>cookie; none valid →401 invalid_token.GET /api/events?token=→ SSE: eventstatuswith same JSON as /api/status, pushed on change + every 5s heartbeat. Versioned like every other contract route (/api/v1/events), and also served at the bare/events, which the shipped waiting page asks for. That alias is permanent, not legacy: every waiting page currently open in a browser holds anEventSourceon it, and those reconnect by themselves after a restart or a deploy, so removing the path would break the visitors who are in the queue at that moment. The server ends the stream (Notion 843): right after a final frame, which is astatusframe withexpired,ejected,passed: true(a pass, a bypass, or a deleted room) orclosed: true(the room closed under a waiting visitor); and atSSE_MAX_AGE_MS(default 600000, plus 0-50 % per stream), after anevent: refreshwith data{}. A client (the shipped page, or an integrator'sEventSourceon/api/v1/events) MUST stop on a final frame (close()theEventSource, act on the answer) and not reconnect: anEventSourcereconnects on its own after any end, so a client that does not stop re-opens a stream that is answered with the same final frame at once. Onrefreshit reopens the stream (one reconnect, no poll). Stream limits:503 sse_capacityatSSE_MAX_TOTALstreams,429 sse_per_ip_limitatSSE_PER_IPper address, both withRetry-After: 5.- Refresh frame (QM-469). When the stream's token is due to be re-signed (
TOKEN_REFRESH_AFTER_MSafter itsiat: half the shorter ofTOKEN_MAX_AGE_SECandQUEUE_COOKIE_MAX_AGE_SEC) and the refresh would be granted, the server sendsevent: refreshwith data{}and ends the stream. A stream cannot set cookies once its headers are sent. The page reopens the stream itself, once, and the new stream's response re-signs the place and re-sets both cookies. Itsstatusframes then carry the freshtoken. The end is delayed past the due time by a jitter fixed per place:uint32_be(sha256("r|n|q|g|iat")[0..4]) % (floor(TOKEN_REFRESH_AFTER_MS / 10) + 1)ms, over the token payload's fields (a field the token does not carry, such asqon a ticket, is the literal textundefined, as JavaScript renders it), so at most +10% of the window, and a burst of joins with oneiatdoes not reconnect together. A port must send the same frame and use the same jitter. A stream whose due refresh would not be granted is never ended for it. - Transport hint (Notion 850). The status answer of a ticket far from the head (
/api/status, the/api/joinanswer and/api/eventsframes; only a plain waiting place, never a pre-queue, scheduled, passed, expired, ejected or closed answer) carriestransport: "poll"andpollMs(20000 to 120000 by default,SSE_FAR_POLL_MIN_SEC/SSE_FAR_POLL_MAX_SEC): the client should hold no stream and ask/api/statusagain after aboutpollMs. Every other answer carries neither field, and an absenttransportmeans stream. A ticket is near, and streams, when itspositionis at mostSSE_NEAR_POSITION(default 20000), or itsetaSecis at mostSSE_NEAR_SEC(default 300) and itspositionat mostSSE_NEAR_MAX_POSITION(default 100000: the ETA test alone grows with the drain rate and would outgrow the edge's concurrent-connection ceiling, about 285-300k fleet-wide). Every other ticket is far.pollMsisetaSec/ 10 clamped to 10-60 s (60 s with no ETA); presence does not change it. A frame of an already open stream is judged with a wider test (2xSSE_NEAR_SEC, 1.25x both position limits), so a page hovering at the threshold is not ended and reopened. A client that opens/api/events?tr=1says it honours the hint: the server sends the farstatusframe, an SSEretry:ofpollMs, and ends the stream (qm_sse_streams_ended_total{reason="far"}). That client MUSTclose()itsEventSourceon the frame and not reopen it until an answer carries nopoll. A stream opened withouttr=1is never ended for this: it sees the hint and keeps streaming, as before.SSE_FAR_POLL=0turns the hint off. GET /w/:roomId→ serves waiting.html (injects roomId + branding JSON aswindow.QM_CONFIG). Aqm_returnthat the room's return policy refuses is stripped, not honoured.- The page's style and main script are linked, not inline (QM-467):
GET /assets/waiting-<hash>.cssand/assets/waiting-<hash>.js, also under/__qm/assets/…on an inline host.<hash>is the first 22 characters of the base64url SHA-256 of the file. They are served withCache-Control: public, max-age=31536000, immutable. A process serves only its own build's hashes, so with more than one instance, or during a rolling deploy, every instance must serve every hash that any instance is still handing out. See OPERATIONS.md, Waiting-page assets and live streams across a deploy. - A visitor arriving with a token that is no longer a place gets
lapsedin that config:"expired"when their own entry window ran out,"reset"when it was our doing (eject, purge, room reset), absent when nothing was lost. Both deployments derive it from the engine's own word for the refusal, and the page has the sentence for each in every locale; without it the visitor is told their ticket "could not be verified", which names a fault that did not happen. A token known to have lapsed is also treated as no token, so the replacement place the page promises is minted, including for a visitor with no JavaScript, who has no second way to recover. POST /api/notify {token?, email?, lang?}→ registers (or, with an empty/omittedemail, withdraws) the visitor's turn notification. Ticket comes from the body token or the queue cookie, never the URL.langis the page language the e-mail is written in (Thai forth, English otherwise). Answers{ok, notify, emailDelivery}:notify.deliveryis"email"when SMTP is configured and"recorded"when the server only keeps the address, andemailDeliveryis{enabled:true, nearPlace, onTurn:true}or{enabled:false}.- Notification e-mail (Notion 746). With
EMAIL_NOTIFYon andSMTP_HOSTplus a validSMTP_FROMset, a place that holds an address is e-mailed twice, each at most once: near when its place is at or below the room'snotifyNear(1 to 1000, or null forEMAIL_NOTIFY_AT, default 50; not while a scheduled room's doors are shut) and turn when its pass is minted (the head passed it and its entry window is live, it is not yet inside). Only the leader scans and sends, off the request path, through a bounded queue paced per instance and per fleet, retrying 4xx and network failures with backoff and giving up on 5xx. A mail is claimed in one atomic store step before it is queued, so several instances, a failover or a restart send it at most once; a turn claim deletes the address, a near claim marks the record, a re-save or a withdraw-and-refile keeps the marks. The address is deleted at the turn claim and with the ticket on every end, never logged, and the e-mail carries no token, ticket or reference: only the room name and the linkPUBLIC_URL/w/<room>, which cannot claim a place because theqms_<room>cookie does. SMTP off changes nothing. See OPERATIONS.md, Notification e-mail. POST /api/redeem {code, token?}(Notion 744) →{ok:true, result:"ok", effect:"skip"|"jump", position, ahead, etaSec, priority}. A visitor who holds a waiting place in the room presents a priority code (the ticket comes from the body token or the queue cookie, never the URL). One code per place. Refusals:400 code_invalid(unknown, expired, used up or revoked: one answer on purpose, so a guess learns nothing),409 not_in_line(no waiting place),409 already_priority(nothing spent),429 rate_limited(REDEEM_LIMIT_PER_MIN),429 redeem_locked(a place wrongREDEEM_FAIL_LIMITtimes inREDEEM_FAIL_WINDOW_SEC, withRetry-After; the right code is refused too until the window ends),401 invalid_token,400 invalid_code_field. The waiting page also redeems/w/<room>?code=…by itself and removescodefrom the address bar.- Priority codes (Notion 744). Per room.
skip: the holder is admitted at the next tick, ahead of the rate's pacing, but only into a free slot (maxConcurrent, the door and a paused or scheduled room still bind it).jump: the holder stands in front of every ticket without a code and is admitted at the normal pace. Position order is skip holders, then jump holders (each by ticket number), then everybody else in FIFO order, so a ticket without a code is pushed back by at most the number of code holders. A code that is redeemed keeps its effect after it is revoked or expires. - Stock control (Notion 745). A room may carry a stock: how many visitors it may still admit. Unset (the default) means no limit and changes nothing. Every pass the room mints reserves one unit, in the same step as the promotion, so no number of instances can oversell and the stock never goes below 0: the clock, an operator's flush (
force: trueincluded) and a skip code all stop at it. A ghost's pass (its holder is not there) takes a unit too, because the holder who comes back holds a valid pass. At 0 the line is held, not ended: nobody is admitted, every place is kept and a join still gets a place at the back; when stock is raised (the shop returns units, an operator adds some) admission resumes from the head, in order. Units come back on their own in two cases: a pass that lapses unclaimed (its holder never used it at the door before the grant ran out) gives its unit back, and an eject of any pass, claimed or not, gives back its unit in the same step; the tick that finds the lapse then admits the next waiting visitor in order. A pass that was claimed and ends by itself (the grant or the session running out) does not: the shop returns it. Only a pass minted while the room has a stock holds a unit, and asetis the truth: units out before it are not given back after it, so a return never takes the stock above what the shop or operator set plus what they added since (a delta that stopped at 0 is not remembered).bypasspromotes nobody and takes nothing. A purge keeps the stock; deleting the room drops it. POST /api/stock/:roomIdandGET /api/stock/:roomId(Notion 745, also/api/v1/stock/:roomId) are the shop's side of the stock, server to server, authenticated withAuthorization: Bearer <STOCK_API_KEY>(its own key: neitherPUBLIC_API_KEYnorADMIN_KEYopens it; the key in the query string is refused,401 credential_in_query; with noSTOCK_API_KEYset the route is off,404 stock_api_disabled).GET→{roomId, stock, soldOut}(stock: nullis no limit).POST {delta: n, key}takes (n< 0: a sale confirmed) or returns (n> 0: a cart abandoned, a reservation expired) units;POST {set: n | null}sets the number outright,nullremoves the limit.key(the order id; alsoorderId, or anIdempotency-Keyheader) is required withdelta: the same key with the same call is answered again withreplayed: trueand changes nothing, so a retry cannot count twice; the same key with another call is409 stock_key_conflict. The last 5000 keys per room are remembered. Answer200 {roomId, stock, soldOut, previous, applied, clamped?, replayed}:appliedis what actually moved, and a delta stops at 0 (and at 1,000,000,000) and says so withclamped: true. Refusals:400 invalid_stock(send exactly one ofsetanddelta; whole numbers,set0 to 1,000,000,000,deltanon-zero),400 invalid_key,400 key_required,409 stock_not_set(a delta on a room with no stock: set one first),409 stock_key_conflict,404 room_not_found,401 unauthorized,404 stock_api_disabled,429 rate_limited(STOCK_LIMIT_PER_MIN). A change is answered only once it is on disk (503 storage_unavailableotherwise; the retry finds its key).POST /api/release(Notion 885, also/api/v1/release) is the shop's "this buyer reached payment", server to server (the buyer is no longer a holder from then: coming back they queue again as a new visitor, and a failed or cancelled payment is returned to the stock by the shop itself with adelta), with the sameAuthorization: Bearer <STOCK_API_KEY>and the same refusals (401 unauthorized,401 credential_in_query,404 stock_api_disabled,429 rate_limited, a failed-key budget shared with the stock route; its ownSTOCK_LIMIT_PER_MINbucket). Body{roomId, token}:tokenis the visitor's own queue token, which names the ticket (no door key is needed); anything else is400 invalid_request; a body that is not JSON, not an object or over 4 KB is400 invalid_json,400 invalid_bodyor413 payload_too_large, and those three are not counted inqm_release_total. The visitor's door session and any pass they have not used end in the same step, so themaxConcurrentslot is free for the next tick (it isejectwith the pass's stock unit kept spent, journaled as the sameejectevent without a stock figure, so a rebuild keeps it). Only a visitor who is inside is released; a ticket still waiting in the line is never touched. Answer200 {released: true}, or200 {released: false, reason}withreasonone ofnot_inside(released before, ended, or still waiting; a retry is safe),invalid_token(not signed by this server, expired, another room's, or from before a reset),no_room; it is never a 404 for a token. The visitor is not put back in the line: their next/api/checkisqueuewith reasonejected, and they queue again as a new visitor. The stock is not touched. Audited asrelease.shop(actorshop, ticket number, never the token); counted inqm_release_total{result}.POST /api/hooks/mandrillandHEAD /api/hooks/mandrill(Notion 753) are Mandrill's delivery webhook, called by Mandrill and by nobody else.POSTtakesapplication/x-www-form-urlencodedwithmandrill_events= a JSON array of events, signed inX-Mandrill-Signature= base64(HMAC-SHA1(MANDRILL_WEBHOOK_KEY,MANDRILL_WEBHOOK_URL+ each field's name and value, fields sorted by name)), compared in constant time;HEADanswers200unsigned. With noMANDRILL_WEBHOOK_KEYthe route is off:404 mandrill_webhook_disabledfor every method. Answers200 {ok, counted, ignored},401 unauthorized(a failed signature spends the admin failed-auth budget,429 too_many_auth_failuresonce it is empty),400 invalid_events,413 payload_too_large(1 MiB),405(Allow: HEAD, POST). Eventssend,delivered,deferral,hard_bounce,soft_bounce,open,click,spam,unsub,rejectare counted (qm_email_delivery_total{event}); any other is ignored. The last 50 failures are kept with a masked address; no address is logged or stored. See OPERATIONS.md, "Delivery status".- A turn notification is filed against the ticket, so wherever the server replaces a ticket it carries the record over: the pre-queue draw, and a rejoin presenting a ticket the engine will not honour. The client sends the dead token on that rejoin for exactly this reason. A purge or an eject deletes it instead: the operator discarded that place in line.
POST /api/jointherefore also answersnotify:{emailMasked, requestedAt, delivery}(delivery:"email"or"recorded") ornull, stating what is held against the place it just named. Absent entirely whenEMAIL_NOTIFYis off; the page reads absence as "no statement" andnullas "nothing stored", and stops claiming a save the server does not have.- Before
opensAt,/api/joinand/api/statusanswer{state:"scheduled", scheduled:true, preQueued:true, preCount, opensAt, now}withpositionandaheadnull, and the token carries a pre-queue handleqinstead of a ticketn. - Every visitor error is
{error, code}; branch oncode. The full visitor-facing list is INTEGRATION.md, Error codes. - Any frame carrying a server instant carries
now(server epoch ms) beside it:opensAton a scheduled drop,messageAtwhen an operator message is set. Server instants are the only times on the visitor's wire that are not device-relative, and the page renders every clock time it shows in the DEVICE's frame (instant - (now - clientNow)), because that is the clock the visitor compares it against. Withoutnowa skewed device reads a skew-corrected countdown beside an uncorrected "doors open at", and the two disagree. A frame that names no server instant needs nonow.
Edge check (used by snippet)
GET /api/check?roomId=&token=&url=→{action: "pass"|"queue", reason?, waitingRoomUrl?, clearToken?, sess?, targeting?, …}: pass if room bypass/inactive or the token's ticket has passed and is unexpired. An unknown room answers200 {action:"pass", reason:"no_room"}(fail open), counted for the operator in/api/admin/healthand/metrics. Apassthat admits somebody is answered only once the admission is on disk;503 storage_unavailableif it could not be written, and the admission is taken back so a retry is admitted.- Door-session key
sess: returned on thepassthat opens (or reclaims) a door session, and replayed on every later check as theX-QM-Sessionheader (what the snippet sends: a header keeps the credential out of URLs and logs),?sess=, or on an inline host the HttpOnlyqm_dk_<roomId>cookie.clearToken: truemeans drop the stored token and key before redirecting; it accompaniessession_elsewhereandbound_to_other_client(QM-792). The snippet then redirects with?qm_reset=<ticket>(also on its 3rd-redirect breaker) and the waiting page drops its own stored pass for the room only if that is the ticket it holds (QM-795); local only, nothing is revoked server-side. Because the body can carrysess, on a room with an origin policy/api/check(and itsOPTIONS) sendsAccess-Control-Allow-Originonly to a browser origin in the room's tag origins (tagOrigins, elsereturnOrigins, plus thetargetUrlorigin). See INTEGRATION.md, The door-session key. - Door ownership gates (QM-796,
checkonly;statusis unchanged). A direct caller of a passed ticket is measured against the ticket's recorded holder by fingerprint (bound_to_other_client), then, once an admission exists, against the admission (fingerprint again, then the door key:session_elsewhere). Two proofs outrank the fingerprint comparisons (never the door-key gate): (1) the caller presents the door key of the ticket's live admission (X-QM-Sessionequal to the admission's key), so an address or browser-build change mid-session no longer refuses its holder; (2) the identity carriesclaimed: true, which the server sets only after verifying a waiting-room claim (X-QM-Claim, minted by the cookie holder, bound to this room and ticket, 60 s) — it lets the first use of a ticket through from another address and mints the door key as usual; once an admission exists a claim alone getssession_elsewhere, so it is usable once in effect. Neither proof overrides a queue cookie the caller presents that contradicts the recorded one (a different browser:bound_to_other_client), a wrong or absent key behaves exactly as before, and the vouched (server-side) path is untouched. The Valkeycheck.luaand the door's fast case decide identically (a claim is always the script's). ?ip=&agent=vouches for the real client (server-side and edge connectors) and needsAuthorization: Bearer <PUBLIC_API_KEY>(orADMIN_KEY); without it401 unauthorized, or401 credential_in_querywhen the key was sent as?key=. A vouched check is rate-limited per vouched address, not per calling colo.url=is the page being visited. It decides scope: whether this page belongs to the room at all. Absent, theRefererheader is used; absent both, the check isunknownand fails open into the queue (never silently unprotected).?targeting=1adds the room's full rule list to the response.- A page the room's rules exclude answers
{action:"pass", reason:"out_of_scope"}without minting a place in line. targetingis present only on scoped rooms:{rev, rules, scope:"in"|"out"|"unknown", rule, action}. A room with no rules omits the key entirely and behaves exactly as it did before URL targeting existed.
Targeting (public, used by edge connectors)
GET /api/targeting?roomId=→{roomId, rev, scoped, updatedAt, patterns:[{pattern, action}]}. It is the room's URL scope, so a Worker/Lambda/nginx connector pulls the rules at runtime instead of hard-coding them.ETag+304so it is cheap to poll.GET /api/entry?roomId=(Notion 815) →{state:"open"|"full"|"closed", url, rev}: what a visitor with no place would meet now, so an edge connector can answer without a check call. Public, no visitor data,Cache-Control: public, max-age=5with anETag(304on a match),Access-Control-Allow-Origin: *, rate limited like/api/targeting.urlis the absolute page forfullandclosed,nullwhen open;revis the targeting revision. A malformed or unknown room is404 room_not_found. A failed call is to be read asopen(the check still decides).
Install checks and connector registry (public)
GET /api/verify?roomId=&url=&origin=&connector=&version=→{ok, checks:[{id, status:"pass"|"fail"|"warn"|"info", title, detail?, fix?}], …}. It is the pre-deploy check every connector's CLI or settings screen runs.originfalls back to the origin ofurl, then the request'sOriginheader. ABearerPublic API key makes the report privileged (it also checks the key); a key in?key=is reported as a failing check.400 invalid_room_idwithoutroomId. Checks are recorded for the console's "connectors that checked in" list. See INTEGRATION.md, Installable connectors.GET /api/verify.gif?roomId=&origin=&connector=→ the same verdict as a status code, for the GTM sandbox, which can only see whether an image loaded:200 image/gifwhenok, else424 {ok:false, error:"verify_failed", checks}.X-QM-Verifynames the failing check ids;Cache-Control: no-store.GET /api/connectors→ the registry: each connector's version, install/upgrade/verify commands, download URL and SHA-256 integrity, as served by this server.GET /api/connectors/wordpress/update→ the same for WordPress's plugin-updater shape. The artifacts themselves are under/connectors/<name>/latest.{js,tgz,zip}(unversioned)./api/verify,/api/verify.gifand/api/connectorsshare theCHECK_LIMIT_PER_MINbudget (429 rate_limited).
Health (public, unauthenticated)
GET /healthz,GET /api/health→ readiness payload;503when the instance is notready(for example it cannot persist a join),200otherwise.GET /api/version→ the same payload, always200. Exempt from connection-ceiling shedding. See OPERATIONS.md, Readiness.
Admin (all under /api/admin/*; Bearer, or the console session cookie)
POST /api/admin/session {key}with headerX-QM-CSRF: 1→ signs the console in: setsqm_console(HttpOnly,SameSite=Strict,Path=/api/admin, 12 h), a signed session reference that never contains the key; answers{ok, name, role, expiresInSec}.DELETE /api/admin/session(same header) clears it and revokes the session server-side. A request carrying the cookie and noAuthorizationheader must sendX-QM-CSRFon every non-GET, or403 csrf_required; a request withAuthorizationis judged on that alone. See OPERATIONS.md, Two keys, two blast radii.- Grants:
viewerand the monitor token read (rooms, events, metrics, health, security, reports, alerts status, audit; the monitor token is refused audit, visitors and targeting);operatoralso changes queue state and room settings;owner/ADMIN_KEYalso manage operators, delete rooms and shut down. GET /api/admin/operators,POST /api/admin/operators {name, role}→ key returned once;DELETE /api/admin/operators/:idrevokes. No route changes an existing operator's role.GET /api/admin/audit→ who did what, when and from where.GET /api/admin/security→ bot-protection scoring and refusals.GET /api/admin/reports?roomId=&bucket=hour|day→ historical rows (CSV available for BI).GET /api/admin/alerts→ alert state;POST /api/admin/alertsfires a test page (400 alerts_disabledwithoutALERT_WEBHOOK_URL,502 webhook_failedif the webhook refuses).POST /api/admin/shutdown→{ok, stopping, uptimeSec}then a clean stop (the documented way to stop it on Windows).owneronly.POST /api/admin/sse-ticket→ single-use 30 s ticket forGET /api/admin/events?ticket=.GET /api/admin/rooms→ list with live stats{waiting, passedLastMin, rate, state, oldestWaitSec}estWaitSecis the wait for a visitor joining now, and it is only ever a number the room can back. A room admitting nobody (paused,ratePerMinute: 0, or measured outflow of zero) reportsnull(unbounded), whether or not anyone is queued. A room whose doors are still shut reports the time left on the clock plus the drain of anyone already holding a ticket, the same sum/api/statusquotes a waiting visitor, withestWaitFloor: true: the draw decides how much longer than that a pre-queue entry waits, so nothing is added for it.0means the room would admit immediately.POST /api/admin/roomscreate/update room. The writable set is exactly:{id, name, targetUrl, proxyOrigin?, ratePerMinute, maxConcurrent?, passedTtlSec?, sessionTtlSec?, sessionMaxSec?, branding?, returnOrigins?, tagOrigins?, autotune?, protection?, autoActivate?, urlPatterns?, opensAt?, preQueueMaxPerIp?, queueMaxPerIp?, presenceSec?, state?, onBackendDown?, challenge?, firewall?, notifyNear?, maxWaiting?, fullUrl?, closedUrl?, showCodeButton?, stockCheck?}- The nine beyond the obvious ones, because each is a whole feature reachable only through this body:
proxyOriginis inline mode (the internal address this server forwards an admitted visitor to);sessionTtlSec/sessionMaxSecbound a door session;autotuneis the automatic rate controller;protectionis the bot-scoring mode ({mode:"off"|"monitor"|"enforce"});autoActivateis threshold activation;opensAtandpreQueueMaxPerIpare the scheduled drop and its per-identity pre-queue cap;queueMaxPerIpandpresenceSecare the live line's per-address ceiling and presence window (see Core concepts, Ghost tickets);statesets active/paused/bypass in the same write as everything else. onBackendDown("closed", the default, or"open") is what an inline room's gate does while the backend is down (Valkey unreachable, or the room being rebuilt from the journal):closedanswers a browser navigation with the waiting page in retry mode (503+Retry-After, no place taken) and any other request with503 storage_unavailable;openforwards toproxyOriginunqueued. Anything else is400 invalid_on_backend_down. Stored but without effect onSTORE=memory, which has no backend to lose.challenge(null, the default, or{mode:"off"|"turnstile", failOpen?:boolean},failOpendefaulttrue) is the room's optional Turnstile challenge (see Visitor, above). Any other shape is400 invalid_challenge. Switching a room to"turnstile"while the server lacksTURNSTILE_SITE_KEYorTURNSTILE_SECRET_KEYis400 challenge_not_configured, unless the room already has it (so the read shape still posts back). Stored by both stores and replayed with the room.firewall(null, the default, or{mode:"deny"|"allow", ips?:string[], countries?:string[], message?:string|{en?,th?}}) is the room's access rules (see Visitor, above).ipsare IPv4/IPv6 CIDR strings (at most 200),countriesISO 3166-1 alpha-2 codes plusT1for Tor (at most 50;XXandUKare refused); at least one of the two must be non-empty. Stored normalised (host bits cleared, shortest IPv6 form, duplicates and covered ranges dropped, sorted), so the read shape posts back unchanged. Refusals, all400:invalid_firewall(shape or an unknown field),invalid_firewall_mode,invalid_firewall_ip(including0.0.0.0/0and::/0),invalid_firewall_country,invalid_firewall_message,firewall_empty,firewall_too_many_ips,firewall_too_many_countries, andfirewall_countries_need_edge(adding country rules whileEDGE_SECRETis unset, unless the room already has some). A change is its own audit entry,room.firewall. A shared monitor link reads the mode only:ips,countriesandmessagecome back blank. Stored by both stores and replayed with the room.maxWaiting(null, the default = no limit, or a whole number from 1 to 100000000) is the most visitors the room lets wait;fullUrlandclosedUrl(null= the server's own page, or anhttps://URL of at most 2048 characters with no credentials) are the pages a visitor is sent to when the line is full or the room is closed. Any other value is400 invalid_max_waitingor400 invalid_entry_url. Whether the room is closed is not a field here: it is set by its own call and a room write cannot change it. A visitor with no place at a full or closed room is not given one (the firewall is judged first, then closed, then full):POST /api/joinanswers200 {refused:"full"|"closed", url}and writes nothing,GET /api/check(and/api/v1/check) answers200 {action:"queue", reason:"room_full"|"room_closed", waitingRoomUrl}(the same shape as the firewall's, and for a waiting ticket of a closed room too; a visitor holding a pass still passes), andGET /w/<room>answers302to the page for a visitor who holds no ticket.urlandwaitingRoomUrlare absolute: the room'sfullUrlorclosedUrl, else the server's/full/<room>or/closed/<room>.showCodeButton(true, the default, orfalse) shows or hides the waiting page's Have a priority code? button; a?code=link is redeemed either way. Anything but a boolean is400 invalid_show_code_button.stockCheck(null, the default, or{enabled, url, round, roundParam?}) is the shop endpoint a stock check asks.urlishttps://with no credentials, at most 2048 characters, and may have a query string but not one that already hasroundParam;roundandroundParam(defaultround) are 1 to 32 characters ofA-Za-z0-9._-.enabled: trueneeds aurland around; a disabledstockCheckmay keep them empty (nullor absent are stored and read back as''), and every sub-field must be a string. Any other value is400 invalid_stock_check. The URL may carry a token, so a shared monitor link readsstockCheck: null. Stored by both stores and replayed with the room.redacted: trueis refused with400 redacted_shaperather than treated as an unknown field. A room read through a shared monitor link comes back with its internal address, origin allowlists and URL rules blanked, so posting that body straight back would wipe all of them; the error says so instead of naming a field.rateis accepted as an alias forratePerMinute: it is whatGET /api/admin/roomscalls the same field, so a read-edit-write round trip does not have to rename it. Sending both is fine if they agree; sending both with different values is400 conflicting_field. Any field name outside the documented set is400 unknown_field, not a silent no-op. Without that, a typo would look exactly like a successful edit that did nothing.returnOriginsis where a promoted visitor may be sent;tagOriginsis which pages may read a door check (the browser CORS allowlist). The room'stargetUrlorigin is always on both.tagOrigins: null(the default) inheritsreturnOrigins, so a room configured before the split is unchanged. They are separate because they fail in opposite directions: a wrong return policy is an open redirect, while a missing tag origin serves that page completely unqueued in silence.urlPatternsis the room's scope, as runtime config: at most 25 rules, each at most 300 characters and at most 10*wildcards. A rule starts with/(path),*(anywhere) or a fullhttps://host/path(pins the origin); a leading!makes it an exception. Matching is case-insensitive; a rule with no?is matched against the path only. Exceptions always win, whatever order they are listed in, because order-dependent rules are an operator footgun.[]means unscoped: every page carrying the tag is queued.branding.messageis the operator's message to queued visitors; the server stampsbranding.messageAtwhen the text changes, and the waiting page shows it in a timestamped pane in every state, including a scheduled drop's countdown.branding.hide(absent or[]shows everything) lists waiting-page elements to switch off for the room: any ofopensHint(the pre-queue line under the headline; the countdown stays),message(the staff message box; the stored text is kept and not sent while hidden),notify(the "notify me" button) andemail(the e-mail button: it can only hide it, never force it on overEMAIL_NOTIFY, and the e-mail endpoint is unchanged). An unknown name, a duplicate or a non-array is400 invalid_branding. It reaches visitors already waiting on the status frame (hide, the names butmessage, only when non-empty), like the message.branding.copy.thandbranding.copy.enhold the operator's own waiting-page texts:headline(80),description(300),passMessage(200),footer(200) andinside(80 characters, Notion 884), strings only.insideis the whole sentence for the "people inside now" line (peopleInside):{n}is replaced by the number, and a text without{n}gets the number added after a space. Empty or absent keeps the built-in label; Spanish, German and French always use their built-in label.DELETE /api/admin/rooms/:idPOST /api/admin/rooms/:id/state {state}(active/paused/bypass)POST /api/admin/rooms/:id/rate {ratePerMinute}(rateaccepted as an alias, same rule as above): takes effect immediatelyPOST /api/admin/rooms/:id/flush: promote N now{count}POST /api/admin/rooms/:id/schedule {opensAt?, preQueueMaxPerIp?}: set/clear the doors-open instant. Each field is applied only if present: sendingpreQueueMaxPerIpalone adjusts the cap and leaves the drop scheduled. Cancelling a drop takes an explicit{"opensAt": null}. A body with neither field is400 nothing_to_change, not a silent no-op.POST /api/admin/rooms/:id/eject {ticket}: revoke the pass, drop any live session, back of the linePOST /api/admin/rooms/:id/purge: discard the whole waiting backlog without admitting anybody. For a room that has outlived its event: durability keeps its line across every restart, and deleting the room used to be the only way out. No passes are minted and no outflow is recorded, so the chart gains no spike that never happened; purged tickets read asexpired, and the room, its settings and its history are kept. A scheduled room's pre-queue is emptied too. Answers{purged, stats}once the purge is on disk (503 storage_unavailableif it could not be written);purgedcounts pre-queue entries, which are also given aspreQueue.GET /api/admin/rooms/:id/visitors?ticket=or?ref=→ per-visitor lookup for support (state, position, TTLs, session, binding; one-way digests only, never raw identifiers).ref=resolves the short code the waiting page shows the visitor, so the string they read down the phone is the string that goes in the box; an ambiguous code returns the candidate tickets rather than guessing.GET /api/admin/rooms/:id/targeting?url=→ the room's rules with{matchCount, lastMatchedAt}per rule, plus counts of checks that matched nothing and checks that arrived with no URL. Optionalurl=is a dry run: which rule would win, without touching the counters. A rule that has never fired is the visible symptom of a room pointed at the wrong pages. The server's own health probe (User-Agentqueue-manager-healthprobe/…) is judged like any visitor but is not counted.GET|POST /api/admin/rooms/:id/codes,DELETE /api/admin/rooms/:id/codes/:n,POST /api/admin/rooms/:id/codes/:n/reveal,POST /api/admin/rooms/:id/codes/:n/delete(Notion 744, 840): priority codes.POST {label, effect:"skip"|"jump", uses?: 1..100000|"unlimited" (default 1), expiresAt?}answers201 {code, secret, shownOnce:true, link}: the server makes the 12-symbol code, andsecretandlink(/w/<room>?code=…) are the only time it exists in the clear (Cache-Control: no-store); a keyed hash (HMAC-SHA256 under a key derived fromSECRET, over the room id and the code) is stored and journaled, and a code made since Notion 840 is also kept encrypted (AES-256-GCM, a key derived fromSECRETwith HKDF infoqm:code-enc, a random 12-byte IV, the room id and the code's hash as AAD; stored and journaled as base64iv+tag+ciphertextin the record'sec) so the console can copy it again.GETlists{id, label, effect, uses, left, expiresAt, createdAt, createdBy, redeemed, revokedAt, state, copyable}(state: active, expired, exhausted, revoked;copyable: a ciphertext is kept), never the code or the ciphertext.DELETErevokes; it is idempotent.POST .../:n/reveal(empty body) answers200 {id, secret, link}(Cache-Control: no-store), the code and its link in the clear, for an active code that has a ciphertext;409 code_not_copyablefor a code made before Notion 840,409 code_not_activefor a revoked, expired or used-up one,404 code_not_found, and500 code_decrypt_failed(fails closed, nothing returned) whenSECRET(andSECRET_PREVIOUS) cannot open the stored value.POST .../:n/deleteremoves the code record outright (its hash lookup and ciphertext with it; the number is not reused; tickets that already redeemed it keep their place) and answers200 {roomId, id, deleted:true},404 code_not_foundthe second time. Both POSTs need the write grant, like create and revoke (a viewer and a monitor link get403). Owner and operator may create and revoke, a viewer may only list, and a monitor link may not see them at all. A room holds at most 1000 codes. Audited:code.create,code.revoke,code.revealandcode.delete(the number only, never the code), andcode.redeemfor a code's first use, its last and every 25th (the exact count is on the code).GET|POST /api/admin/rooms/:id/stock(Notion 745): the operator's stock.GET→{roomId, stock, soldOut};POST {set: n | null}or{delta: n}(optionalkey, as above) →{roomId, stock, soldOut, previous, applied, clamped?, replayed}. A viewer may read, owner and operator may write, a monitor (share) link may do neither (403, as for visitors and codes) and the stats it reads carrysoldOutbut notstock. Audited:stock.setandstock.adjustwith what it did and what the stock was; the shop's own calls are not audited one by one (a shop calls once per order) but the two edges are,stock.sold_outandstock.restock. A room that has a stock carriesstockandsoldOutin its stats (the room list and the admin stream); a room with no stock carries neither.POST /api/admin/rooms/:id/stock-check(Notion 878): the Test button of the room'sstockCheck. One request to the room's savedstockCheckurl and round (the body is ignored), read-only: no stock, no poller state, no audit, and the URL is never echoed. Any instance answers it.200 {ok, state, stock, soldOut, ms}(ok:true;stateissold_outoravailable;stockis a whole number ornullwhen onlysoldOutwas sent) or200 {ok:false, reason}withreasonone oftimeout,blocked,unreachable,status,not_json,too_large,no_field;400 stock_check_not_configured(no saved url and round),404 room_not_found,429 stock_check_busy(Retry-After: 1: one test per room at a time and at most one a second). Owner and operator may call; a viewer and a monitor (share) link get403. The check itself is run by the fleet leader everySTOCK_CHECK_EVERY_MSand acts only when the shop's answer changes (OPERATIONS.md, Stock check); its metrics areqm_stock_check_total{room,result}andqm_stock_check_enabled{room}, its alertstock_check_failing.POST /api/admin/rooms/:id/closeand/reopen(Notion 816) →{roomId, closed, changed, waiting, cleared}. Idempotent (changed:falsewhen nothing moved, and only a change is audited). Closing ejects nobody and promotes nobody; the status and SSE frame of a waiting or pre-queued ticket then carryclosed:trueand the page's absoluteurl, and a pass is answered as before. Reopen starts a fresh line: it clears every waiting and pre-queued ticket (clearedcounts them) and leaves pass holders alone. Owner and operator may call; a viewer and a monitor (share) link get403. Audited:room.closeandroom.reopen(with the count). Metrics:qm_room_entry_state{room,state}andqm_entry_refused_total{room,reason}. WithCLAIM_COOKIE_DOMAINset, a waiting ticket also sets theqm_w_<room>marker (Domain=<that>; Path=/; HttpOnly; Secure; SameSite=Lax, session length, no place information) that the Worker's shortcut reads.GET /api/admin/events→ SSE stats every 2s for all rooms{rooms:[...], totals, sparkline data}- Delta frames (QM-468). A full frame (no
deltakey) is sent on connect and again on the next tick. After that each tick is{delta:true, rooms:[changed rooms], removed:[ids], totals, …}: only the rooms whose stats changed since the previous tick, plus the ids of rooms that are gone, with the same other keys as a full frame. Changed rooms replace theirs, new ones are appended (server order is creation order), and removed ones are dropped. A tick where rooms changed order is sent as a full frame (QM-480). A client that receives a delta with no full frame under it must reconnect, which is the resync. GET /api/admin/metrics?roomId=&range=→ time series (joins/min, passes/min, queue depth) for chartsGET /api/admin/health→ effective config, storage state, misconfiguration warningsPOST /api/admin/monitor-token→ mints the read-only monitor credential (observe only; neverADMIN_KEY).GETlists live share links (a read, but not open to a monitor token itself);DELETE ?id=revokes one (?all=1every one).GET /metrics→ Prometheus exposition, a read credential required (monitor token,vieweror above; room ids and depths are commercially sensitive)GET /→ admin.html.GET /progress→ PROGRESS.html.GET /docs→ the guides.
Quality bar (what critics judge)
- Waiting page: calm, branded, live position + honest ETA, progress bar, accessible (reduced-motion, aria-live), works on mobile, survives refresh/tab-close, auto-redirects on pass, no layout jank, offline/reconnect handling.
- Dashboard: live queue depth graphs, per-room controls that apply instantly, surge visible at a glance, keyboard accessible, dark UI acceptable, no fake data.
- Engine: 10k joins burst must not crash or reorder; FIFO invariant; rate change mid-surge honored; restart mid-surge loses nothing (
STORE=valkey). - Everything: no console errors, no dead buttons, no lorem ipsum.