Repository navigation
Releases
v0.2.28
-
Breaking: a key repeated in a query string or urlencoded body is now
an array (?tag=a&tag=b→{ tag: [ "a", "b" ] }), as in Express 5.
Before, the last value silently replaced the others, which lost data
from multi-select forms and filter UIs. A handler that treats
req.query.xor a form field as a string will throw if a client
repeats the key — declare the field withboxExpressValidate()or
checkisArray().- Both parsers now share
models/QueryString.bx, with the semantics of
Node'squerystring(Express 5's default "simple" parser). A key
that appears once is still a string. Brackets are not parsed:
tag[]anduser[name]stay literal keys. There is noquery parsersetting. - Keys that differ only in case are one key, because a BoxLang struct's
keys are case-insensitive:?Tag=a&tag=bis{ Tag: [ "a", "b" ] }.
Express would give two keys. - Unchanged:
+is a space in both; a malformed%escape is kept as
raw text in a query string and answered with400in a body. app.inject( { query: { tag: [ "a", "b" ] } } )already sent both
values; the handler now receives both.boxExpressUpload()does the same for a repeated non-file field
in a multipart body (models/middleware/Multipart.bx); it also kept
only the last value.boxExpressCsrf()ignores a token field sent more than once and
falls back to the header, so such a request is rejected as before.
- Both parsers now share
-
boxExpressValidate()and arrays (models/middleware/Validate.bx):type: "array"accepts a single simple value as a one-item array, so
?tag=aand?tag=a&tag=bboth validate. This also applies to
JSON bodies:"tags": "a"is now accepted as[ "a" ], where it was
a400.- An untyped field with
oneOf,pattern,minLengthor
maxLengthnow rejects an array or object ("must be a single
value"). Those rules were skipped for a non-simple value, so
{ "role": [ "root" ] }passed aoneOfcheck — and with repeated
keys,?role=root&role=xwould have too. - Scalar types already rejected arrays; that's unchanged.
-
ETags for buffered responses (
models/Response.bx,
models/ConditionalGet.bx):app.set( "etag", "weak" | "strong" | true | false | ( bodyBytes, encoding ) => tag ). Off by default —
Express turns weak tags on, but a new header and a SHA-1 pass per
response shouldn't arrive with an upgrade. An invalid value throws at
app.set(). The weak format is theetagpackage's
(W/"<length in hex>-<27 characters of base64 SHA-1>"). A response is
tagged only forGET/HEAD, a 2xx status, a non-empty body and no
ETagset by the handler. -
req.fresh/req.stale(models/Request.bx), with thefresh
package's rules as in Express 5:If-None-Match(*, a list, weak
comparison) decides when present, otherwiseIf-Modified-Since
againstLast-Modified;Cache-Control: no-cacheon the request is
always stale. They are read like properties and computed on each read. -
Buffered
GET/HEADresponses now answer304when the request is
fresh, with no body and withoutContent-TypeorContent-Length;
res.getBytesWritten()reports0. This applies withetagoff
too: a handler that already sets its ownETagorLast-Modified
beforeres.send()/res.json()will start answering matching
conditional requests with304, as Express does.sendFile(),
static files andres.sse()are unchanged.sendFile()and static files now send the file in full when the
request saysCache-Control: no-cache(a hard reload), matching
the rule above; they answered304before.- The exchange adapters gained
removeHeader(). A hand-written
exchange adapter needs one. Request.bxis now declared withaccessors=true invokeImplicitAccessor=truesoreq.freshcan be computed when
read;reqgainsgetFresh()/getStale()and unused generated
setFresh()/setStale()methods.
-
Fix:
app.inject()threw "Count cannot be zero" for a URL that is
only a query string ("?page=2") (models/BoxExpress.bx).
v0.2.27
- Request helpers (
models/Request.bx, newmodels/Negotiator.bx):
the parts of Express'sreqthat a ported handler reaches for first
and had to be hand-rolled fromreq.headersuntil now.req.accepts()andreq.acceptsLanguages()pick from the types or
languages you offer by the client'sqweights, returningfalse
when none is acceptable.req.is()matches the request's own
Content-Type, including wildcards,+json-style suffixes and the
urlencoded/multipartshorthands. The rules follow the npm
negotiatorandtype-ispackages, minus media-type parameters
other thanq.req.is()returnsfalse, notnull, for a request
with no body.req.xhr, andreq.subdomainswithapp.set( "subdomain offset", n ).req.baseUrl(models/Router.bx): the mount path of the router or
path-scoped middleware handling the request. A mounted router had no
way to learn where it was mounted, so it couldn't build a link to
itself without the prefix hard-coded.- No
req.fresh/req.staleyet — they only mean something once
res.send()/res.json()set anETag, which they don't.
- Response helpers (
models/Response.bx):res.clearCookie(), plusdomainandexpiresoptions on
res.cookie()— withoutdomaina cookie scoped to a parent domain
could be neither set nor cleared.res.vary()adds toVaryinstead of replacing it.
boxExpressCors()now uses it, so itsVary: Originno longer
overwrites aVaryset earlier in the chain. A hand-written fake
respassed to the CORS middleware in a unit test needs avary()
method.res.format()dispatches onAccept, setsContent-Typeand
Vary: Accept, and answers406when nothing matches. Pass an
ordered struct ([ ... ]): a plain{ ... }has no key order to
fall back on when the client has no preference.res.get(),res.append(),res.location(),res.links(),
res.attachment(),res.set( { ... } )for several headers at once,
and an extension shorthand forres.type( "json" ).res.append()
joins values into one comma-separated line (a line each for
Set-Cookie) sores.get()still returns the whole value.
- Timeouts and size limits (
models/BoxExpress.bx,
models/HttpBridge.bx, newmodels/RequestWatchdog.bx; see
docs/limits.md). Until now the only bounds on a
request were the body parsers' own limits and the accept backlog.app.set( "requestTimeoutMs", n )answers503when a handler
hasn't started its response in time;req.setTimeout( ms )changes
or removes it for one request. Off by default. The handler's thread
is interrupted and sends the503itself — the watchdog never writes
to the response, because Undertow's exchange isn't safe to write from
a second thread while the handler may be using it. The trade-off is
that a handler which never blocks isn't stopped. Error-handling
middleware doesn't run for a timeout; a handler that catches the
interruption can checkreq.timedOut. A response that has already
started (SSE, a file download) is never cut off.app.set( "maxBodySize", bytes )answers413before any handler
runs, onContent-Lengthalone when there is one. Off by default, so
upgrading can't start rejecting uploads. This is enforced in
BoxExpress rather than with Undertow'sMAX_ENTITY_SIZE, which was
tried first: it answered an oversized request with a500, or
dropped the connection with no response for a chunked one, and
printed a stack trace either way. A chunked body is read into memory
up to the cap to measure it.headerTimeoutMsdefaults to 60 s. Before, a client that never
finished sending its headers was held open indefinitely (measured
against 0.2.26: still open after 75 s).maxHeaderSizedefaults to 64 KB, down from Undertow's 1 MB; a
request over it gets a400. Raise it if you send unusually large
headers.keepAliveTimeoutMsmakes the idle keep-alive timeout configurable.
Its default, 60 s, is what Undertow already did.
- Text and raw body parsers (
models/middleware/BodyParsers.bx, new
bifs/boxExpressText.bx,bifs/boxExpressRaw.bx; see
docs/middleware.md):boxExpressText()puts atext/plainbody onreq.bodyas a
string, decoded with the charset the request names (415for one the
JVM can't decode).boxExpressRaw()puts an
application/octet-streambody there as the exact bytes.- All four parsers take a
typeoption — the same patterns as
req.is(), an array, or a function — soboxExpressJSON( { type: [ "json", "+json" ] } )parsesapplication/vnd.api+json. With no
type,json()andurlencoded()match exactly as before. - All four take a
verify( req, res, bodyBytes )option, called with
the bytes as received before they're parsed; throwing answers403.
This is what a webhook signature check needs: the signature covers
the sender's exact bytes, which re-serializing parsed JSON doesn't
reproduce, and before this the only way to see them was to skip the
parser and readreq.bodyStream()by hand. - A parser now skips a request an earlier parser, or
boxExpressUpload(), already handled. The body stream can only be
read once, so a second parser was reading nothing — harmless while
no two parsers could match the same request, but a catch-all
type: "*/*"would have replaced a parsedreq.bodywith an empty
one.
- Signed cookies (new
models/CookieSigner.bx,models/Request.bx,
models/Response.bx):app.set( "cookie secret", secret ), then
res.cookie( name, value, { signed: true } )andreq.signedCookies.
A cookie that fails verification reads asfalseand, like every
signed cookie, is removed fromreq.cookies, so a forged value can't
be read as a plain one. An array of secrets signs with the first and
verifies with all, for rotation. The format iscookie-parser's, byte
for byte (checked against Node's own HMAC output), so an Express app
with the same secret reads these cookies and vice versa. Noj:JSON
cookies. Setting a secret changes nothing for an app that doesn't sign:
only values startings:are affected. - View layouts and partials (
models/Response.bx; see
docs/views.md):app.set( "view layout", name )wraps
everyres.render()in a layout view, which gets the rendered view as
data.body. The view runs first, so it can set a title or anything
else ondatafor the layout to read.layoutin the render data (or
res.locals) picks another layout for one render, orfalsefor none.
partial( view, data )renders another view inline, with the caller's
data plus its own. Until now every view had to include its own header
and footer.layoutis now a reserved key in render data. - Access log (
models/HttpBridge.bx, newmodels/AccessLog.bx; see
docs/observability.md):app.set( "log", "access" )or"json"logs each request when it's answered, with
status, duration and bytes sent; a function receives the entry instead.
The default (true) is unchanged — a line on arrival — which can't
say how a request went, and getting status and duration meant writing
logging middleware aroundres.getStatusCode(). The logged path
leaves out the query string. An invalid"log"value now throws at
app.set(). The timeout log line no longer prints the query string
either. - Binary WebSocket sends (
models/WebSocketConnection.bx):
connection.sendBinary( bytes ), andconnection.send()sends a
binary frame when handed abyte[]. A connection could receive binary
messages (onBinary()) but only ever answer in text. - Cron schedules (new
models/CronExpression.bx,
models/Scheduler.bx; see docs/scheduler.md):
app.schedule( "0 2 * * *", callback )runs a job at clock times.
Five fields or six with seconds, ranges, lists, steps, month and
weekday names,@daily-style shorthands, andoptions.timezone. An
interval can't say "every night at 2" — the first run lands wherever
the process happened to start. Cron parsing was left out of the first
scheduler on purpose as a separable feature; this is it. A cron job is
driven by a one-shot timer re-armed after each run, since the gap
between fire times isn't constant. A malformed expression, or one that
can never fire, throws atschedule(). - Middleware for WebSocket upgrades (
models/BoxExpress.bx, new
models/adapters/WsUpgradeMiddleware.bx; see
docs/websockets.md):app.ws( path, handler, { use: [ ... ] } )runs ordinary middleware against the upgrade
request. The socket opens only if they all callnext(); one that
responds refuses the upgrade. The handler receives the request as a
second argument and asconnection.req. Authenticating a socket used
to mean re-reading the session cookie fromconnection.cookiesand
looking the session up by hand. Opt-in per route rather than running
theapp.use()chain, which would let an app's catch-all 404 handler
answer every upgrade. - Path patterns (
models/Router.bx; see
docs/routing.md): a param can carry a regex
constraint (/users/:id(\d+)), share a segment with literal text or
other params (/flights/:from-:to,/api/v:version,
/files/:name(.+).json), and a trailing*namecaptures the rest of
the path. A route that needed a numeric id had to accept anything and
reject it in the handler. A segment that is only:nameis parsed as
before, so/:user-idis still one param. A literal colon inside a
path segment (/time/12:30) is now read as the start of a param, and
a segmen...
v0.2.26
- Session ids (
models/middleware/Session.bx,
models/stores/CacheStore.bx): the session cookie's value went to the
store as-is, so with a cache-backed store a client could name any entry
in that cache as its session — another feature's data, or the rate
limiter's own counter, which the session save then wrote back stale
(a limit of 3 let 10 of 10 requests through). Only values shaped like a
generated id are looked up now, andCacheStorekeys are prefixed
boxexpress-session-. Upgrading signs out existing cache-backed
sessions once, since their entries are under the old, unprefixed keys. - Malformed
%escapes (models/Request.bx,
models/WebSocketConnection.bx,models/middleware/BodyParsers.bx): a
cookie such asdiscount=50%failed every request carrying it with a
500. Cookie and query values that won't decode are kept as raw text; a
urlencoded body that won't decode gets a 400. - Request log (
models/HttpBridge.bx): control characters in the
logged path and client address are printed as?— the decoded path
could carry a newline or a terminal escape sequence and forge log lines. - Rate limiter (
models/middleware/RateLimit.bx): the in-memory
counter is updated atomically; concurrent requests could read the same
count and run a few over the limit. - SSE (
models/SseEmitter.bx):send()splits data on CR and CRLF as
well as LF, so a bare CR can't start a new field, and blank lines inside
the data are no longer dropped. - Uploads (
models/middleware/Multipart.bx):nameis no longer read
out offilename="..."when a client sendsfilenamefirst, and a part
with nonamegets a 400 instead of a 500. - STOMP (
models/middleware/Stomp.bx,models/StompFrameCodec.bx):- Destinations, subscription ids, exchange bindings, topic patterns and
listeners match case-sensitively./ADMIN/feedand/admin/feedwere
one subscriber set, so anauthorize()that compared case-sensitively
could be sidestepped. Apps that relied on case-insensitive
destinations need to normalize them. sendToUser()compares logins exactly;alicealso reachedALICE,
and7reached007.- Line breaks are dropped from headers sent to STOMP 1.0 subscribers
(1.0 has no escapes), CR from 1.1 headers, and NUL from all of them.
- Destinations, subscription ids, exchange bindings, topic patterns and
- Static files (
models/middleware/StaticFiles.bx): a path holding a
NUL falls through to the next handler instead of a 500.
v0.2.25
- Lazy init vs. teardown (
models/BoxExpress.bx):close()and the
reload supervisor nulled theSchedulerandClusterManagerwithout
the lazy-init lock, so a concurrentschedule()could hit a null or
build a replacement nothing ever shut down (its non-daemon tick thread
kept the JVM alive). Teardown now detaches both under the lock, and
schedule()/getClusterManager()afterclose()throw
BoxExpress.AppClosed.getScheduledJobs()andmetrics()read them
under the lock too. - Clustered job ticks (
models/Scheduler.bx): the election check
ran outside any try, so aClusterManagerthat failed to build
cancelled the job's future ticks with nothing logged; it's now caught
and the tick skipped. The tick no longer blocks on another thread
building theClusterManager, and a clusteredschedule()builds it
up front so config errors throw at the call. - Cluster election (
models/cluster/ClusterManager.bx):- A manager whose own heartbeat is stale (older than half of
peerIdleTimeoutSeconds) steps down and stops renewing its claim,
so it can't keep acting as manager, or overwrite a successor's
claim, after its peers have elected someone else. - Only a live election candidate keeps the role; a holder that
restarted without clustered jobs left clustered jobs running nowhere
until the claim expired. - Heartbeats carry a millisecond timestamp. Whole-second comparison
expired live peers on scheduling jitter at a 1s idle timeout.
Entries from older nodes are still read. The heartbeat interval floor
is now 250ms, andpeerIdleTimeoutSecondsunder 1 is rejected. - The manager no longer rewrites its claim on every election check;
the heartbeat renewal covers it. getPeerPresence()and the relay connection mesh are keyed
case-sensitively, so peers whose names differ only by case no longer
collide.- A cache read that lands mid-write (FileSystemStore rewrites files in
place) is retried before a peer is treated as gone, and an election
check that still can't read every peer counts as not-manager for that
round instead of electing from a partial view.
- A manager whose own heartbeat is stale (older than half of
v0.2.24
- Scheduler fixes (
models/Scheduler.bx):- A run the stall watchdog gave up on could, when it finally returned,
mark the job idle while its replacement was still running, so the
next tick started a third run alongside it — the overlap guard was
off for as long as that lasted. Each run now owns the job by id and
only the current owner can release it. - A job that cancelled itself during its first
immediate: truerun
could beatschedule()to storing the timer's future;cancel()
then failed, was logged as a job failure, and the job kept running.
Cancellation now works whichever side gets there first. intervalMsis validated: anything but a whole number of
milliseconds, 1 or more, throwsBoxExpress.InvalidArgument. Before,
the JDK rejected it only after the job was registered, leaving a
dead job ingetScheduledJobs()and metrics.- Job ids come from an atomic counter. Two concurrent
schedule()
calls could get the same id, and the second overwrote the first,
leaving its timer ticking with no way to cancel it. - Two concurrent first calls to
app.schedule()could each create a
Scheduler, and jobs registered on the one that lost were never
reachable bygetScheduledJobs(), metrics orclose(). The lazy
creation (andapp.getClusterManager()'s) is now locked. - New
options.stallThresholdMsoverrides the stall threshold. running(ingetScheduledJobs()and the
boxexpress_scheduler_job_runningmetric) counts runs actually in
flight.
- A run the stall watchdog gave up on could, when it finally returned,
- Cluster manager election (
models/cluster/ClusterManager.bx): the
manager claim was only written when no live manager was found and never
renewed, so it expired everypeerIdleTimeoutSeconds * 3and went to
whichever instance checked next, and two instances checking at once
could both claim it and both run a clustered job. Now a live manager
keeps the role and renews its claim on each check and heartbeat, and
with no live manager every instance picks the same winner — the
lowest-named live election candidate — and only it writes the claim.
Only instances that have checked (ones with clustered jobs) are
candidates. See "How the manager is elected" indocs/cluster.md. - Heartbeat interval is a third of
peerIdleTimeoutSecondswith a 1s
minimum, down from a 5s minimum that made any idle timeout under 15s
expire live peers between heartbeats.
v0.2.23
- Dependencies: bumped the vendored
libs/undertow-core-*.jarfrom
2.4.3.Final to 2.4.4.Final, andwildfly-commonfrom 1.5.4.Final to
2.0.1, the version Undertow 2.4.4 is built against. wildfly-common 2.x
needssmallrye-common-expression,-net,-osand-ref, now
vendored at 2.14.0 alongside the existing smallrye-common jars. The
WebSocket shim is rebuilt against the new Undertow.