# Marmeon > Marmeon is a full-stack framework for TypeScript on Node.js: an app is a set of modules whose routes, controllers and React pages are typed from end to end, and the server renders each page before the browser takes over. The documentation of Marmeon 1.3.0, each page as Markdown in the order of https://marmeon.com/docs. Every page in one file: https://marmeon.com/llms-full.txt --- # Why Marmeon ## Introduction Marmeon is built by [BespokeCode](https://bespokecode.de), a software company in Munich that builds tailor-made web applications for its clients. This page explains why BespokeCode made a framework, what it stands for, and why it is open source. ## Where it comes from Project after project needed the same foundation: sign-in, sessions, validation, mail, queues, scheduled tasks, translations, security headers and CSRF protection. We assembled it each time from separate libraries, and each library had its own conventions. The types broke at the seams between them, and every project made the same security decisions again. Marmeon is that foundation, built once, in one place. It is the one we want to build our clients' applications on. ## What it stands for These are the principles every part of the framework follows, and each links to the page that shows it: - **Typed end to end.** Types run from the database column through the controller, validation and route names to the form error in the React component. See [routing](https://marmeon.com/docs/routing.md), [validation](https://marmeon.com/docs/validation.md) and [forms](https://marmeon.com/docs/forms.md). - **No global state.** There are no singletons holding request data: one application, and a scope per request or job. See the [container](https://marmeon.com/docs/container.md) and the [request lifecycle](https://marmeon.com/docs/lifecycle.md). - **TypeScript runs natively on Node.** There is no transpile step and there are no decorators: constructor injection works from generated lists. See [installation](https://marmeon.com/docs/installation.md) and the [container](https://marmeon.com/docs/container.md). - **Modules first.** A module brings its routes, providers, migrations, views and tests, and installed packages register themselves. See [modules](https://marmeon.com/docs/modules.md). - **One endpoint, one class.** Controllers, jobs, listeners, commands, mails and policies are classes with `handle()`. See [controllers](https://marmeon.com/docs/controllers.md). - **Batteries included, behind contracts.** Services that talk to the outside world have several drivers, and mail, the queue, notifications, storage, events, live updates and the schedule have a fake for tests. See [packages](https://marmeon.com/docs/packages.md) and [fakes](https://marmeon.com/docs/fakes.md). - **Secure by default.** Protections fail closed outside development, page data never lands in the browser's storage, and signed-in pages are never cached. See the [security overview](https://marmeon.com/docs/security.md). ## Why it is open source Marmeon is free software under the MIT licence. A foundation gets better and safer when more people build on it and report what breaks. If you find a bug, a gap in the docs or a security problem, we want to hear about it. The [contribution guide](https://marmeon.com/docs/contributing.md) explains how, and the [security policy](https://marmeon.com/docs/security-policy.md) says how to report a vulnerability. ## Who is behind it BespokeCode builds Marmeon and keeps it up to date. If you want an application built on Marmeon, or help with your own, [BespokeCode](https://bespokecode.de) can do that. --- # Upgrading This page lists every change between one version and the next that an app has to act on: how likely it is to affect your app, what to do, and the way back where there is one. The [release policy](https://marmeon.com/docs/releases.md#what-a-version-promises) says what a version promises. ## Upgrading to 1.3.0 from 1.2.3 ### Security hardening #### Low: A table refuses a NUL character or half of a surrogate pair in its search, filters and row keys *Likelihood of impact: low — apps with data tables whose search, filter values or row keys can carry such text, and tests that send it.* A table now refuses text with a NUL character or half of a surrogate pair (a lone `\ud83d`) before it asks the database. A search or a select or has filter value in the URL, in the state of "all matching", in an export or in a form post answers 400, and the message names the key, never the value. A text row key in a row action answers 422, and one such key in a bulk action refuses the whole request with 422. In 1.2.3 Postgres answered 500, and SQLite answered 200 and searched with the value. Text with accents or emoji is unaffected. Nothing changes in code. There is no way back. See [the URL is strict](https://marmeon.com/docs/tables.md#the-url-is-strict) and [bulk actions](https://marmeon.com/docs/tables.md#bulk-actions). #### Low: An upload name with a NUL character is refused and a long one is cut by code points *Likelihood of impact: low — apps with uploads whose clients send a file name with a NUL character, or a long name of characters outside the Basic Multilingual Plane.* A request that announces an upload under a file name with a NUL character now answers 400 and leaves no row. Postgres answered 500, and SQLite stored the name. A name longer than 255 is cut at 255 code points, where 1.2.3 cut it at 255 UTF-16 units: a name of emoji keeps up to 255 of them instead of about 127, and a character is never split. A lone half of a surrogate pair is still accepted and stored as U+FFFD. The name is only shown, never used as a path or a key, and its column stays `varchar(255)`. There is no way back. See [uploads](https://marmeon.com/docs/storage.md#uploads). #### Low: cookies.set() refuses a value with half of a surrogate pair and options a browser would ignore *Likelihood of impact: low — code that sets a cookie from text it does not check, or with a `path`, `domain`, `sameSite`, `maxAge` or `expires` built at run time.* `cookies.set()` now throws a `TypeError` that names the cookie when the value has half of a surrogate pair, encrypted or not, and when the value is not a string. It throws for a `path` or `domain` with `;`, a control character or a character above U+00FF, for a `sameSite` other than `lax`, `strict` or `none`, for a `maxAge` that is not a span of time and for an `expires` that is not a valid date. `delete()` refuses the same `path` and `domain`. Before, an unencrypted value failed with a `URIError` when the response was written, an encrypted one stored U+FFFD in place of the value, and an invalid `expires` was written as `Expires=Invalid Date`, so the cookie lasted only for the browser session. The error is now thrown inside the request, where the error page renders it, and `set()` keeps the options as they were when you called it. Check text with `wellFormed()` before you store it, and correct the option. There is no way back. See [cookies](https://marmeon.com/docs/requests.md#cookies) and [lone surrogates](https://marmeon.com/docs/validation.md#lone-surrogates). #### Low: password() refuses a NUL character and a password of more than 4096 characters as typed *Likelihood of impact: low — forms that use the `password()` rule on fields whose other rules let a NUL character through, and passwords of more than 4096 characters.* `password()` now refuses a value with a NUL character with the message "Enter a password." that a missing value gets. It also refuses a value of more than 4096 characters as typed, also one that fits 4096 bytes after NFKC. The starter's sign-in forms refuse both already, so an account could be given a password that it could never sign in with. Stored passwords keep verifying: the hasher itself still accepts a NUL character. There is no way back. See [the password rule](https://marmeon.com/docs/hashing.md#the-password-rule). #### Low: json() and view() throw for a status outside 200 to 599 *Likelihood of impact: low — routes that pass a status of their own that is not a whole number from 200 to 599, or 204, 205 or 304 with a body, and `abort()` with such a status.* `this.json(data, { status })` and `this.view(…, { status })` now throw a `TypeError` for a status that is not a whole number from 200 to 599, and for 204, 205 or 304 with data. The request fails inside the route, and the error page answers 500. Under `startServer()`, a status of 0 or a fraction answered 200, and 600 to 999 went out as sent. `abort()` with a status outside 200 to 599 is answered and reported as a 500, without its message or headers. `abort(204)`, `abort(205)` and `abort(304)` still answer that status, now without a body. Pass a status in the range. There is no way back. See [responses](https://marmeon.com/docs/responses.md#json). ### Database and migrations #### Low: A migration that drops a name Postgres would cut stops with D5, and names are judged by the database *Likelihood of impact: low — Postgres apps with a migration that gives, drops or indexes an index, constraint, table or column name of about 63 bytes or more, or a database whose encoding is not UTF-8.* On Postgres, a migration's index, check and foreign-key names are now judged by the database itself, in its own encoding: a LATIN1 database keeps names that a count of UTF-8 bytes refused, and an EUC_JP database refuses names it would cut. A run with such a name stops with D5 before its first migration, and a rollback before the first `down()`. A migration that drops a table, column or index by a name that Postgres would cut at 63 bytes (`drop()`, `dropIfExists()`, `dropColumn()`, `dropIndex()`, `dropUnique()`) stops with D5 too, as does a foreign key to such a table or column, and the columns an index covers or filters on with `where`, in an `up()` and a `down()`. Before, such a drop acted without a word on whatever the first 63 bytes name. `rename()`, `renameColumn()`, `dropCheck()`, `alter()`, `notNull()` and `nullable()` with such a name already ended in D19 in an `up()`; in a `down()` they now end in D5 (`oneOf()` of such a column still ends in D19). A step may use a long name that an earlier step of the same migration gave. A name an earlier migration gave is not exempt: use the name as Postgres stored it. On every driver, a schema step on the migrator's record table spelled `public.migrations.x` now ends in D4. A migration that already ran stays recorded. Nothing changes on SQLite and MySQL. There is no way back. See [D5](https://marmeon.com/docs/errors.md#server-error-codes) and [indexes](https://marmeon.com/docs/migrations.md#indexes). #### Low: schema.create() and schema.rename() refuse a table name with a dot in an up() *Likelihood of impact: low — migrations that create or rename a table to a name such as `audit.items`.* A table created or renamed with a dot in its name has always ended in D3 after its statement, because the migrations follow a table by its bare name, so no applied migration can contain one. It now stops in `up()` with the new code D31 before any statement runs. On MySQL this also stops a table that would have stayed in another database. `drop()` and `dropIfExists()` accept a dotted name as before, a `down()` still accepts one, and the name of a table can no longer be changed in a `create()` or `alter()` callback after it was checked. Use a name without a dot, or `schema.raw()` for a table of another database. There is no way back. See [D31](https://marmeon.com/docs/errors.md#server-error-codes) and [what the migrations describe](https://marmeon.com/docs/migrations.md#what-the-migrations-describe). #### Low: A new migration is stamped behind the migrations of every module *Likelihood of impact: low — apps that generate migrations with `make:migration`, `make:resource` or a package's generator, and have a migration of a module with a stamp ahead of today.* `make:migration`, `make:resource` and the generators of packages now stamp a new migration behind the newest migration of every module, not only its own: the later of now and that stamp plus one second. A migration that adds a column to the table of another module therefore runs after it. A migration of a module whose stamp lies in the future is no longer overtaken by the next file you generate. A newest stamp that is no date or leaves no room is printed as a warning, and the file is stamped behind its own module's migrations. Nothing you committed changes, and there is no workaround to remove. See [migrations](https://marmeon.com/docs/migrations.md#generating-migrations). #### Low: A statement that reaches a transaction after its commit or rollback is refused *Likelihood of impact: low — code that starts a query in `connections.transaction()` without awaiting it and relies on it running after the transaction ended.* A statement that you start inside `connections.transaction()` and do not await could run after the rollback, in autocommit on the bare connection, and survive. It is now refused. A statement of the transaction that is sent after its commit or rollback started, work that begins while the end statement runs, and a nested `transaction()` that starts after its savepoint ended all throw `TransactionFinishedError` and are never sent. While the end statement runs, every other statement on that connection is refused too. A connection you reserve with `db.connection()` keeps working afterwards. Await every statement inside the callback, or wrap work that should run on its own in `outsideTransaction()`. A `trx` that you use outside the callback's call chain, and Kysely's own transactions, rely on Kysely's checks: await each statement there too. There is no way back. See [await everything](https://marmeon.com/docs/transactions.md#await-everything). #### Low: An aborted commit and a transaction left open end in D24 *Likelihood of impact: low — apps with a `db.transaction()` or `db.startTransaction()` that is not closed (any database), a Kysely `AbortedTransactionError` thrown out of a nested `db.transaction()` callback, or, on Postgres, a statement that fails after its callback returned.* Kysely 0.29.9 stops rolling back a transaction whose callback throws its `AbortedTransactionError`, and the database package now holds the line at every boundary. On Postgres, a commit that the server answers with a rollback becomes a `TransactionError` (D24), and so does the release of a savepoint that failed. A statement that you started inside a callback without `await` and that fails after the callback returned now surfaces as D24 instead of a silent commit. On every database, when a `transaction()` ends with a `db.transaction()` or `db.startTransaction()` that it did not close, it rolls that one back and rejects with D24. On every database, a connection released with its transaction still open is rolled back, a `MarmeonDatabaseWarning` with the code `MARMEON_TRANSACTION_LEFT_OPEN` names the connection, and the release rejects with D24. After a failed `commit()` of `startTransaction()`, call `rollback()` in `catch`. Wrap an `AbortedTransactionError` that leaves a nested `db.transaction()` callback (`new Error(message, { cause })`), or open the nested transaction with `connections.transaction()`. There is no way back. See [nested transactions](https://marmeon.com/docs/transactions.md#nested-transactions) and [transactions you control yourself](https://marmeon.com/docs/transactions.md#transactions-you-control-yourself). ### Queues and the scheduler #### Low: A job key that names the lock of another job is refused, and queue:work warns at its start *Likelihood of impact: low — apps with job names such as `reports` and `reports:daily`, and a unique or `withoutOverlapping()` key of the shorter job that continues with the rest of the longer name and a colon (`daily:7`).* A unique lock and the lock of `withoutOverlapping()` are named by the job's name and the key, and job names may contain a colon: `reports` with the key `daily:7` and `reports:daily` with the key `7` took one lock. The queue now refuses such a key. A unique key throws a `QueueError` at dispatch on every driver. A `withoutOverlapping()` key without `shared` fails the job at once, without retrying; on the `sync` connection the dispatch throws. The message names the two jobs and never the key. A job named `:schedule` makes `s.job()` of the job `` fail with a `ScheduleError` that names the task, because the key of a scheduled job starts with `schedule:`. `queue:work` also warns once at its start for every pair of registered names where one is the other followed by a colon, and never stops. Build the key so it does not start with the rest of the longer name and a colon, or rename one of the jobs: keep the old name registered until its waiting jobs are gone. Lock names and stored records do not change. There is no way back. See [unique jobs](https://marmeon.com/docs/queues.md#unique-jobs). #### Low: Queue log lines name a dispatched job apart from the running one *Likelihood of impact: low — log searches, alerts and tests that read `job` or `jobId` on the "Not queued" line or on the warning of a failing `JobQueued` listener.* A queue log line about a job that is dispatched but is not the one running now carries that job as `dispatched`, and `dispatchedId` where the line has an id, so `job`, `jobId` and `attempt` always describe the running job. This holds for the "Not queued" line of a unique duplicate and for the warning of a failing `JobQueued` listener, also when the worker hands on to the next job of a chain. A failing listener of `JobProcessing`, `JobProcessed` or `JobFailed` on the `sync` connection binds its own job, id and `attempt: 1`. A busy `job.once()` on `sync` rejects with a message that no longer promises a retry, because `sync` never retries. Change the searches and alerts that read the old fields. There is no way back. See [the log context](https://marmeon.com/docs/logging.md#the-log-context). #### Low: schedule:work waits for a run that hangs at the stop, and --stop-timeout has an upper bound *Likelihood of impact: low — schedulers whose runs can hang when the process is stopped, and a `--stop-timeout` above 2073600.* Stopped while a run hangs and holds no handle, `schedule:work` ended the process with exit code 13 at once and skipped its warning, the release of `withoutOverlapping()` locks and the shutdown of the providers. It now waits up to `--stop-timeout`, warns, frees the locks and exits 0. A `--stop-timeout` above 2073600 seconds (24 days) is refused at start with exit code 2: Node fires a longer timer after a millisecond, so such a value cut the runs off at once. Lower the value. There is no way back. See [scheduling](https://marmeon.com/docs/scheduling.md#several-servers-and-long-runs). ### Pages, files and commands #### Low: claimedBy() in a command answers as in a request *Likelihood of impact: low — commands, such as a publish or a rebuild, that refuse data with `router.claimedBy()`.* `router.claimedBy()` answered differently outside a request: only the HTTP kernel told the router the app's locales and health paths, so in a command every first segment counted as a locale and `/up` as the health check, wherever `SERVER_HEALTH_PATH` had moved it. A localized home page then took every path of one segment, and a command refused `/about` that the same save over HTTP accepted. `@marmeon/i18n` and `@marmeon/server` now tell the router while the app boots, so a command gets the answer of a request: a command that refused a free path accepts it, and `/up` is free where `SERVER_HEALTH_PATH` moved it. Ask after the app started, not from another provider's `boot()`. Without those packages the answer stays cautious. See [asking whether a path is taken](https://marmeon.com/docs/routing.md#asking-whether-a-path-is-taken). #### Low: A route pattern that can be empty matches the path / *Likelihood of impact: low — apps with a route such as `/:page?` or `/:path*`, whose commands ask `router.claimedBy('/')`, and sitemaps and alternates built from them.* The router's pattern matching now lets a pattern whose parameters are all optional or a rest (`/:page?`, `/:path*`) match `/`, as the server already answers it. `router.claimedBy('/')` now reports the route, so a command that checks `/` is stricter than before. A sitemap entry or a `PageAlternates` path that resolves to `/` for such a route is accepted instead of refused. A pattern with a required part (`/:page`, `/a/:b?`) still does not match `/`. Nothing changes in code. There is no way back. See [asking whether a path is taken](https://marmeon.com/docs/routing.md#asking-whether-a-path-is-taken). #### Low: The storage routes answer Range requests with 206 and 416 *Likelihood of impact: low — apps with a global middleware or a proxy that tests for status 200, counts downloads or throttles bytes on files under `/storage` or on temporary links, and signed links whose expiry is shorter than the playback.* The built-in storage routes, which serve the public local and memory disks under `/storage` and the signed temporary route, now answer a GET with one `bytes` range with `206 Partial Content` and a `Content-Range`. A range that starts at or after the end of the file, or `bytes=-0`, gets `416` with no body. Any other `Range` header gets the whole file. With `If-Match` or `If-Unmodified-Since` that fails, the answer is `412`. A file that supports ranges says `Accept-Ranges: bytes`, also on `200`, `304` and `HEAD`. A signed link is checked on every range request, so its expiry has to cover playback. Let your middleware and proxy accept 206 and 416, and count a download once. `serveFile()` changes nothing without `ranges: true`. See [ranges and video](https://marmeon.com/docs/storage.md#ranges-and-video). #### Low: tinker finds its helpers by their package and refuses --sandbox beside a second copy of the database package *Likelihood of impact: low — apps that use `marmeon tinker` or `--sandbox` and have a class named like a framework class, list a package only through another one, or install `@marmeon/database` twice.* `marmeon tinker` used to take the classes behind `db`, `repos`, `jobs`, `mail` and the `--sandbox` transaction from a map that is also filled by class name, so a job class named `Connections` could stand in for the database. It now loads `@marmeon/database`, `@marmeon/queue` and `@marmeon/mail` only when your `package.json` lists them, finds each from your app, and offers a helper only when the container binds that exact class. A helper whose package only another package depends on is unavailable until you list the package yourself (`marmeon add database`), and `.ls` names the cause of each missing helper. `--sandbox` refuses before the session starts where a same-named class used to stand in, and where the dependency tree holds a second copy of `@marmeon/database`, because writes through that copy are not undone by the transaction. It prints one line per copy with the fix. A sandboxed session whose start was refused no longer evaluates input outside a transaction. Without `--sandbox`, nothing changes. See [tinker](https://marmeon.com/docs/console.md#tinker). ### Logs #### Low: A failed log write stops the logger instead of ending the process *Likelihood of impact: low — apps whose standard output or error can fail to write (a full disk, a closed descriptor), and runs that pipe the log to a reader that leaves early.* The `Logger` contract says that `debug`, `info`, `warn` and `error` never throw. `@marmeon/log` kept it only in part: a failed write threw out of `info()` under `--json` and `marmeon mcp`, and on the default output a write error other than EPIPE became an uncaught error, after which the process hung in its exit flush. After the first write error, the logger now stops writing until the process restarts and prints one notice on stderr that names the error code. No notice follows when stderr fails in `--json` or `mcp` mode, or when a reader left early (EPIPE). By default (JSON on stdout), a pipe that nobody reads is backpressure: `info()` returns at once, and past 4 MiB of waiting lines the newest are dropped. At exit, the logger waits a few seconds for the reader, then drops the rest and prints the notice. `--json`, `marmeon mcp` and `format: 'pretty'` wait for their reader and retry every 100 ms, so a reader that stops reading blocks the process; after a few minutes the write fails and the logger stops as after any write error. No notice is printed when stderr is a full pipe. A destination you pass to `createPinoLogger` is not wrapped, so its errors stay yours. Watch the notice, and restart a process whose log stopped. There is no way back. See [writing log entries](https://marmeon.com/docs/logging.md#writing-log-entries). #### Low: Auth and the queue finish their work before they depend on the logger *Likelihood of impact: low — apps with a log sink that can throw or reject, and tests that check the order of a log line and an ended session.* A logger that throws, or returns a rejected promise, no longer changes how a request ends. When auth finds a copied remember-me cookie or a possibly copied passkey, it ends the sessions first and logs the warning after them, so a log sink that is down cannot keep the thief signed in. The log calls on the failure paths of passkeys, authenticator apps, the gate and password resets are guarded the same way: the original error or answer is kept, and a password reset still finishes. A job that fails for good still fires `JobFailed` when the logger's `error()` rejects, and a `sync` dispatch rejects with the job's own error. Nothing changes while your logger works, apart from the order of the theft warning and the endings. See [writing log entries](https://marmeon.com/docs/logging.md#writing-log-entries). ### The start and the packages #### Low: Discovery and the database look for packages and lockfiles only up to your workspace *Likelihood of impact: low — apps that depend on a package installed only outside their workspace (above a pnpm workspace, through an optional peer or a development dependency after a production install), on a lockfile planted in a folder everyone can write to, or on a `package.json` of a workspace package that changes while the app runs.* Discovery looked a dependency up in the `node_modules` of every folder up to the file system's root. It now looks in the `node_modules` of the package that needs it and of each folder above it, up to your workspace: the first folder from your app upwards with a workspace marker or a lockfile, else your app's folder. The search for the workspace stops below the first folder above the app that everyone can write to or that another user owns. A package in `dependencies` that is installed but out of reach is named in a warning at the start, once per process, and is not discovered: install it in the app. A missing dependency ends with K7, and the message now says where the lookup stopped. A provider that is no class makes the start end with K7 and names its package, where it ended in a `TypeError` that did not. `.marmeon/manifest.json` also records the `package.json` of the packages of your workspace, so a change in one of them makes the app discover again; it is written once more after the upgrade. `@marmeon/database` stops its search for a lockfile at the same bound, so a lockfile planted in a writable folder between the app and the workspace no longer narrows the migrations' workspace (D20) or moves the install root of `db:publish`. See [discovery](https://marmeon.com/docs/modules.md#discovery) and [D20](https://marmeon.com/docs/errors.md#server-error-codes). #### Low: The vite peer range starts at 8.3.6 *Likelihood of impact: low — apps on vite 8.3.1 to 8.3.5.* `@marmeon/server` and `@marmeon/vite` now ask for `vite` `^8.3.6`. Vite 8.3.6 is the first release whose dev server refuses `.wasm` files outside `server.fs` and escapes HTML attributes, and `@marmeon/vite` relies on `server.fs.deny` holding for clients that reach the dev server over the network. An app on an older vite 8.3 gets a peer warning. Run `pnpm up vite`. There is no way back. #### Low: A sync delay, a scheduled job of another class and a second copy of a package are warned about *Likelihood of impact: low — apps that dispatch with a delay on the `sync` connection (the usual one in tests), schedule a subclass of a registered job, or install a framework package twice in one version.* Three new warnings; nothing refuses. A `delay` on the `sync` connection logs one `warn` line with `dispatched: `: the job still runs at its dispatch, or at the commit inside a transaction, and ignores the delay. It is said once per app, connection and job name, in every environment, so it can show up in test output, and a test that refuses any warning sees it. Queue the job on `database` or `redis` to delay it. `schedule:work` prints one warning at its start for each task that queues a job class whose name the app registers for another class, such as a subclass that inherits `static job`; the runs of that task already failed at the queue. `marmeon check` and `doctor` warn when a package your app lists resolves its own copy of an `@marmeon/*` package in your app's version (pnpm installs a package once per set of resolved peers): align the peers and run `pnpm dedupe`. The exit code stays 0. `marmeon dev` prints the advice at its start, and a failed command prints it after K3. Manifest text can no longer add a line to a finding: names and versions that are no package name or version print escaped. See [queue connections](https://marmeon.com/docs/queues.md#drivers), [scheduling](https://marmeon.com/docs/scheduling.md) and [the packages check](https://marmeon.com/docs/check.md#the-packages-check). ## Upgrading to 1.2.3 from 1.2.2 ### Security hardening #### Low: startServer holds a response to its length, answers a failed body, and refuses a fetched Response *Likelihood of impact: low — apps with streamed responses of their own, routes that return a `Response` from `fetch()`, its clone, `Response.error()` or one made before the server started, code that checks `instanceof Response` or `instanceof Request`, and routes that set `Content-Length`, `Transfer-Encoding` or `Trailer` on a response.* Under `startServer()`, a response is held to its `Content-Length`: a longer body is cut at it and a shorter one closes the connection. A streamed body that fails on its first reads is answered `500` instead of a shorter `200`. A body that fails later closes the connection, and the text of its error is never sent. A `Transfer-Encoding` or `Trailer` header of a route is not sent, and a `Content-Length` of a route is sent only when it is one whole number. Nothing changes in code, unless your route sets one of these headers itself. A stream is cancelled when its client left before the response started. A stream you feed from a timer or an event needs a `cancel()` that stops feeding it. - `instanceof Response` and `instanceof Request` in your own code are now true also for those of the platform, such as from `fetch()` and `.clone()`. - A route that returns a `Response` of `fetch()` or its clone, `Response.error()`, or one whose body is read or locked now answers `500` with a `TypeError`. Before, `startServer()` sent it as JSON `{}`. Build a `Response` of your own from the body and the headers you choose to pass on, without `Content-Encoding` and `Content-Length` ([responses](https://marmeon.com/docs/responses.md#other-results)). - A `Response` your code made goes out as the pages say, also a subclass of it, a clone of it, and one made before the server started. Before, `startServer()` sent a clone and one made before the start as `{}`. This release fixes [GHSA-mxg6-hmhw-47gq](https://github.com/marmeon/marmeon/security/advisories/GHSA-mxg6-hmhw-47gq). ## Upgrading to 1.2.2 from 1.1.0 ### Commands #### Low: A command of your own named add, doctor, upgrade or db:query needs another name *Likelihood of impact: low — apps, and packages they use, with a command of exactly one of these names, such as `db:query` in a module named `db`.* `marmeon` brings four new commands. `add` installs a framework package at the app's version, `doctor` checks that a machine can run the app, and `upgrade` moves every framework package to one version. `db:query` comes with `@marmeon/database` and runs one read-only query against a connection. A command of your own with one of these names now stops `marmeon build` and the start with K8, and the message names both classes. Rename yours, preferably into your module's group (`notes:doctor`), and change the scheduled tasks and scripts that call it by its old name. There is no way back: the names belong to the framework. See [writing commands](https://marmeon.com/docs/console.md#writing-commands). #### Low: @marmeon/oauth brings the commands make:oauth and make:social-accounts-table *Likelihood of impact: low — apps that add `@marmeon/oauth` and have a command of their own named `make:oauth` or `make:social-accounts-table`.* Nothing changes until you add the package. Its provider registers `make:oauth`, which writes the sign-in module into the app, and `make:social-accounts-table`, which writes the migration of the `social_accounts` table. A command of your own with one of these names then stops `marmeon build` and the start with K8. Rename yours before you add the package. There is no way back. See [the generated module](https://marmeon.com/docs/oauth.md#the-generated-module). ### Pages, forms and policies #### Low: A policy's static guard names the guard whose users it judges *Likelihood of impact: low — policy classes with a static property named `guard`, also one they inherit.* `@marmeon/auth` now reads `static guard` on a policy class: it names the guard whose users the policy judges ([policies of a guard](https://marmeon.com/docs/authorization.md#policies-of-a-guard)). Without the static, or with `undefined`, a policy judges your app's users as before. Any other value that is not a guard made by `defineGuard()` and registered, or a guard slot, fails with A8 the first time the gate asks the policy, before the policy runs. The compiler points at such a policy: it has no abilities, so `can()` and the gate's methods refuse its ability names. Rename the static. There is no way back. #### Low: Every page of the web group carries the prop _conflict *Likelihood of impact: low — tests that compare all props of a page, and pages that pass a prop named `_conflict`.* `ShareErrorsFromSession` of `@marmeon/session` shares `_conflict` on every page of the `web` group. It holds the conflict of a stale save that a form shows ([conflicts](https://marmeon.com/docs/forms.md#conflicts)), and `null` when there is none. A test that compares a page's props as a whole now needs `_conflict: null`. A page's own prop named `_conflict` is a type error at `view()` and is dropped at run time: give it another name. There is no way back. #### Low: upload() refuses an option it does not know *Likelihood of impact: low — upload rules whose options come from a variable or from JavaScript and carry a key `upload()` does not take. TypeScript already refuses such a key in an object literal.* `upload()` takes `maxBytes`, `mime`, `text` and `dimensions`. Any other key now makes it throw a `TypeError` that names the key, where 1.1.0 ignored it. A misspelt `mimes` therefore no longer leaves every file type allowed without a word. Correct or remove the key. There is no way back. See [uploads](https://marmeon.com/docs/validation.md#uploads). ### Migrations #### Low: Raw SQL in a data step that names the migrator's tables stops with D4 *Likelihood of impact: low — migrations whose `schema.data()` step names `migrations` or `migration_lock` in raw SQL, or appends raw SQL that changes the schema to a query.* A `schema.data()` step now reads each statement as it is sent. Raw SQL that names `migrations` or `migration_lock` stops the migration with D4, a read included; on SQLite a word inside a string counts too. So does a write to those tables through the query builder inside a CTE, a subquery or an `insert … select`, and raw SQL that changes the schema, appended to a query or nested in one. In 1.1.0 the guard did not look for the migrator's tables in raw SQL. A migration that ran stays recorded and does not run again in that database. It stops with D4 on every fresh database: in your tests, after `migrate:fresh` and in a new environment. Read the migrator's tables through the query builder, which may still do so, and move a schema change into a step of its own (`schema.alter()`, `schema.raw()`). There is no way back. See [changing the data](https://marmeon.com/docs/migrations.md#changing-the-data). ### Logs and coding agents #### Low: A query parameter named state is masked in logs, the error page, the devtools and traces *Likelihood of impact: low — apps with a query parameter of their own named `state` (`/orders?state=open`) whose value someone reads in the log, the error page, the devtools or traces.* An OAuth `state` ties a browser to a pending sign-in, so a reader of the log must not get it. The redactor now masks the value of every query parameter named `state`, like `code`, also your own: `/orders?state=open` shows as `/orders?state=[redacted]`. The error page, the devtools and traces that record query values mask it in their query fields too. Your routes read the parameter as before. If you need such a value in the log, log it as a field of its own: a log field named `state` stays readable. There is no way back: the masking has no setting. See [keeping secrets out of the log](https://marmeon.com/docs/logging.md#keeping-secrets-out-of-the-log). #### Low: A coding agent can read rows of the development database through marmeon mcp *Likelihood of impact: low — apps whose coding agent uses the MCP server that `marmeon agents:install` sets up, and whose development database holds personal data.* `marmeon mcp` has a new tool, `query`: one read-only SQL query on a connection of the app, in development and test only ([the query tool](https://marmeon.com/docs/mcp.md#query)). It is there as soon as the packages are upgraded. The server announces it as read-only, and it is meant to run without a question for each call. Secret columns and connections set to `managed: false` are refused, and string values are masked the way the log is. The other values reach the agent, and with them the provider that runs it. If that is not acceptable, deny the tool in the agent's permissions; for Claude Code, add `"mcp__marmeon__query"` to `permissions.deny` in `.claude/settings.json`. #### Low: marmeon check reports the AGENTS.md block and the installed skills as out of date *Likelihood of impact: low — apps that ran `marmeon agents:sync` or `marmeon agents:install`, and run `marmeon check` or the `--check` of those commands in CI.* The block of `AGENTS.md` and the skills `marmeon-debugging` and `marmeon-testing` now name the new tools of `marmeon mcp` and `tinker --sandbox`. Until you run `marmeon agents:sync` and `marmeon agents:install` and commit the result, `marmeon check` warns that they are out of date, and `agents:sync --check` and `agents:install --check` exit with 1. There is no way back. See [keeping the block current](https://marmeon.com/docs/agents.md#keeping-the-block-current). ### The start #### Low: A lang/marmeon folder that cannot be read stops the start *Likelihood of impact: low — servers on which the app's `lang/marmeon/` folder exists but the process may not read it.* The start reads your rewording of the framework's texts from `lang/marmeon/` ([the framework's texts](https://marmeon.com/docs/localization.md#the-frameworks-texts)). A folder that is there but cannot be read now stops the start. 1.1.0 skipped it and showed the framework's own wording. A folder that is not there still means no rewording. Let the app's process read the folder, or remove it. There is no way back. ## Upgrading to 1.1.0 from 1.0.0 ### Security hardening #### Low: A passkey with an RSA key under 2048 bits or an unlisted algorithm no longer signs in *Likelihood of impact: low — accounts whose stored passkey uses an RSA key under 2048 bits, or an algorithm other than ES256, EdDSA and RS256 (for example from imported rows). Common RS256 authenticators such as Windows Hello make 2048-bit keys.* Nothing changes in code. Registration refuses an RSA key shorter than 2048 bits with `invalid` and fires no event. Sign-in refuses such a stored key, or one whose algorithm registration does not offer, before anything is verified, like any wrong passkey: a passwordless sign-in returns `invalid` and fires `PasskeySignInFailed`; as a second factor (after the password, at a step-up, when confirming sudo mode) it returns `invalid-code` and fires `TwoFactorChallengeFailed`. An affected account signs in with its password and another second factor or a recovery code, removes the passkey and registers a new one. There is no way back: the bound has no setting. ## Upgrading to 1.0.0 from 0.4.0 ### Before and right after the upgrade #### High: Before you upgrade *Likelihood of impact: high — every app checks this list before it moves to this release.* 1.0.0 reads what 0.4 wrote: sessions, the session and remember-me cookies, API tokens, queued jobs, cache entries, uploads and the record of migrations. Nobody has to sign in again, no queue has to run empty, and servers of 0.4 and 1.0 may run side by side during a rolling deploy. What two versions do not share: the live stream ([the stream's protocol version](https://marmeon.com/docs/upgrading.md#low-the-live-stream-carries-its-protocol-version)), whose hints between old and new nodes are lost during the rollout, so that a tab opened before it gets no live updates until its next visit; values encrypted without a context (step 1); links without an expiry and temporary links over seven days (step 3.3); and a reset link that is older than a lowered `AUTH_RESET_MINUTES` (step 3.3). Do these in order. 1. **On 0.4, before you move a package.** Some changes cannot be made afterwards: - **Values you encrypted without a context:** re-encrypt them, deploy the code that passes the context, then upgrade. This release reads none of them ([encryption](https://marmeon.com/docs/upgrading.md#medium-every-encryption-takes-a-context-of-its-own)). - **A named Redis connection without a prefix:** give it one in its `resolve`, and move the keys it kept without a prefix under the new one first ([Redis](https://marmeon.com/docs/upgrading.md#low-a-named-redis-connection-needs-a-prefix)). - **A Redis queue whose name ends in `:delayed` or `:reserved`:** rename it, and move its jobs with the workers stopped ([queue names](https://marmeon.com/docs/upgrading.md#medium-a-redis-queue-name-must-not-collide-with-the-keys-of-another-queue)). 2. **In development, with the packages at 1.0.0.** 1. Move every framework package at once: `pnpm up --latest "@marmeon/*" marmeon`. Then check that `package.json` names every `@marmeon/*` package and `marmeon` at exactly `1.0.0`: an app made before 1.0 does not save exact versions, so pnpm may write `^1.0.0`. Set each one to `1.0.0` by hand where it did and run `pnpm install`; never upgrade one alone ([how to upgrade](https://marmeon.com/docs/releases.md#how-to-upgrade)). On the first day after the release, pnpm holds the new versions back ([the first day after a release](https://marmeon.com/docs/releases.md#the-first-day-after-a-release)). 2. Change what stops the start, in `.env`, `.env.test`, `.env.example`, the compose file and the CI configuration. `make:auth`, `migrate`, `db:types` and `route:types` start the app, so they stop on each of these, with a message that names the problem: - `SERVER_MAX_BODY_SIZE`, `MAX_BODY_SIZE` and `HASH_ARGON_MEMORY` become `SERVER_MAX_BODY_MB` and `HASH_ARGON_MEMORY_KB` ([sizes](https://marmeon.com/docs/upgrading.md#medium-a-size-in-an-environment-variable-names-its-unit)); - `AUTH_RESET_MINUTES` and `UPLOADS_SEND_WITHIN_MINUTES` are at most 1440 ([auth](https://marmeon.com/docs/upgrading.md#medium-access-tokens-password-changes-and-reset-links-have-safe-defaults), [temporary URLs](https://marmeon.com/docs/upgrading.md#low-a-temporary-url-lasts-at-most-seven-days-on-every-disk)); - `SERVER_TRUSTED_PROXIES` has no `0.0.0.0/0`, `::/0` or IPv6 range that holds all of IPv4: write `*` if every peer really is your proxy, or list the proxy ranges ([proxies](https://marmeon.com/docs/upgrading.md#low-a-0-proxy-range-stops-the-start-and-development-details-go-only-to-allowed-hosts)); - a slow Postgres server, such as a paused serverless database, needs `?connect_timeout=` in `DB_URL` when it takes longer than 10 s to accept a connection ([Postgres](https://marmeon.com/docs/upgrading.md#low-postgres-connections-time-out-after-10-seconds-and-keep-utc)); - a Vite `base` that is a path or relative (`/static/`, `./`) becomes `/` or the absolute URL of the assets ([the base](https://marmeon.com/docs/upgrading.md#low-vites-base-is--or-an-absolute-url-and-the-server-links-a-pages-chunks-under-it)). 3. An app made with the starter kit: add `oxc-transform` and run `marmeon make:auth --force` ([the kit](https://marmeon.com/docs/upgrading.md#high-apps-made-with-the-starter-kit-take-its-auth-module-once-more)). Until then its tests and its type check fail on the old module. 4. Run `marmeon migrate` on the development database, then `marmeon db:types`, `marmeon route:types` and `marmeon agents:sync`, and commit what they write. 1.0.0 adds no migration an existing app has to run, but `migrate` writes the table types in development; `db:types --check` fails with "generated by another version" until the types are written again ([table types](https://marmeon.com/docs/upgrading.md#high-the-generated-table-types-declare-primary-keys)); `agents:sync` brings the block of `AGENTS.md` up to date, which `marmeon check` reports until then ([coding agents](https://marmeon.com/docs/agents.md)). 5. Make the changes of the other entries below. The compiler, `marmeon check` and the tests point at most of them; the lists after this procedure name what they cannot find. 3. **Deploy.** 1. Set the environment of the servers and the platform to the new names and limits of step 2.2, in the same deploy as the new release: an old name that is still set stops the start. 2. Run `marmeon migrate --force` once, as with every deploy ([deployment](https://marmeon.com/docs/deployment.md#checklist)), and roll the new release out. There is nothing to stop and no session or token to end. 3. Links you sent before the upgrade: a signed link without an expiry answers 403 unless its route says `signed({ forever: true })` ([signed links](https://marmeon.com/docs/upgrading.md#medium-a-signed-link-carries-its-expiry-and-signed-refuses-one-without)), and a temporary storage link made for longer than seven days answers 403: send new ones, or serve such files through a route of your own ([temporary URLs](https://marmeon.com/docs/upgrading.md#low-a-temporary-url-lasts-at-most-seven-days-on-every-disk)). If `AUTH_RESET_MINUTES` was above 1440 and you lowered it, an open password-reset link older than the new limit is refused when it is used: the limit applies at use, so ask those users to request a new link. The start stops with a message that names the problem for: a command named `dev` or `start` (K8), a scoped binding whose binder does not scope (H11), a route pattern that cannot be read the same way everywhere (H13), a check timeout over its limit, at zero or below (K13), a named Redis connection with an empty prefix (K6), a default layout whose `error` is no component (R19), a `MAIL_DRIVER` that no provider brought (Q8), a body schema with a file in a list, a union or an optional object (S2), an environment variable with an old size name, two different `defineConnection()` definitions with the same name (D23), a `csrfExcept` pattern that matches every path, does not start with `/` or starts with a placeholder (a `TypeError`, [CSRF exclusions](https://marmeon.com/docs/upgrading.md#low-a-wildcard-in-a-csrf-exclusion-matches-within-one-path-segment)), `abilities()` without an ability, a default Redis queue whose name collides (Q4), the proxy ranges, `AUTH_RESET_MINUTES` and `UPLOADS_SEND_WITHIN_MINUTES` above, and an invalid `connect_timeout`. `vite.config.ts` refuses the options `pages` and `lang`, and `marmeon build` a Vite `base` that is no URL. `marmeon dev`, `build`, `route:types` and `check` stop for an error page or a layer backdrop in its former place (K14, [system module](https://marmeon.com/docs/upgrading.md#low-the-error-pages-and-the-layer-backdrop-live-in-the-system-module)). Neither the compiler nor the start finds these: a check timeout written in milliseconds; a number in `once(fn, { for })`, which is seconds; a number of milliseconds as the timeout of the live test reader, now seconds; a string returned from a route, now sent as `text/plain`; a link without `expires` at `signed()`; a `sync` or unique job dispatched through a transaction you began yourself; `auth.updatePassword()` without a confirmed password; a script that tests for exit code 1 after a wrong argument; a `temporaryUrl()` longer than seven days on a local disk, which now throws when it is signed; a `Limit` built from a count that is zero or not a number, which now throws when the limiter runs; a test app that runs as production and posts without a CSRF token, which now gets a 419; a call of `AccountSessions.end(userId)` or `marmeon auth:end-sessions` that must keep the user's API tokens, which now revokes them; a test or a `layout(name)` that compares the name of an error page or the backdrop; an island that reads a cookie while its page is rendered on the server for a visitor without a session ([islands and cookies](https://marmeon.com/docs/upgrading.md#medium-an-island-rendered-with-its-page-sees-cookies-only-while-the-page-is-private)); a closure route that returns `island()`, an `island` imported through a re-export, a module package built before this version and a controller that returns a page or an island depending on a branch, which all answer 404 ([island routes](https://marmeon.com/docs/upgrading.md#low-an-island-request-reaches-only-a-controller-that-returns-island)); a `csrfExcept` such as `/webhooks/*` that no longer covers `/webhooks/stripe/events`, whose requests get 419 ([CSRF exclusions](https://marmeon.com/docs/upgrading.md#low-a-wildcard-in-a-csrf-exclusion-matches-within-one-path-segment)); a page that shows a table without `.attach(T.endpoints())`, also a table without actions or exports, which fails when the page is requested ([table endpoints](https://marmeon.com/docs/upgrading.md#medium-a-tables-endpoints-hang-on-its-page-with-endpoints)); a mail template with `mj-social-element`, `mj-accordion` or `mj-carousel` without its image attributes, which `fromMjml()` refuses with Q7 when the mail is rendered or sent ([MJML](https://marmeon.com/docs/upgrading.md#low-mjml-components-without-an-image-source-of-their-own-are-refused)); a `TimeZone` in the `?options=` of `DB_URL`, which UTC silently replaces ([Postgres](https://marmeon.com/docs/upgrading.md#low-postgres-connections-time-out-after-10-seconds-and-keep-utc)); a body schema built by a factory with a file in a list, a union or an optional object, which answers 500 at its first submit ([files](https://marmeon.com/docs/upgrading.md#low-a-file-in-a-list-a-union-or-an-optional-object-stops-the-start)); a table whose `authorize` returns something other than `true` ([table authorize](https://marmeon.com/docs/upgrading.md#low-a-tables-authorize-must-return-true)); and a script or a person that read a mail's reset or verification link from a production log, where only recipients and subject are written now ([the log mailer](https://marmeon.com/docs/upgrading.md#medium-the-log-mailer-writes-only-recipients-and-subject-outside-development-and-tests)). An entry below that names no way back has none. #### High: Apps made with the starter kit take its auth module once more *Likelihood of impact: high — apps made with `make:auth`, and every app made with `create-marmeon` on 0.4.* The kit's controllers, mails, tests and translations changed with the entries of this release, and nothing updates them in an app. Once the packages are at 1.0.0 the app still loads, but its type check and many of its tests fail on the old module. On a clean working tree: 1. Run `pnpm add -D oxc-transform` if the app lacks it: the kit's mails are React views, which the server compiles with it, and `marmeon build` stops without it while any mail view exists. 2. Run `marmeon make:auth --force`. It writes the module again and keeps every migration the app has, adding only the ones it lacks. It deletes the files of the old kit that the new one no longer writes, when `marmeon-stubs.json` shows the app left them unchanged: `controllers/CreateAccessTokenController.ts`, which the kit of 1.0 ships as `StoreAccessTokenController.ts`, and `mail/layout.ts`, which became the component `mail/Layout.tsx`. A file you changed stays and the command names it: carry your changes to the mail frame (branding, footer) into `Layout.tsx`, because the new mails no longer import `layout.ts`, and delete the old file once nothing of yours imports it. 3. Run `marmeon migrate`, `marmeon db:types` and `marmeon route:types`. 4. Look at `git diff` and put your own changes back. Without `--force`, port the changes from `packages/auth/stubs/react/modules/auth` of the installed version; the compiler and the tests point at most places. Every app made with `create-marmeon` on 0.4, with or without the kit, also has `HASH_ARGON_MEMORY` in `.env.test` and `progressBar({ delay: 250 })` in `bootstrap/client.tsx`: rename them to `HASH_ARGON_MEMORY_KB` ([sizes](https://marmeon.com/docs/upgrading.md#medium-a-size-in-an-environment-variable-names-its-unit)) and `delayMs` ([the client's spans of time](https://marmeon.com/docs/upgrading.md#medium-the-clients-spans-of-time-name-their-unit-in-milliseconds)). There is no way back. See [the starter kit](https://marmeon.com/docs/starter-kit.md). ### Security defaults #### Medium: Every encryption takes a context of its own *Likelihood of impact: medium — apps that call `encrypt()` or `decrypt()` themselves.* `Encrypter.encrypt(plaintext, context)` and `decrypt(payload, context)` require the context, also in `AesGcmEncrypter` and `CursorEncrypter`. `''` or a missing argument throws a `TypeError`. The context binds a ciphertext to its use: without one, two values an app encrypted were interchangeable. - Give each use of your own a context of its own that starts with none of `cookie:`, `session:`, `queue:` or `marmeon`: ```ts // before encrypt(value) // after encrypt(value, 'billing:coupon') ``` - Values stored without a context used the empty one. This release does not decrypt them, and no method reads them. Re-encrypt them **before you upgrade, on 0.4**, where `decrypt(payload)` still reads them and `encrypt(text, context)` already takes a context: run `encrypt(await decrypt(row.code), 'billing:coupon')` over the column, deploy the code that passes the context, then upgrade. - The payload format does not change, and every framework caller already passed a context, so cookies, sessions, jobs and cursors keep decrypting. An app that always passed a context changes nothing. #### Medium: A signed link carries its expiry, and signed() refuses one without *Likelihood of impact: medium — apps that make signed links or have routes behind `signed()`.* Making a link: | Before | After | | --- | --- | | `signer.temporarySignedRoute(name, params, '7d', { base })` | `signer.signedRoute(name, params, { expiresIn: { days: 7 }, base })` | | `signer.signedRoute(name, params)` (never expired) | `signer.signedRoute(name, params, { expiresIn: … })`, or `signer.foreverSignedRoute(name, params)` if the link really must never expire | | `signer.signedPath(path)` | `signer.signedPath(path, { expiresIn: … })` | - `expiresIn` is required and at least one second: a number of seconds or a `Duration` object, never a string such as `'7d'`. 0, negative or sub-second values throw a `RangeError`. Untyped code without `expiresIn` gets a `TypeError` that names `foreverSignedRoute()`. - `params` is always required: pass `{}` for a route without parameters. Accepting a link: - A route behind `signed()` answers 403 to a link without `expires`, and `hasValidSignature(url)` is `false` for it. An expired link is refused as before. - Links from `foreverSignedRoute()`, and old links in mails that were made without an expiry, need `signed({ forever: true })` on their route, or `hasValidSignature(url, { forever: true })`. `forever` takes only `true`. Prefer giving such links an expiry. - An empty or doubled `expires=`, or one in the path or fragment, is refused. Links made with an expiry change nothing, and links sent before the upgrade *with an `expires`* keep working; the signature and the query format are unchanged. A link sent without one needs `forever` as above. #### Medium: Access tokens, password changes and reset links have safe defaults *Likelihood of impact: medium — apps with `@marmeon/auth` that create API tokens, change passwords outside the kit's controllers, or end a user's sessions.* - **Tokens:** `{ abilities, expiresIn }` is required. ```ts // before tokens.create(user.id, 'CI') // after tokens.create(user.id, 'CI', { abilities: ['users:read'], expiresIn: { days: 90 } }) ``` `abilities: ['*']` allows everything and `[]` nothing; `expiresIn: null` never expires and `0` is expired at once. An untyped caller without options gets a `TypeError` before anything is written. A custom `AccessTokenStore` takes the now required `options`. - **Password change:** `auth.updatePassword()` throws unless the password was confirmed within `AUTH_PASSWORD_TIMEOUT_SECONDS`. A route that calls it runs `checkPassword(current)` first, as the kit does, or sits behind `confirmedPassword()`. - **Ending a user's sessions:** `AccountSessions.end(userId)` and `marmeon auth:end-sessions` now also revoke the user's API tokens and delete their password-reset link, like `endEveryone()`. Keep the tokens with `end(userId, { accessTokens: false })` or `--keep-api-tokens`, for an integration that must outlive a sign-out; the result says how many it revoked (`accessTokens`). The options are an object: `end(userId, false)` throws a `TypeError`. - **Reset links:** a changed password deletes the account's reset link inside its transaction, so an older link answers `invalid-token`. A `PasswordResetTokenStore` of your own is asked to `forget()` the account's address there and when sessions end, as stored and trimmed in lower case (the form the starter kit creates links under); when it fails, the password change fails. - **`AUTH_RESET_MINUTES`:** 1 to 1440; a larger value such as 10080 stops the start. - **Session id:** a right password in `checkPassword()` regenerates the session. Browsers follow on their own. Live streams in other tabs end until the tab navigates, and a request that still carries the old cookie (a double submit, a parallel fetch) is a guest. - **Tests** that hold a session cookie across a right password take the new one from the response: ```ts cookie = (await app.withCookie(S, cookie).post('/confirm-password', …)).cookie(S) ?? cookie; ``` An app that copied the kit's tests takes their updated versions from the kit. The kit's controllers already pass `abilities` and an expiry and confirm the password first, so they are unchanged, and so is the reset flow through `PasswordBroker.reset()`. A stolen remember cookie, a cloned passkey and `auth:reset-two-factor` end the sessions but keep the API tokens; the clone mail tells the owner to check them. A passkey clone suspended inside an app transaction now stays suspended after a rollback. #### Medium: A string from a route is sent as text, and only Html as HTML *Likelihood of impact: medium — apps with routes, controllers or error handlers that return a string.* | Result | Before | Now | | --- | --- | --- | | a string | `text/html` | `text/plain; charset=utf-8` | | ``html`…` `` or `raw(…)` | JSON `{}` | `text/html; charset=utf-8` | Return ``html`…` `` from `@marmeon/core` or `this.view()` for markup, and drop any `String(…)` around an `html` template: ```ts // before return String(html`…`); // after return html`…`; ``` This holds for closures, controller `handle()`, action requests and error handlers. An `Html` result gets the CSP header, so `ctx.nonce()` works in it. #### Low: A /0 proxy range stops the start, and development details go only to allowed hosts *Likelihood of impact: low — apps that trust every peer through a `/0` range, or develop on a LAN IP or a Compose host name.* - `SERVER_TRUSTED_PROXIES` with any `/0` (including `/00`), `::/0`, or an IPv6 range that holds all of the IPv4-mapped block (`::ffff:0.0.0.0/96`, `::/80`) stops the start. Such a range let every client write its own address into `X-Forwarded-For`. Write `*` if every peer really is your proxy, or list the proxy ranges. - In development, the error page, the exception text of region and island errors, the SSR overlay, the page and island hints and the details of `/up/ready` go only to `localhost`, a loopback address or the host of `APP_URL`. Any other `Host` gets the plain answer. If you develop on a LAN IP or a Compose host name, set `APP_URL` to that host. #### Low: A named Redis connection needs a prefix *Likelihood of impact: low — apps with a `defineRedisConnection()` whose `resolve` returns `prefix: ''`.* An empty prefix on a named connection stops the start with the "Invalid configuration" error (K6), as `REDIS_PREFIX` already did. Give every `defineRedisConnection(...)` a non-empty `prefix` in its `resolve`, e.g. `'notes-app:'`. If the connection kept keys without a prefix, move them under the new prefix first: the connection now reads and writes under it. `resolve` also runs during that check, so keep it free of side effects. #### Low: A middleware list that would drop a layer throws *Likelihood of impact: low — apps in plain JavaScript, or with conditional middleware entries.* Each of these throws a `TypeError` when the routes or groups are defined; the TypeScript signatures are unchanged. - Several layers in one call: chain them. ```ts // before Route.middleware(throttle('x'), authenticate()) // after Route.middleware(throttle('x')).middleware(authenticate()) ``` The same for `Route.authorize(a).authorize(b)`. Chained `authorize()` calls add up, so every check must pass. - `undefined` or another non-middleware entry in a route or group list, e.g. `Route.middleware(flag ? throttle('x') : undefined)` or an entry in `defineApplication({ middleware: { global: [...] } })`: build the list with `.filter(Boolean)` or chain conditionally. - `MiddlewareGroups.append()` takes a number as its priority. #### Low: A binder of your own declares that it scopes *Likelihood of impact: low — apps that use `scopedBy` with a route binder of their own.* A binder used with `bind(…, { scopedBy })` declares `static readonly routeBindingScoped = true` and reads `binding.scope` (docs/routing.md › "Your own binder"). Without the mark TypeScript refuses `scopedBy`, and the app stops with H11 when its routes load. A subclass of `Repository` keeps the mark; one that overrides `resolveRouteBinding` passes `binding` on to `super`. A scoped binding whose parent is missing from the request answers 404 without calling the binder. #### Low: Live validation leaves out every field named like a secret *Likelihood of impact: low — forms that validate card numbers, codes, tokens or similar fields live.* The client no longer sends a field that `isSensitiveField` knows (passwords, passcodes and passphrases, card numbers and CVCs, one-time codes, tokens, secrets and keys) with a live validation, at any depth. Check such fields when the form is sent. - `form.validate('cardNumber')`, `validating('cardNumber')` and `validate: { fields: ['cardNumber'] }` are type errors; drop those names. - The type `PasswordNeverLive` from `@marmeon/http/page` is `SensitiveNeverLive`. #### Low: The deprecated remembered-field patterns are gone *Likelihood of impact: low — apps or client adapters that test field names against the two patterns.* Neither `@marmeon/http/client` nor `@marmeon/http/client/adapter` exports `SENSITIVE_REMEMBER_FIELD` and `NEVER_REMEMBERED_FIELD` any more. ```ts // before SENSITIVE_REMEMBER_FIELD.test(name) // or NEVER_REMEMBERED_FIELD.test(name) // after isSensitiveRememberField(name) ``` Its second argument lists the fields a form lets in after all, never a password: `isSensitiveRememberField(name, ['card_number'])`. It answers `true` until `loadSensitiveFields()` has resolved (docs/forms.md#remembering-input). #### Medium: A rate limit takes its numbers by name *Likelihood of impact: medium — apps that call `RateLimiter.attempt()` themselves, or build a `Limit` from a number that may be zero or missing.* `limiter.attempt(key, 5, 60)` becomes `limiter.attempt(key, { maxAttempts: 5, decay: 60 })`. The two numbers were easy to swap: `attempt(key, 60, 5)` allowed 60 attempts every 5 seconds instead of 5 a minute, and nothing said so. The old form is a type error, and in JavaScript it throws a `TypeError` without counting an attempt; so do a `maxAttempts` that is not a positive finite number and a missing or invalid `decay`. The `Limit` factories (`Limit.perSecond()`, `perMinute()`, `perHour()`, `perDay()`) throw a `TypeError` for a count that is not a positive finite number. Such a limit used to be dropped, so `Limit.perMinute(Number(env.LOGIN_MAX))` with the variable unset let every request through; it now fails the request instead. `Limit.perMinute(0)` throws as well. For no limit, use `Limit.none()`. `hit()`, `tooManyAttempts()` and the route middleware `throttle()` are unchanged. `new Limit(…)`, `limit.maxAttempts` and `limit.decaySeconds` are internal: build limits with the factories. #### Low: Only the test app turns CSRF protection off *Likelihood of impact: low — code that called `CsrfProtection.disable()`, tests that run the test app as production, and apps with a `csrfExcept` pattern that matches every path.* `CsrfProtection.disable()`, `enable()` and `skips()` are no longer API, and `disable()` throws in a protected environment — any `NODE_ENV` but `development` and `test`, read from the app's environment, not the process's — so a line copied from a test cannot turn the protection off in production. Tests run without it as before, and `createTestApp(app, { csrf: true })` keeps it on. A test app that runs as production (`env: { NODE_ENV: 'production' }`) keeps it on as well, as on a server: a post without a token gets a 419. A `csrfExcept` or `except()` pattern that matches every path (`*`, `/*`, `**`) throws, so a `csrfExcept` like that stops the start: it turned the check off everywhere. Name the paths that need it (`/webhooks/*`), or put such routes in a group without CSRF verification. A route that takes signed requests from other sites can use `verifyWebhook()` instead. #### Low: A temporary URL lasts at most seven days on every disk *Likelihood of impact: low — apps that sign `temporaryUrl()` links for longer than a week, or set `UPLOADS_SEND_WITHIN_MINUTES` above 1440.* `disk.temporaryUrl(key, { expiresIn })` throws a `RangeError` for more than 7 days on every disk. On S3 such a link failed already, but only in production; on a local disk it was a link that practically never expired. A file that has to stay reachable longer goes through a route of your own that checks access and answers with `serveFile()`. A disk driver of your own is never asked for more than 604 800 seconds. The route that serves temporary links of local and memory disks (`/_marmeon/storage`) refuses one whose expiry lies more than seven days ahead, so links signed for longer before the upgrade answer 403. `UPLOADS_SEND_WITHIN_MINUTES` above 1440 stops the start, like `UPLOADS_LIFETIME_MINUTES`. #### Low: abilities() needs at least one ability *Likelihood of impact: low — routes that use `abilities()` without a name.* `abilities()` without a name checked nothing and let every token through. It is now a type error, and it throws a `TypeError` when the route is defined, as does an empty name or one that is not a string. A route that every token may call needs no `abilities()`. #### Low: Only html and raw() make an Html *Likelihood of impact: low — code that wrote `new Html(…)` or `new Mjml(…)`.* An `Html` is sent as `text/html`, so `new Html(markup)` was a second way past the escaping of the `html` template. The constructor is no longer public, and it throws a `TypeError` at run time too, from JavaScript and from a subclass. Build markup with the `html` template, and wrap markup you trust with `raw()` — never a value from a request. `Html` stays a type, and `instanceof Html` works as before. The same holds for `Mjml` of `@marmeon/mail`: only the `mjml` template makes one, so `new Mjml(markup)` becomes ``mjml`${raw(markup)}` ``. #### Low: Mails load a web font only from an mj-font of the template *Likelihood of impact: low — apps whose mail templates name Open Sans, Droid Sans, Lato, Roboto or Ubuntu in a `font-family` without an `` of their own.* mjml imported these fonts from Google Fonts whenever a template named one, so every opened mail called a third party. `fromMjml()` turns that list off: such a template now renders in the next font of its stack. To keep the web font, add `` inside ``, with a source you may load; it applies to that mail only. Mails of the starter kit need no change: their frame lists system fonts before Roboto. The way back, for one mail, is its own ``. See [writing mails](https://marmeon.com/docs/mail.md#writing-mails). #### Low: MJML components without an image source of their own are refused *Likelihood of impact: low — apps whose MJML uses `mj-social-element`, `mj-accordion` or `mj-carousel`, or loads an image from a host the template names nowhere else.* mjml fills a missing source of these components with an image from mailjet.com or imgur.com, which every opened mail would then load. `fromMjml()` refuses such a template with Q7, an `MjmlError` naming the component, the missing attribute and the host: - `mj-social-element` without `src`; - `mj-accordion` without `icon-wrapped-url` and `icon-unwrapped-url`; - `mj-carousel` without `left-icon` and `right-icon`. Set the attribute, on the tag or through `mj-attributes` (a tag, `mj-all` or an `mj-class`), to an image you host. The compiled HTML may also load only from hosts the template itself loads from (an image `src`, a `background-url`, an `mj-font`; a link or text does not count): an image that, for example, a component of your own adds from another host fails with Q7 and its URL, so write that URL into the template. Relative, `data:` and `cid:` URLs are fine. The starter kit's mails are unaffected. There is no way back. See [writing mails](https://marmeon.com/docs/mail.md#writing-mails). #### Low: A wildcard in a CSRF exclusion matches within one path segment *Likelihood of impact: low — apps with a `*` in `csrfExcept` or in an exclusion a service provider adds.* A `*` matched across `/`, so `/*/unsubscribe/*` also exempted every writing route below a workspace whose slug was `unsubscribe`. Now `*` matches within one path segment and `**` across segments. Search your modules and service providers for `*` in their CSRF exclusions: - A pattern meant for several levels (`/webhooks/*` for `/webhooks/stripe/events`) becomes `/webhooks/**`; otherwise those requests get 419. - A pattern that does not start with `/`, starts with a placeholder (`*`, `/*`, `/**`, `/*/unsubscribe/*`, `/**/x`) or has one in its first segment (`/webhooks*`) stops the start with a `TypeError`. Write the first segment out, one pattern per locale (`/de/abmelden/*`, `/en/unsubscribe/*`). There is no way back. See [excluding paths](https://marmeon.com/docs/csrf.md#excluding-paths). #### Medium: A table's endpoints hang on its page with endpoints() *Likelihood of impact: medium — apps that call `tableRoutes()`.* `tableRoutes()` is removed. A table's action, bulk and export endpoints hang on the page that shows it, and run everything that page runs, including the `authorize` of the page controller's request: ```ts // before list.get('/', ListMembersController).name('index'); tableRoutes(list.middleware(throttle('members-table')), MembersTable, { export: { middleware: [throttle('members-export')] } }); // after list.get('/', ListMembersController).name('index').attach(MembersTable.endpoints({ middleware: [throttle('members-table')], export: { middleware: [throttle('members-export')] }, })); ``` - Attach every table a page shows with `resolve()`, also one without actions or exports (`.attach(T.endpoints())`); otherwise `resolve()` fails and names the table and the page. - The endpoints are under the page's path. For a page at the root of its registrar, the URL stays the same. - Someone who may not see the page can no longer call its export or actions. - A table has routes only for the kinds it has: one without actions has no action route, one without an export no export route. A request to such a `/_tables/…` URL is a 404 for everyone; `tableRoutes()` registered all three, so a user the table's `authorize` refused got a 403 there. Nothing a user could do is gone, but a test or a monitor that expects that 403 has to expect the 404. #### Medium: The log mailer writes only recipients and subject outside development and tests *Likelihood of impact: medium — apps that read mail links (password reset, verification, signed links) from a production log.* `MAIL_DRIVER=log` is the default in every environment, and it wrote each mail's whole text to the log, so reset and verification links and their tokens reached production logs. Outside development and tests (production, or no `NODE_ENV`) the log mailer now writes only each mail's recipients and subject, with a note that the text is left out. Queued mails go through the same transport. Development and tests still log the whole mail. - An app that has to deliver mails sets `MAIL_DRIVER=smtp` with `MAIL_HOST`, `MAIL_USERNAME` and `MAIL_PASSWORD`, or uses a transport of its own (docs/drivers.md#mail-transports). - An app that only logged mails changes nothing; the boot warning says that no mail is sent. There is no option to log the text in production. See [the log mailer](https://marmeon.com/docs/mail.md#the-log-mailer). #### Low: The image of make:docker no longer holds the project's .npmrc *Likelihood of impact: low — apps that keep a registry token in `.npmrc` and build their image with a Dockerfile from `make:docker`.* A Dockerfile from `make:docker` copied the project's `.npmrc` into the image, so a registry token in it (`//npm.pkg.github.com/:_authToken=…`) was readable by anyone who could pull the image. A new Dockerfile deletes every `.npmrc` before the run stage and takes the credential as a BuildKit secret. - Run `marmeon make:docker --force` again, or copy the secret mounts and the `.npmrc` cleanup at the end of the last build-stage `RUN` from a newly generated Dockerfile. - Remove the auth line from the project's `.npmrc` and pass the credential with `docker build --secret id=npmrc,src=$HOME/.npmrc`. - **Rotate every token that was in a pushed image or a pushed build cache.** See [a private registry](https://marmeon.com/docs/deployment.md#a-private-registry). ### Spans of time #### Medium: Spans of time are seconds or a Duration, and values handed back name their unit *Likelihood of impact: high — apps that write a span of time as a string such as `'7d'`, apps with their own health or app checks, `once()` props, job middleware or scheduler overlap locks, and code that reads the auth, session, queue or uploads config, a queue event's delay, a cache entry's TTL or a limiter.* A bare number is seconds; anything else is a `Duration` such as `{ minutes: 5 }` (docs/time.md). A value the framework hands back names its unit. The environment variables (`AUTH_RESET_MINUTES` …), the worker flags `--sleep`, `--max-time` and `--stop-timeout`, and the stored records keep their names and units. **Strings are gone:** - `'7d'` becomes `{ days: 7 }` and `'60m'` becomes `{ minutes: 60 }`: in signed links, in the `expiresIn` of API tokens and verification links, and wherever else a span was a string. A string is a type error, and untyped code gets a `TypeError` that names the object to write. - Import `Duration` from `@marmeon/core`; `@marmeon/http` no longer exports it. The object form is the type `DurationParts`. - An expiry is rounded down to a whole second; a temporary storage URL used to round up. A storage `expiresIn` under one second is a `RangeError`. - A `Temporal.Duration` with `years`, `months`, `weeks`, `microseconds` or `nanoseconds` is refused; it used to count as zero. **Three numbers that keep compiling and change their meaning:** - A `static timeout` of a health check or an app check (`marmeon check`) is seconds, not milliseconds. Check every one, small values included: `100`, meant as 100 ms, now waits 100 seconds. ```ts // before static timeout = 5000; // after static timeout = 5; // or { milliseconds: 5000 } ``` A health check allows up to 60 s and an app check up to 600 s; over that, at zero or below, the start stops with K13, naming the check class. - `once(fn, { ttl })` in milliseconds is `once(fn, { for })`, a `Duration`, and **a number in `for` is seconds**: `for: 60_000` would mean about 16.7 hours. ```ts // before once(fn, { ttl: 60_000 }) // after once(fn, { for: { minutes: 1 } }) // or { for: 60 } ``` An old `ttl` key throws a `TypeError` naming the new form. - In tests, the timeout of `LiveStreamReader.hello()` and `waitFor()` is a `Duration`: `stream.waitFor(n, 3000)`, meant as 3 s, now waits 3000 seconds. Write `{ seconds: 3 }` or `3`. **Core and router:** - `DEFAULT_HEALTH_TIMEOUT` is no longer exported: write `2` or `{ seconds: 2 }`. - The `lock` and `wait` of `Route.block({ lock, wait })` are `Duration`s, and zero or a negative span throws a `TypeError` ([block()](https://marmeon.com/docs/upgrading.md#low-block-on-a-route-takes-lock-and-wait-by-name)). - `CookieOptions.maxAge` and a queued listener's `backoff` also take a `Duration` (the backoff a list of them); nothing to change. - `HealthCheckResult.ms`, `/up/ready` and `check --json` keep milliseconds. **HTTP and server:** - `createHttpKernel(app, { islandTimeout: 5000 })` becomes `{ islandTimeoutMs: 5000 }`; an old `islandTimeout` key throws. - `securityHeaders({ hsts: { maxAge: 31_536_000 } })` keeps working, and `maxAge: { days: 365 }` works too: whole seconds, and at least a year with `preload`. **Queue, notifications and cache:** - `retryAfter` is `retryAfterSeconds`: on a connection of the queue config, in the `QueueConnection` a driver factory returns, in the options of the memory, database and redis drivers, and in `JobMiddlewareContext` and the `QueueConnectionOptions` of `QueueConnections.options()`. `QUEUE_*_RETRY_AFTER_SECONDS` is unchanged, and the docs anchor is `queues.md#timeouts-and-retryafterseconds`. - `JobQueued.delay` and `JobReleased.delay` are `delaySeconds`, as is the `delay` of the entries of `app.queue.dispatched()` and of the `queue.dispatch` diagnostics message. A queue driver of your own reads `delaySeconds` in `QueuedPush` (the `next` entries of `ack(job, next)`). - A job middleware reads `context.timeoutSeconds`; reading `context.timeout` throws. - `cache.ttl(key)` becomes `cache.ttlSeconds(key)`, and `limiter.availableIn(key)` becomes `limiter.availableInSeconds(key)`; the old names are gone. - The cache's `ttl`, `lock()` and `Lock.block()` take a `Duration`; numbers keep meaning seconds. A `Limit` window that is not a whole number of seconds (`Limit.perSecond(5, 0.5)`), or zero or below (`Limit.perSecond(5, 0)`, `Limit.perMinute(5, 0)`), is a `RangeError`; `Limit.none()` is unchanged. A count that is not a positive number throws as well ([rate limit](https://marmeon.com/docs/upgrading.md#medium-a-rate-limit-takes-its-numbers-by-name)). - A `Duration` is taken by a job's `timeout` and `backoff`, `job.once(key, fn, { for })`, `withoutOverlapping({ releaseAfter, expiresAfter })`, the `WorkOptions` `sleep`, `maxTime`, `stopTimeout` and `watchOtherQueues`, `worker(connection, stopTimeout)` and a notification's `backoff`. - A worker started with a span that is not finite or below 0 (or `'5s'` from untyped code) stops with a `QueueError` at once, before it claims a job. **Storage:** - `UploadsConfig.lifetime` and `sendWithin` are `lifetimeMinutes` and `sendWithinMinutes`; the environment variables are unchanged. - A disk driver of your own (`static diskDrivers`): the factory returns a `DiskDriver`, and its `temporaryUrl(key, options)` receives `{ expiresInSeconds, filename?, base? }`, whole seconds of at least 1, instead of `expiresIn`. The app-facing `disk.temporaryUrl(key, { expiresIn })` still takes a `Duration`. **Scheduler:** - `.withoutOverlapping(30)` (minutes) becomes `.withoutOverlapping({ expiresAfter: { minutes: 30 } })`. The old form is a type error, and untyped code gets a `TypeError` naming the new form. The default stays 24 hours. **Auth and session:** | Before | After | | --- | --- | | `AuthConfig.passwordTimeout` (seconds) | `passwordTimeoutSeconds` | | `AuthConfig.resetExpire` (minutes) | `resetMinutes` | | `AuthConfig.resetThrottle` (seconds) | `resetThrottleSeconds` | | `AuthConfig.emailChangeThrottle` (seconds) | `emailChangeThrottleSeconds` | | `SessionConfig.lifetime` (minutes) | `lifetimeMinutes` | | `confirmedPassword({ seconds: 60 })` | `confirmedPassword({ maxAge: 60 })` or `{ maxAge: { minutes: 1 } }` | | `TWO_FACTOR_MAX_AGE` | no longer exported; write `{ hours: 24 }` | | `error.retryAfter` of a `throttled` failure | `error.retryAfterSeconds` | - Reading an old config key throws a `TypeError` naming the new one, and `confirmedPassword({ seconds })` is refused. - `twoFactor({ maxAge })` takes a `Duration` too; a number still means seconds, and the default stays 24 hours. - A `throttled` failure comes from `attempt()`, two-factor, passkeys and password checks. An app that copied the kit's auth controllers renames the field there. - Every window keeps its value. #### Medium: The client's spans of time name their unit, in milliseconds *Likelihood of impact: medium — apps on `@marmeon/react` that set prefetch, progress, pending, debounce or poll times.* Rename the options; the values stay milliseconds, and TypeScript reports every place that still uses an old name. | Before | After | Where | | --- | --- | --- | | `cacheFor` | `cacheForMs` | ``, `router.prefetch()`, `PrefetchOptions` | | `delay` | `delayMs` | `progressBar()`, `showProgress()` (`ProgressOptions`) | | `delay: 300` | `delayMs: 300` | `usePending()`; `delay: 'short'` stays | | `debounce` | `debounceMs` | `useQueryState()` (`QueryStateOptions`), the `validate` option of `useForm()` and `
` (`LiveValidationOptions`) | | `searchDebounce` | `searchDebounceMs` | `useTable()` (`TableControllerOptions`) | | `poll` | `pollMs` | `` | | `HOVER_PREFETCH_DELAY` | `HOVER_PREFETCH_DELAY_MS` | `@marmeon/http/client/adapter` | `usePoll` and `createPoll` take their interval in the options: ```ts // before usePoll(15_000, reloadOptions, { keepAlive }); createPoll(run, 1000, options); // after usePoll({ intervalMs: 15_000, keepAlive }, reloadOptions); createPoll(run, { intervalMs: 1000, ...options }); ``` The old form is a type error and throws a `TypeError` naming `{ intervalMs }`. An interval that is not finite, not above 0 or above 2 147 483 647 ms throws C5, in `usePoll` on the server too. ### Data and the queue #### High: The generated table types declare primary keys *Likelihood of impact: high — every app with `@marmeon/database`.* `bootstrap/database.d.ts` is format 3: it fills a new `PrimaryKeys` interface with the primary key of every table, and a repository takes its key from the schema instead of a column named `id`. A `json()` column is written as `JsonColumn<'table.column'>`, which reads as `Json` unless the app declares a type for that key (below). - Run `marmeon db:types` once and commit `bootstrap/database.d.ts`; `marmeon db:types --check` fails with "generated by another version" until then. - Replace `KeyOf<'table'>` with `PrimaryKeyOf<'table'>`. - A table you type by hand declares its key, or `find()` and the other methods that take a key refuse it in the types: ```ts declare module '@marmeon/database' { interface PrimaryKeys { orders: 'id' } } ``` - A table without a single-column primary key makes `find()`, `findOrFail()`, `exists()`, `update()`, `tryUpdate()`, `delete()`, `forceDelete()`, `restore()`, `relation()`, `chunk()` and the route binding throw a `TypeError`; there is no fallback to `id`. Use `query()` for such a table. - A table that raw SQL (`schema.raw()`) created is unknown to a managed connection, so its repository has no key: create the table with `schema.create()`, or use `query()`. - A route binding checks the value against the key column first: digits for an integer, a UUID for a `uuid`, at most 255 characters for anything else; any other value answers 404. A key of a timestamp, boolean, JSON or decimal column needs a `static routeKeyPattern` on its repository, and so does a text key longer than 255 characters. - A scoped route binding compares with the column the foreign key references, and a scope column that is no foreign key is a `TypeError`. - A `json()` column can carry the type of its value. Declare it once and `Row<…>`, `select` and `find()` read the column as that type instead of `Json`; a declared type that is not JSON (a `Date`, a class, a function, `bigint`, `unknown`) reads as a message that names the key, and an open part is typed as `Json`. The type is a promise: nothing checks the shape of a value on read, and writes still take a string (`JSON.stringify`). Nothing changes for a column without a declaration. See [a JSON column's type](https://marmeon.com/docs/queries.md#a-json-columns-type). ```ts declare module '@marmeon/database' { interface JsonTypes { 'surveys.options': readonly string[] } } ``` #### Low: Postgres connections time out after 10 seconds and keep UTC *Likelihood of impact: low — apps whose Postgres server is slow to accept a connection, or that set `TimeZone` through `?options=`.* - The pool and the migration lock give up connecting after 10 s with D11. If the server needs longer, e.g. a paused serverless database, set `?connect_timeout=` in `DB_URL`: whole seconds from 0 to 2147483, and `0` waits without a limit, as before. Any other value stops the start, naming it. - A full pool that cannot hand out a connection in that time fails with D11 "no free connection; raise `DB_POOL_MAX` or shorten transactions". - A `DB_URL` with its own `?options=` keeps them, and UTC is set after them, so a `TimeZone` among them is replaced by UTC. #### Low: queue.using(trx) follows its own transaction, and a stopped job keeps its attempt *Likelihood of impact: low — apps that dispatch through `queue.using(trx)` or listen to `JobQueued`.* - Dispatch a `sync` or unique job through `queue.using(trx)` only with the `trx` that `connections.transaction()` hands you. With a transaction you began yourself (`db.transaction()`, `db.startTransaction()`, a second connection) or a derived handle (`trx.withSchema()`), such a dispatch throws `QueueError`, in `Queue` and in `QueueFake`. - A listener on `JobQueued` runs after the commit, and not for a transaction you began yourself. - A job cut off by a worker stop (past `--stop-timeout`) goes back without counting its attempt, so it no longer lands in `failed_jobs`. A worker killed outright or a job that times out still counts it. #### Low: A transaction takes one of three isolation levels *Likelihood of impact: low — apps that pass `isolationLevel: 'snapshot'` or `'read uncommitted'`.* `TransactionOptions.isolationLevel` takes the exported `IsolationLevel`: `'read committed'`, `'repeatable read'` or `'serializable'`. Anything else is a type error and throws a `TypeError` before the transaction begins. #### Low: A lock that waits returns a Result *Likelihood of impact: low — apps that call `lock.block()`.* `lock.block(wait, callback)` returns `ok(result)`, or `err({ kind: 'timeout' })` without calling the callback, like `lock.get(callback)` returns `err({ kind: 'locked' })`. `LockTimeoutError` is gone. Returned from a `transaction()` callback, `timeout` rolls the transaction back. `block()` always takes the callback now, and throws a `TypeError` without one: the protected code never runs without the lock. To hold a lock without a callback, take it with `get()` and release it yourself. ```ts // before const report = await cache.lock('report', 60).block(5, () => this.#reports.build()); // after const report = await cache.lock('report', 60).block(5, () => this.#reports.build()); if (!report.ok) abort(423); ``` #### Low: Queue sizes and unique jobs in tests name what they mean *Likelihood of impact: low — apps that count a queue on another connection, or assert on unique jobs in tests.* - `queue.size(name, connection)` becomes `queue.size(name, { connection })`. `queue.size('redis')` counted the queue named `redis`; a second string is now a type error and throws. - In tests, the `unique` of a dispatched job reads `forSeconds` instead of `for` (type `DispatchedUnique` of `@marmeon/queue/testing`). #### Low: The where of unique() and exists() is typed by the repository's query *Likelihood of impact: low — apps that pass `where` to `unique()` or `exists()`.* The `where` callback gets the repository's own query type instead of `any`. A wrong column name, a value of another type, or a callback that does not return the query (an `async` one, one without `return`) is a compile error. Fix the column or the value, or run `marmeon db:types` if the column is new. `ctx` stays `any` unless you annotate it with the context the request has, such as `ctx: HttpContext }>`, which then also checks `ctx.params`. Run-time behaviour does not change. There is no way back. See [database rules](https://marmeon.com/docs/validation.md#database-rules-and-why-they-never-run-live). #### Low: Equal live hints of one transaction go out once *Likelihood of impact: low — apps that call `broadcast.refresh()` per row inside a transaction, and their tests that count hints.* Inside a transaction, `refresh()` registers its hint on the outermost transaction, and after the commit equal hints go out once: the same channel, the same `only` in any order, leaving out the same tab. A hint from a savepoint that rolled back is dropped; outside a transaction every hint goes out at once, as before. The channel's sequence rises once per transaction, so an open tab reloads once. A test that expected n hints for n rows changed in one transaction expects one, in `assertRefreshed({ times: n })`, `app.live(path).waitFor(n)` and `app.broadcast.refreshed(channel)`. There is no way back. See [sending hints](https://marmeon.com/docs/realtime.md#sending-hints). #### Medium: A Redis queue name must not collide with the keys of another queue *Likelihood of impact: low — apps on the Redis queue driver with a queue whose name ends in `:delayed` or `:reserved`.* On the Redis driver, a queue named `a:delayed` used the key `queues:a:delayed` as its list, which is queue `a`'s delayed set; the same held for `:reserved`. A push or a reserve failed with `WRONGTYPE` or mixed the jobs of two queues. The driver now refuses such a name before any Redis call, in push, reserve, size, counts, ack, release and fail, with a message that names the queue, the suffix and the queue it would collide with. `a:delayed:x` and `delayed` stay allowed; the database and memory drivers are unaffected. - A default queue with such a name (`QUEUE_REDIS_QUEUE`) stops the app at the start with Q4. - A refused name that is already in the queue registry is no longer listed or taken, so jobs queued under it are not worked. `queue:size`, the devtools page and the worker's look at other queues keep working. - Rename the queue, then move its jobs with the workers stopped: 1. Pick a name no queue uses yet. Move `queues:x:delayed` to `queues:x-delayed` with `RENAMENX`, and do the same for its `:delayed` and `:reserved` keys if they exist. `RENAMENX` refuses an existing target; `RENAME` would overwrite it and lose its jobs. Check `TYPE queues:x:delayed` first: only a `list` belongs to `x:delayed`; a `zset` is queue `x`'s delayed set and stays. 2. Run `SREM queues x:delayed` and `SADD queues x-delayed`. There is no way back. See [the queue drivers](https://marmeon.com/docs/queues.md#drivers). ### Configuration and drivers #### Medium: A size in an environment variable names its unit *Likelihood of impact: medium — apps that set `SERVER_MAX_BODY_SIZE`, `MAX_BODY_SIZE` or `HASH_ARGON_MEMORY`, or pass `maxBodySize`.* An old name that is still set stops the start and names the new one, with the conversion. Check `.env`, `.env.test`, the deployment settings and CI. | Before | After | Value | | --- | --- | --- | | `SERVER_MAX_BODY_SIZE=8m`, `MAX_BODY_SIZE` | `SERVER_MAX_BODY_MB=8` | whole MiB, 1 to 1024 | | `HASH_ARGON_MEMORY` | `HASH_ARGON_MEMORY_KB` | KiB, unchanged | | `createHttpKernel(app, { maxBodySize })` | `createHttpKernel(app, { maxBodyBytes })` | bytes | | `ServerConfig.maxBodySize` | `ServerConfig.maxBodyBytes` | bytes | | `DEFAULT_MAX_BODY_SIZE` (`@marmeon/router`) | no longer exported; the default stays 8 MB | | Divide a value in bytes by 1,048,576; it must come out as a whole number. A limit under 1 MB, or one that is no whole number of MB, goes through `createHttpKernel(app, { maxBodyBytes })`. #### Low: A mail transport of your own returns the provider's message id *Likelihood of impact: low — apps with a mail transport or a `Mailer` of their own, or code that reads `MailConfig`.* - A transport's `send()` resolves with a `MailReceipt`, `{ messageId }`, where `messageId` is `undefined` when the provider gives none. It may have a `close()`. - A class that implements `Mailer` resolves `send()` with a `SentMail`: the composed message and its `messageId`. - `MailConfig.mailer` is `MailConfig.driver`, and the boot warnings of the log mailer carry the log context key `driver`. - A provider can bring a transport with `static mailDrivers = { name: factory }` and `MAIL_DRIVER=name`; binding `MailTransport` in the container still works. A `MAIL_DRIVER` that no provider brought stops the start with Q8 and lists the known names. #### Low: The Vite plugin has no pages and lang options *Likelihood of impact: low — apps that pass `pages` or `lang` to `marmeon()` in `vite.config.ts`.* Remove both options; passing either throws a `TypeError`. Views live in `modules//views/` (`.tsx`), language files in `lang/` and `modules//lang/`. A custom glob only half worked before: the route types and the server's translator read the default places. #### Low: createPinoLogger() takes its destination and app as options *Likelihood of impact: low — apps that build their own pino logger.* `createPinoLogger(config, stream, app)` is `createPinoLogger(config, { destination: stream, app })`. A stream as the second argument, or a third argument, throws a `TypeError`. #### Low: The kernel's asset version is assetVersion *Likelihood of impact: low — apps that pass `version` to `createHttpKernel()`.* `createHttpKernel(app, { version })` is `createHttpKernel(app, { assetVersion })`, the name of `ServerConfig.assetVersion` and `SERVER_ASSET_VERSION`. The old key throws a `TypeError`. #### Low: Vite's base is / or an absolute URL, and the server links a page's chunks under it *Likelihood of impact: low — apps that set `base` in their Vite config.* The server serves the build under `/` only, so a path base (`/static/`) or a relative one (`./`) never worked without a proxy. `marmeon build` now refuses both when Vite resolves its config, and a build made earlier with such a base stops `marmeon start`, with the value named. An absolute `http(s)` URL that ends in `/` and carries no credentials, query or fragment is accepted; the server then prefixes every modulepreload and page stylesheet with it, where it used to link them as `/assets/…` on its own origin, which answered 404 when the assets lived elsewhere. - Build with `base: '/'` (the default) or with the absolute URL where the assets are hosted. Apps that leave `base` alone change nothing. - A CDN base: the CDN has to send `Access-Control-Allow-Origin`, because every tag is `crossorigin`; and a policy without the nonce needs the origin in `script-src` and `style-src`. There is no way back. See [the base](https://marmeon.com/docs/vite.md#the-base). #### Low: A session codec of your own has no encrypts *Likelihood of impact: low — apps that bind a `SessionCodec` of their own.* `SessionCodec` is `seal()` and `open()`; `encrypts` is gone, and nothing read it. Remove it from your codec: an object typed as `SessionCodec` with `encrypts` no longer compiles. ```ts // before const codec: SessionCodec = { encrypts: true, seal, open }; // after const codec: SessionCodec = { seal, open }; ``` ### Routes and pages #### Low: A route pattern reads the same everywhere, or the start stops *Likelihood of impact: low — apps with unusual route patterns.* A pattern that the server, links, the bind check and the sitemap could read differently stops the app with H13, which names the pattern: - a parameter name is letters, digits and `_`, starting with a letter or `_` (`:user_id`, not `:user-id`); - a parameter fills a whole segment (not `/a/:x{[a-z]+}.json`); - only the last parameter may be optional (not `/a/:x?/b`); - a name may not repeat in one pattern; - a constraint must be closed and may not name a group. `ExtractParams` reads a parameter only after `/` or at the start of the path, so `/files/v:version` gives no key, as at run time. #### Low: A file in a list, a union or an optional object stops the start *Likelihood of impact: low — apps with an `upload()` field that is not a field of its own.* A body schema with `upload()` inside a list (`r.array`, `r.list`), a union, a field added with `.when()`, or an optional, nullable or defaulted object at any depth stops the start with S2, naming the field. Such a schema never worked: the submit answered "invalid" without saying why. Give each file a field of its own, in the body or in an object that is always there; `upload(…).optional()` and `.nullable()` on the field stay allowed. A schema built by a factory is checked at its first submit instead, and answered with a 500. #### Low: twitter.image takes the shape of openGraph.image *Likelihood of impact: low — pages that set `twitter.imageAlt`.* ```tsx // before twitter: { image: '/card.png', imageAlt: 'A card' } // after twitter: { image: { url: '/card.png', alt: 'A card' } } ``` A plain `twitter: { image: '/card.png' }` keeps working. `twitter:image:alt` is written only next to an image that survives URL resolution, and a relative URL resolves against the origin of `APP_URL`. #### Low: Head keeps its server tags when the page hydrates *Likelihood of impact: low — tests that assert the head marker, default layouts with an `error` that is no component, and path-relative head URLs.* - A test that asserts `data-marmeon-head="ssr"` on a child tag of `` now sees `ssr-tag`; the title and the head fields keep `ssr`. - A default layout whose `error` is not a component fails on every page with R19, like a page's own layout. Such an app was already broken on its first error. - A path-relative head URL (e.g. `canonical="notes/1"`) resolves against the origin of `APP_URL`, not its path. Root-relative values such as `/de/x` are unchanged. - An element that `` creates gets only primitive props, never `on*`, objects or functions. Script and style get the page's nonce; their own `nonce` prop is ignored. #### Low: Once props are scoped by the page's language *Likelihood of impact: low — apps that copied the auth kit's tests.* The browser keeps a page's once props per session and language, so a switch from `/de/…` to `/en/…` sends them again. An app's code changes nothing. An app that copied the kit's tests keeps an old test in `modules/auth/auth.test.ts` ("the app name in the layout … comes with the first page only") that now fails: take the current version from the kit (`marmeon make:auth --force` for the test file, or copy it). #### Low: block() on a route takes lock and wait by name *Likelihood of impact: low — routes that pass arguments to `.block()`.* `.block(5, { seconds: 2 })` becomes `.block({ lock: 5, wait: { seconds: 2 } })`: two spans of time side by side were easy to swap. `.block()` without arguments is unchanged, and so are the defaults (`lock` 10 seconds, `wait` as long as `lock`). A number as the first argument, a key it does not know, or a second argument throws a `TypeError`. #### Low: Flash data is put with session.flashData() *Likelihood of impact: low — apps that call `session.flash()`.* `session.flash(key, value)` is `session.flashData(key, value)`. "Flash" now always means the message that `redirect().flash()` sends and `useFlash()` shows; flash data is read with `session.get()` on the next request, like `redirect().with()`. There is no alias, so TypeScript points at every call. #### Low: WhenVisible takes reload, and resolveRoute() takes options *Likelihood of impact: low — pages that pass `params` to ``, and client adapters of your own.* - `` is ``. On every other component `params` are route parameters. `params` on `` throws a `TypeError` naming `reload`. - For client adapters: `resolveRoute(manifest, name, params, query, { locale })` is `resolveRoute(manifest, name, { params, query, pageLocale })`. More arguments, or a key it does not know, throw a `TypeError`. `Navigator.cachedPages` is internal. #### Low: The error pages and the layer backdrop live in the system module *Likelihood of impact: low — apps with their own error page (`modules/errors/views/`) or layer backdrop (`modules/layers/views/Backdrop.tsx`).* Move `modules/errors/views/` to `modules/system/views/errors/` and `modules/layers/views/Backdrop.tsx` to `modules/system/views/layers/Backdrop.tsx`, then run `marmeon route:types`. The views are named `system/errors/Error`, `system/errors/` and `system/layers/Backdrop`: a test that asserts `assertPage('errors/Error')` asserts `system/errors/Error`, and a `layout(name)` that compares names gets the new ones. Until the files are moved, `marmeon dev`, `build`, `route:types` and `check` stop with K14 and name the new path. #### Low: A binder's context is typed by the state of its route *Likelihood of impact: low — apps with a route binder of their own that reads `ctx`, and code that calls `resolveRouteBinding()` itself.* `RouteBindingContext` types `ctx` by the state the binder needs; without the argument it carries no state, where it was `any`. - A binder that reads `ctx.user`, or anything else a middleware adds, declares it: `resolveRouteBinding(value: string, { ctx }: RouteBindingContext)`. `bind()` then compiles only on a route behind `authenticate()`, and the message names the missing keys. - Code that calls `resolveRouteBinding()` itself passes a context whose `params` are the raw strings, or uses `findByRouteKey(value)`. `findByRouteKey()` hands the binder a context that throws a `TypeError` naming the repository when read. - Binders that read only `scope`, `with`, `request` or `params` are unaffected. There is no way back. See [your own binder](https://marmeon.com/docs/routing.md#your-own-binder). #### Low: A form's field for a boolean rule is a boolean *Likelihood of impact: low — pages whose form has a field of `r.boolean()` or `r.accepted()` and set it to something other than `true` or `false`, compare it with `'on'`, or cast it.* In a form typed from its controller (`useForm('route', …)`, `useForm()`, `FormHandle`, `FormPart`) a field whose rule is `r.boolean()` or `r.accepted()` holds a `boolean`, also inside an object or a list; with `.optional()` or `.default()` it is `boolean | undefined`. The same holds for such a field in the `data` of `useAction().submit()`, and `PendingSubmission.input` types it `boolean`. A checkbox needs no cast: `checked={form.data.agree}` and `form.set('agree', event.target.checked)`. - Code that sets such a field to `'on'`, `'1'`, `1` or another spelled-out value, in `form.set()`, `setData()` or the initial data, or casts it to the rule's input type, no longer compiles: set `true` or `false`. - A check like `form.data.agree === 'on'` becomes `form.data.agree`. - A form typed directly (`useForm<{ agree: BooleanInput }>()`) keeps its type. Requests do not change: the rules still take `'on'`, `'0'` and `'1'` from a form posted without JavaScript. There is no way back. See [fields and errors](https://marmeon.com/docs/forms.md#fields-and-errors). #### Medium: A route form types number fields as numbers and defaulted fields as present *Likelihood of impact: medium — every `useForm()` form that has a number rule or a `.default()` field.* `form.data.count` was `number | \`${number}\``, and a field with `.default()` was optional in `form.data` and `initial`. Now: - A number rule's field is `number`. Where the field may be missing (optional, nullable or defaulted), it also takes `''` for an empty input. - A defaulted field is required in `form.data` and `initial`, inside objects, lists and union members too. - A pending submission's `input` is what was sent: an action's data as passed, or a route form's fields. - `useAction()` bodies are unchanged. `FormOutputOf` and `ActionFields` are exported. What an app does: set numbers (`e.target.valueAsNumber`), or `''` for an empty optional field; add every defaulted field to `initial`, and drop `?? []` fallbacks. In an app from the starter kit, both two-factor forms need `{ code: '', recovery_code: '' }`. `pnpm typecheck` lists each place. There is no way back. #### Low: A later .when() sees the fields of the .when()s before it *Likelihood of impact: low — schemas that put a condition on a conditional field.* A condition on a field that an earlier `.when()` adds never held, so its fields were neither checked nor in the body. Now a later `.when()` sees the fields of the ones before it, and its fields are checked and kept. Send the fields the form shows, or change the condition. There is no way back. #### Low: A standalone describeAccess() check sees HttpContext, not any *Likelihood of impact: low — checks written apart from their route that read params or middleware state.* `describeAccess((ctx) => …, label)` outside `.authorize()` gave `ctx: any`, so a typo in `ctx.params` compiled. Such a check now sees `HttpContext`, and it must return `boolean` or `Promise`. A check written inside `.authorize()` keeps the route's bound context. Write the check inside `.authorize()` after the `.bind()` it reads, annotate `ctx` (`HttpContext`), or pass the type argument. There is no way back. #### Low: An island request reaches only a controller that returns island() *Likelihood of impact: low — islands built outside a controller method, module packages with island controllers, and tests that stand in for an island.* A request with the island header used to reach any route, run its middleware, and only then learn whether the handler returned an island. Now the loader marks the controllers whose own methods call `this.island(…)` or `island(…)` imported from `@marmeon/http`, in development, in Vitest and, through `.marmeon/injections.json`, in production. An island request to any other route answers 404 before a middleware runs, and a marked route answers a page request with 404 after the global middleware. - A closure route or a helper outside the controller that returns `island()`: write it as a controller class that calls `this.island(…)` in one of its methods. - `island` imported through a module of the app that re-exports it: import it from `@marmeon/http` in the controller's own file, or call `this.island()`. - A module package that ships island controllers: rebuild it with `marmeon package:build` from this version; a package built before answers 404 for its islands. - A controller that returns a page or an island depending on a branch: split it into two routes. - Tests: a fixture that stands in for an island needs such a controller too; a test that expected a login redirect on a direct call of an island URL expects 404. `marmeon route:list` shows island routes. There is no way back. #### Low: A resolver you pass to the router takes a class or a token *Likelihood of impact: low — code that passes its own `resolve` to `validate()`, `new Router()` or `dispatch()`.* A route's checks (`authorize`, `afterAuthorize`, `describeAccess`) and its hooks can now resolve a token, not only a class: `resolve(Clock)` or `resolve(Translator)` works where only `resolve(SomeClass)` did. A hook can read `session.readOnly` to tell whether the request may change the session, and runs after the locale is set, so a hook after `RequestLocale.use()` already speaks the new language ([after the checks](https://marmeon.com/docs/routing.md#after-the-checks)). An app that uses the defaults has nothing to do. A resolver you pass yourself, to `validate(schema, value, { resolve })`, `new Router({ resolve })` or `dispatch(…, { resolve })`, is now typed `(key: Constructor | Token) => T`: ```ts // before resolve: (Class) => new Class() // after resolve: (key) => container.make(key) ``` A resolver typed for classes only does not compile any more; otherwise check `typeof key === 'function'` before `new key()`. Outside an app, the default resolver refuses a token with a `TypeError` that names it. There is no way back. #### Low: A table's filters and its actions' answers are typed by name and by handler *Likelihood of impact: low — pages that type a `run()` or `runBulk()` callback with the bare `TableRunOutcome`, or a table's data by hand.* `table.filter('status')` reads the filter `status` of the props as its definition made it (a select with `options`, a date range, a `has` filter); a name the table does not define is a type error. `run()` and `runBulk()` type `outcome.data.data` as what the action's handler returns, serialized (a `Date` becomes a `string`). A handler that answers with `json(body)` types `outcome.data` as that body, without counts; a `Response` handler gives `unknown`; a redirect-only handler has no data outcome at all. - A callback typed with the bare `TableRunOutcome` no longer accepts the outcome of an action whose handler returns `json()` or a `Response`. Let the run type it, or widen it on purpose: ```ts // before — no longer compiles for such an action table.run('report', row).then((outcome: TableRunOutcome) => …); // after table.run('report', row).then((outcome) => …); const report = (outcome: TableRunOutcome) => …; ``` - A value typed by hand as `TableData` no longer fits `TableProps` for a table with actions or filters: type it as `TableProps`. - A cast such as `outcome.data.data as { at: Date }` fails, because the date arrives as a string. A hand-written `TableFilter<'a' | 'b'>` still fits, `useTable()` call sites do not change, and a bare `TableRunOutcome` is the same type as before. There is no way back. #### Low: IslandElementProps is a union of route and href *Likelihood of impact: low — components that are typed with `IslandElementProps`.* `` embeds an island whose URL the server chooses, so a page can render the panels a user may see without knowing every panel's route ([islands the server chooses](https://marmeon.com/docs/deferred-props.md#islands-the-server-chooses)). `IslandElementProps` is therefore a union of the `route` form and the `href` form. A component typed `(props: IslandElementProps)` narrows before it reads `props.route`; `href` is the other member. `Omit` no longer distributes over the members. Apps that only use `` change nothing. There is no way back. #### Medium: An island rendered with its page sees cookies only while the page is private *Likelihood of impact: medium — apps with islands on pages outside the session group, or on a guest's page, that read a cookie or the session.* An `` on a page without `StartSession` was resolved in-process with the visitor's `cookie` header. When the island's route started the session, it loaded the visitor's own, although the page had gone out as `public` with the shell: a cache could keep a signed-in visitor's data and serve it to everyone. The server now decides before it runs the island: - An island whose route starts the session, on a page that started none, loads in the browser: the server renders its `fallback`, and the island appears after hydration with the visitor's own session. Nothing runs twice. - The `cookie` header reaches an island rendered with its page only while the page is private: for a visitor whose session the store already keeps (a signed-in one, or a guest whose session holds data). On pages without `StartSession`, on a guest's page in the session group, and in apps without `@marmeon/session`, the island sees no cookies. - In development, a warning names the page route and the island route once. Pass what such an island reads from a cookie as page props, or let it load in the browser; to render a session island on the server, put its page in the session group. Check tests that expect server-rendered content from session islands on such pages. There is no way back. See [how islands load](https://marmeon.com/docs/deferred-props.md#how-islands-load). #### Low: A table's authorize must return true *Likelihood of impact: low — tables whose `authorize` returns something other than a boolean.* A table's own `authorize` was tested for truthiness, so an untyped check that returned a `Response`, an object, `1` or a non-empty string let the request through; the `boolean` type stopped it only at compile time. The page, the row actions, the bulk actions and the exports now let a request through only when the awaited check is `true`. Any other value answers 403, like `false`; a check that throws (`can()` with 403 or 404) still propagates. An `authorize` that returns a boolean changes nothing. ### Renamed exports #### Low: Names that two packages exported have names of their own *Likelihood of impact: medium — apps that import one of the names below; TypeScript reports each.* Rename the imports and type positions; there are no aliases. | Before | After | Package | | --- | --- | --- | | `RequestInfo` (type and token) | `ClientInfo` | `@marmeon/http` | | `NO_REQUEST_INFO` | no longer exported; write `{ ip: undefined, userAgent: undefined }` | `@marmeon/http` | | `RequestInfo`, `JobInfo`, `TaskInfo` | `CurrentRequest`, `CurrentJob`, `CurrentTask` | `@marmeon/core` | | `ActionException`, `VisitException` | `ActionError`, `VisitError` | `@marmeon/http/client`, `/client/adapter`, `@marmeon/react` | | `Router`, `Action` (the types of `useRouter()` and `useAction()`) | `ClientRouter`, `ClientAction` | `@marmeon/react` | | `KeyOf`, `ParamsOf`, `CheckKey` | `MessageKeyOf`, `MessageParamsOf`, `CheckMessageKey` | `@marmeon/i18n`, `@marmeon/i18n/messages` | | `Invokable`, `InvokableClass` | `CallableTask`, `CallableTaskClass` | `@marmeon/scheduler` | | `Entry` | `CacheEntry` | `@marmeon/cache` | | `ServeOptions` | `ServeFileOptions` | `@marmeon/storage` | | `ColumnOf` | `RepositoryColumnOf` | `@marmeon/validation` | | `PasskeyConfigError` | `PasskeySetupError` | `@marmeon/auth/passkeys` | `ActionError` and `VisitError` are types, not classes, so there is no `instanceof` to change. #### Low: PostgresConnection is PostgresConnectionOptions *Likelihood of impact: low — apps that import the type of a Postgres connection's options.* The options of a Postgres connection (`driver: 'pgsql'`, `url`, `host` …) are `PostgresConnectionOptions`, like `RedisConnectionOptions` and `QueueConnectionOptions`. `Connection` stays the connection itself. There is no alias. ### Packages that left experimental #### Low: The data tables have names of their own *Likelihood of impact: low — apps with `@marmeon/table`, `@marmeon/react/table` or `@marmeon/react/table-tanstack`.* | Before | After | | --- | --- | | `Table` (what `defineTable()` returns) | `DataTable` | | `Tables` (the injected service) | `DataTables` | | `RowOfTable` | `DataTableRow` | | `RowOf` of `@marmeon/react/table` and `@marmeon/table/client` | `TableRowOf` | | `Column` | `ColumnDefinition` | | `CheckKey` | `CheckColumnKey` | | `VisibilityCheck` | `TableVisibilityCheck` | - The `RowOf` helper of `@marmeon/table` is no longer exported: read a row with `DataTableRow`. `KeyName` and `Visibility` are no longer exported either. - The constructor of `DataTables` is internal: take the service by injection. #### Low: @marmeon/live names the units of its config and its test reader *Likelihood of impact: low — apps that read `LiveConfig` or test live updates.* - `LiveConfig.heartbeat` and `retry` are `heartbeatSeconds` and `retryMs`; the environment variables are unchanged. - In tests, `BroadcastRecorder` is `BroadcastTester`, and `stream.retry` of a `LiveStreamReader` is `stream.retryMs`. The timeout of `hello()` is a `Duration`, so a number is seconds ([spans of time](https://marmeon.com/docs/upgrading.md#medium-spans-of-time-are-seconds-or-a-duration-and-values-handed-back-name-their-unit)). `stream.waitFor(until, timeout, what)` becomes `stream.waitFor(until, { timeout, what })`, with `timeout` a `Duration`; `waitFor(1)` is unchanged. The constructor of `LiveStreamReader` is internal. - `LiveBackend` and `LiveMessage` are no longer exported; they have no replacement. #### Low: @marmeon/devtools has names of its own *Likelihood of impact: low — apps that import from `@marmeon/devtools` or read its entries.* - `DevtoolsConfigError` is `DevtoolsSetupError`. - Each content type is named after its entry: `MailContent` is `MailEntryContent`, `RequestContent` is `RequestEntryContent`, and so on; the embedded `ErrorContent` is `ErrorDetails`. The keys of the entries (`'mail'`, `'exception'` …) stay. - `FileStore` and `FileStoreOptions` are `FileDevtoolsStore` and `FileDevtoolsStoreOptions`. `MemoryStore` is no longer exported: type a variable `DevtoolsStore`. - A reader of job entries reads `content.delaySeconds` instead of `content.delay`. - `DevtoolsTester` is exported as a type only (`import type`); `createTestApp()` makes it, and `app.devtools` stays. - Entries written before the upgrade may show incompletely; `marmeon devtools:clear` empties them. #### Low: The client adapter API is stable and smaller *Likelihood of impact: low — client adapters of your own; apps on `@marmeon/react` change nothing.* - `pageQuery(page)` is `pageQueryOf(page)`. - `@marmeon/http/client/adapter` no longer exports `loadLiveValidation`, `loadPrefetch`, `loadViewTransitions`, `withoutDefaults`, `mergePage` and `ResetProps`. For the two remembered-field patterns, see [the remembered-field patterns](https://marmeon.com/docs/upgrading.md#low-the-deprecated-remembered-field-patterns-are-gone). - `defineFeature`, `Feature.setup`, `FeatureHost`, `slot`/`Slot`, `LayerHost`, the members of `LayerStack` but `list`, and the constructors of `RegionOwner`, `Region`, `LayerStack` and the feature classes are internal: an adapter uses the features the core ships. - `islands.region()` refuses an owner that this navigator did not make with a `TypeError`, and `RegionOwner.live` is a `ReadonlyMap`. ### Internals moved #### Low: Undocumented machinery leaves the stable API *Likelihood of impact: low — apps that imported names no docs page names.* One rename: `ReadOnlyViolation` (`@marmeon/http`) is `ReadOnlyError`; its code stays H6. Everything else below was undocumented; use the documented API instead. - **`@marmeon/http`:** no longer exported from the main entry: `CONNECTION_HEADER`, `LIVE_PATH`, `LiveSigner`, `DOCUMENT_HEADER`, `SESSION_PATH`, `INTENDED_KEY`, `OLD_INPUT_KEY`, `flashableInput`, `jsonResponse`, `PageSession`, `AssetVersion`, `LiveDeclaration`, `browserRoutes`, `BrowserRoutes`, `Flasher`, `FlashEntry`, `PropOrigins`, `staticView` (now internal), and `addFlash`, `addLive`, `carryLive`, `withLiveMethod`, `toLayer`, `compilePolicy`, `epochOfResolver`, `SessionEpoch`, `SessionEpochController`, `SessionEpochAnswer`, `TabSyncMessage`, `TAB_SYNC_CHANNEL`, `LIVE_CHANNEL`, `mergeOf`, `propKind`, `resolveProp`, `ResolvedPage`, `PartialReload`, `OnceContext`, `ReadOnlyOptions`, `WritePermit`, `ERRORS_KEY`, `httpSolutions`, `BrowserRoute`, `HiddenReason`. `@internal`: `RedirectResult.toResponse()` and `CloseLayerResult.toResponse()`, `SharedData.entries/resolve/liveChannels`, `Prefetches.landed()/size`, and `Session.queueFlash/takeFlash` in `@marmeon/session`. Instant visits stay available through `` and `app.placeholder()`. - **`@marmeon/core`:** no longer exported from the main entry: `MAX_ENTRY_BYTES`, `ENCRYPTED`, `currentTransaction`, `REDACTED_KEYS`, `runTransaction`, `rollBackOnErr`, `missingListenerQueue`, `InjectionWarning`, `NODE_ENVIRONMENTS`, `DOTENV_MARKER`, `resolveEnvironment`; the last three are internal in `@marmeon/core/environment` too ([the last machinery](https://marmeon.com/docs/upgrading.md#low-the-last-machinery-of-the-services-leaves-the-api)). `readEnvFile` is exported from no entry. `Container.onWarning()` and `Container.warnings` are `@internal`. Ask about a transaction with `inTransaction()`. - **`@marmeon/router`:** no longer exported: `joinPaths`, `queryInput`, `issueOfFields`, `nothingToValidate`, `attributeName`, `parseCookies`, `serializeCookie`, `createNonce` (use `ctx.nonce()`), `messageOf`, `NOT_LIVE`. `Router.dispatch()` and `dispatchNotFound()` with their types `DispatchInput`, `DispatchOptions` and `ResponseFactory` are internal: a server of your own uses `createHttpKernel()`, and tests use the test app. The constructors of `Route` and `RouteDefinition` are `@internal`. - **`@marmeon/validation`:** `RuleDefinition`, `RuleStep`, `BuildContext` and `Engine` are no longer exported; the `Rule` constructor, `~rule`, `~engine` and `with` are `@internal`. `~standard` is unchanged. - **`@marmeon/database`:** a migration uses the builder's methods (`table.string()`, `table.index()` …), not `Blueprint`'s lists or `seal()`; the constructors of `Blueprint`, `Column` and `PendingFactory`, `Column.spec` and `allIndexes()` are `@internal`. The running methods of `Migrator` (`migrate`, `rollback`, `reset`, `fresh`, `dropAllTables`, `connections`) are `@internal`: run `marmeon migrate`, or, where a call must stay, pass `{ onRun, … }` as its only argument. `status()`, `changed()`, `missing()`, `projection()` and `files()` stay public. `SchemaMarker`, `MigrateOptions`, `MigrationRun`, `UnknownSchema`, `TypeGenerator` and `Rendered` are no longer exported. - **`@marmeon/queue` and `@marmeon/notifications`:** `JobRunner`, `PayloadCipher`, `Prepared`, `WorkerDependencies`, `NotificationDeliverer`, `DelivererDependencies`, `PendingDelivery`, `NotificationRegistry` and `RecipientRegistry` are no longer exported. `QueueConnections.runner()` and `cipher()` and the constructors of `Worker` and `SendQueuedNotification` are `@internal`; get a worker with `app.make(QueueConnections).worker(…)`. - **`@marmeon/auth`:** `PasswordHasherInternals` is no longer exported, and `new PasswordHasher(options)` takes only its options. - **`@marmeon/server`, `@marmeon/testing`, `@marmeon/table`, `@marmeon/storage`, `@marmeon/devtools`:** build test responses with `createTestApp()`, table builders with `column()`/`filter.*`/`action()`/`bulk()`/`exportCsv()`, and render pages with the kernel's own renderer: the constructors of `TestResponse`, `PendingTestResponse`, `ColumnDefinition`, `Filter`, `RowAction`, `BulkAction` and `TableExport`, `TestResponse.from` and `KernelOptions.renderer` are `@internal`, and `PageRenderer`, `PageRenderOptions`, `RenderFailureDetails`, `CookieCrypto` and `SessionAccess` are no longer exported. `TemporaryUploads`, `TargetRequest`, `UploadTarget`, `UploadSource` and `UploadsOptions` are no longer exported, and the constructors of `TemporaryUpload` and `RejectedUpload` are `@internal`. `checkS3Sdk` is not needed. `StorageFake` no longer extends `StorageManager` (never importable); its public members are unchanged, only the protected `build()`/`memory()` are gone. - **`marmeon`:** `run` from `marmeon/main` is no longer API; only the launcher calls it. #### Low: Auth events take the user, the details and the time; service constructors are internal *Likelihood of impact: low — apps that build auth events in tests or fakes, or build a framework service with `new` or extend one.* `new SignedIn(user, remember, at, { via, ip, userAgent })` becomes `new SignedIn(user, { remember, via, ip, userAgent }, at)`, and `new TwoFactorChallengeFailed(user, at, details)` becomes `new TwoFactorChallengeFailed(user, details, at)`. The event objects keep their fields. An app gets the framework's services from the container, and tests get the fakes from `createTestApp()`, so their constructors are no longer stable API: - **`@marmeon/auth`:** `Auth`, `TwoFactor`, `Passkeys`, `EmailChange`, `PasswordBroker`, `AccountSessions`, `Gate`, `NoStoreWhenSignedIn`, `EmailVerification`, `TwoFactorStore`, `PasskeyStore`, `DatabaseAccessTokens`, `DatabasePasswordResetTokens`, `DatabaseSignIns`. The symbol-keyed members of `Auth` and `AccountSessions` are internal too. `DatabaseEmailChanges` keeps its constructor. - **`@marmeon/session`:** `Session`, `StartSession`, `VerifyCsrfToken`, `ShareErrorsFromSession`, `UserSessions`, `SessionLottery`. - **`@marmeon/http`:** `CheckAssetVersion`, `ClearClientHistory`, `EncryptCookies`, `UrlSigner`, `ValidateSignature`. - **`@marmeon/core`:** `ErrorReports`, `EventDispatcher`, `ConsoleLogger`. A logger of your own implements `Logger` rather than extending `ConsoleLogger`. `TransactionFrame` is no longer exported at all ([the last machinery](https://marmeon.com/docs/upgrading.md#low-the-last-machinery-of-the-services-leaves-the-api)). - **`@marmeon/database`:** `Migrator`, `Factories` (`Seeding` is no longer exported at all, [more names](https://marmeon.com/docs/upgrading.md#low-more-names-only-the-framework-used-leave-the-api)). **`@marmeon/cache`:** `RateLimiter`, `CacheHealthCheck`, `LimitLiveValidation`. **`@marmeon/i18n`:** `Locales`, `Translators`. **`@marmeon/redis`:** `RedisConnection`. - **`@marmeon/queue`, `@marmeon/storage`, `@marmeon/notifications`:** `QueueConnections`, `QueueHealthCheck`, `QueueFake`, `StorageFake`, `NotificationFake`, `Inbox`. `NotificationStore` is no longer exported at all ([the last machinery](https://marmeon.com/docs/upgrading.md#low-the-last-machinery-of-the-services-leaves-the-api)). - **`@marmeon/scheduler`:** `Scheduler`, and its methods `checkProcess()`, `lockWarning()` and `releaseHeld()`; run `marmeon schedule:work`. Replace `new Gate(…)` with `container.make(Gate)` (or take it by injection), and a fake built by hand with the one `createTestApp()` installs. #### Low: More names only the framework used leave the API *Likelihood of impact: low — apps that imported a helper no docs page names.* An app that imported one of these gets a type error. Where an app has a use for it, the replacement is named: - **`@marmeon/core`:** `deprecated` is imported from `@marmeon/core/deprecation` only. `LOOPBACK_HOSTS`, `devSecured`, `devEnvironment`, `forbiddenDevHost` and `notInDevelopment` leave `@marmeon/core/dev`; `devHosts`, `devOnly` and the two host checks stay. - **`@marmeon/http`:** `ActionParamsOf` is `ParamsOf`, and `ActionQueryOf` is `QueryParams` from `@marmeon/http/page` or `@marmeon/router`. `WrappedProp`, `ClientRoutesOptions`, `isLiveValidation` and `liveValidationFields` are no longer exported; `toSearchParams` leaves `@marmeon/http/page` and is internal everywhere ([the last machinery](https://marmeon.com/docs/upgrading.md#low-the-last-machinery-of-the-services-leaves-the-api)). - **`@marmeon/router`:** `fillPath`, `isLiveValidation`, `liveValidationFields`, `AccessProblem`, `MiddlewareProblem`, `PipelineOptions`, `RequestStateOptions`, `ValidateOptions`, `MessageOptions`, `ValidatedRequest` and `RouteEntry` are no longer exported. - **`@marmeon/auth/testing`:** `authenticatedToken` is no longer exported; sign in with `actingAs(user, { guard: 'api' })`, or create a token with `create()` of the `AccessTokenStore` (`app.make(AccessTokenStore).create(user.id, name, { abilities, expiresIn: null })`; `expiresIn` takes a `Duration` or `null` for a token that never expires). - **`@marmeon/database`:** `Seeding` is no longer exported; run seeders with `marmeon db:seed` or the test app's `seed` option. - **`@marmeon/i18n`:** `CurrentLocale` and `createTranslate` are gone, and `Messages` is imported from `@marmeon/i18n/messages` only. - **`@marmeon/cli`:** `CheckReport`, `CheckStatus`. **`@marmeon/queue`:** `CacheSource`, `JobEvents`. **`@marmeon/storage`:** `TemporaryUrls`, `UploadRule`, `RejectedUpload`. **`@marmeon/notifications`:** `AnyRecipientResolverClass`. **`@marmeon/mail`:** `compose`. None has a replacement an app needs. #### Low: The last machinery of the services leaves the API *Likelihood of impact: low — apps and tests that built a framework service with `new`, or called a member or imported a name no docs page names.* What the container or `createTestApp()` builds, and what only the framework calls, is internal. Take services from the container and fakes from the test app (`app.events`, `app.mail`, `app.schedule`, `app.storage` …): - **`@marmeon/core`:** the constructors of `Container`, `EnvBlock`, `EnvSchema`, `EventFake`, `HealthChecks`, `ErrorSolutions`, `Redactor` and `TransactionFinishedError` (the error class stays); `Container.isScope`, `EventRegistry.listenersFor()` and `bindingsFor()`, `EventFake.isFaked()`, `Redactor.payload()` and `fit()`, `CurrentJob.fromReporter`. Make a scope with `container.createScope()` and environment variables with `env()` and the `e.*` builders. The `container` option of `createApplication()` is internal. `TransactionFrame` and `EventDispatcherOptions` are no longer exported. `environment.problem`, `check`, `fromDotEnv` and `dotEnvDevelopmentWarning` are gone from `environment`; `isDevelopment()`, `isProtected()`, `isTest()`, `name()`, `app()` and `describe()` stay. `resolveEnvironment()`, `buildEnvironment()`, `ResolvedEnvironment`, `DOTENV_MARKER` and `NODE_ENVIRONMENTS` in `@marmeon/core/environment` (and `ResolvedEnvironment` in `@marmeon/core`) are internal: the `marmeon` launcher resolves `NODE_ENV`, an app reads it through `environment` and names a value with `NodeEnvironmentName`. `HealthReport`, `HealthCheckResult`, `ListenerQueue` and `escapeHtml` are internal: write HTML with the `html` template, which escapes every value, and read `/up/ready` by its documented JSON; `@marmeon/queue` binds `ListenerQueue`. - **`@marmeon/router`:** the constructors of `Router` and `CookieJar`, and `RouterOptions`; `CookieJar.lock()`, `useCodec()` and `queued()`, and `CookieCodec`; `RequestNonce.want()` and `forDocument()`; `MiddlewareGroups.version`; `Router.findByName()`; `RouteDefinition.routeName`, `inSitemap`, `isInternal` and `blocking`, and the `RouteBlocking` type. `matchesPath` and `urlFor` leave `@marmeon/router` and `@marmeon/router/url`, and `urlFor` leaves `@marmeon/http/page`: build a URL with `router.url(name, params, query)` or redirect with `redirect().route()`. A client adapter keeps `matchesPath` from `@marmeon/http/client/adapter`. `statusText()`, `toSearchParams()` (also from `@marmeon/router/url`), `ResponseContext`, `PageQuery`, `GET_HAS_NO_BODY` and `ISLAND_IS_GET_ONLY` are internal: read a status's text from `response.statusText`, and build a query with `URLSearchParams`. `CookieDefaults`, from `@marmeon/router` and `@marmeon/http`, is internal: `SESSION_SECURE_COOKIE` decides `Secure` for every cookie. - **`@marmeon/i18n`:** `Locales.add()` is gone; the supported locales are fixed once the app has booted, and an app adds one through a language file or `APP_LOCALES`. `Catalog.namespaces()`. - **`@marmeon/http`:** `ServerClosing`, `ReadOnly` and `ParentRequest` are no longer exported: the framework drives them, and there is no public replacement. The constructor of `CloseLayerResult` (use `closeLayer()`); `ClientHistory.cleared` and `siteData`; `CookieEncryption.isEncrypted()`. The fields of the page prop descriptors (`AlwaysProp.value`, `DeferredProp.group` and `resolve`, `MergeProp.value` and `match`, `OnceProp.resolve`, `key` and `expiresInMs`, `OptionalProp.resolve` …) are internal: create props with `always()`, `defer()`, `merge()`, `once()` and `optional()`. - **`@marmeon/session`:** `Session.start()`, `save()`, `abandoned`, `ended`, `hasFlash()`, `started`, `persists` and `regenerateToken()`; `Session.readOnly` stays public. `Session.id` and `exists` are internal too: the id is the session's secret, so never log it or key data by it. Rotate the token with `session.regenerate()`. - **`@marmeon/database`:** the constructor of `Connections`, and `isolate()`, `used()` and `verify()`; a test gets a clean database with `createTestApp(app, { database: 'refresh' })`, which isolates the `default` connection. Isolating another connection has no public replacement. - **`@marmeon/table`:** `DataTables.runAction()`, `runBulk()` and `export()`, `DataTable.definition` and the read-only fields of the builders (`isSortable`, `visibility`, `confirms`, `limit` …); `TableDefinition` and `RowAuthorization` are no longer exported. `tables.resolve()` stays. - **`@marmeon/auth`:** the writing methods of `TwoFactorStore` (`startSetup`, `confirm`, `useStep`, `consumeRecoveryCode`, `replaceRecoveryCodes`, `removeTotp`) and its `remainingRecoveryCodes()`, and those of `PasskeyStore` (`userHandle`, `create`, `updateCounter`, `suspend`, `release`, `rename`, `remove`): change factors through `TwoFactor` and `Passkeys`. The constructors of the auth events the framework dispatches — all but `SignedIn`, `Registered` and `TwoFactorChallengeFailed`. The `_auth_*` keys are no longer declared on `SessionData`; don't write them. `FACTOR_CHANGE_MAX_AGE` is no longer exported (it is 15 minutes, with no setting). `AuthConfig.protected` is gone, and reading it throws; ask `environment.isProtected()`. The constructor of `PolicyResponse`: use `allow()`, `deny()` and `denyAsNotFound()`. - **`@marmeon/cache` and `@marmeon/redis`:** the constructors of `Lock` (use `cache.lock()`), `Limit` (use `Limit.perMinute()` …), `RedisConnections` and `RedisHealthCheck`; `Limit.maxAttempts` and `decaySeconds`; `RedisConnections.inUse()`. - **`@marmeon/queue` and `@marmeon/scheduler`:** `Worker.process()`, `QueueConnections.verify()`, `cache()` and `events`, `JobRegistry.add()`; the constructors of the queue events (`JobQueued`, `JobProcessing`, `JobProcessed`, `JobReleased`, `JobFailed`); `QueueFake.listenerQueued()` (assert with `assertListenerQueued()`); the constructors of `ScheduleTester`, `ScheduledTaskFinished` and `ScheduledTaskSkipped`; `Scheduler.schedules()`, `due()`, `tick()` and `runNow()`; the constructor of `CronExpression`, and its `matches()`, `matchesHour()` and `hourRestricted`. - **`@marmeon/mail`, `@marmeon/notifications`, `@marmeon/storage`:** the constructor of `MailFake` (use `app.mail`, and don't subclass it); `NotificationStore` is no longer exported (read notifications through `Inbox`); `StorageFake.defaultDisk`, `named()`, `options()`, `verify()` and `close()`; `TemporaryUpload.extension`. `UPLOAD_TYPES` is internal: `UploadMime` names the types an upload rule accepts. - **`@marmeon/cli` and `@marmeon/devtools`:** the constructor of `Output`; `FileDevtoolsStore.directory` and `maxAgeMs`. - **Types and registries only the framework used:** `RouteLookup` (from `@marmeon/router` and `@marmeon/http`), `TaskRun` and `WallTime` (from `@marmeon/scheduler`) and `UploadProblem` (from `@marmeon/storage`) are no longer exported; drop a type import of them. `HealthChecks.add()`, `all()` and `run()` and `ErrorSolutions.add()` and `find()` are internal: register checks with `static health` and solutions with `static solutions`, and read the checks through `/up/ready`. Also internal: `ErrorReports.flush()`, `QueueConnections.find()` and `failed()` (the `queue:failed*` commands read the failed jobs), `RedisConnections.verify()` and `close()`, `NotificationChannels.make()` (`add()` stays), `FileDevtoolsStore.maxBytes`, and `redact()` from `@marmeon/core`. #### Low: Passkeys need the password, and EverySessionEnded takes the time last *Likelihood of impact: low — apps that register or remove passkeys, or build `EverySessionEnded` in tests.* - `passkeys.register(response, name, password)` and `passkeys.remove(id, password)` require the password as a string in their type, as they always did when they ran: without it the answer was `invalid-password`. An empty password gets that answer before anything is hashed. - `new EverySessionEnded(at, counts)` is `new EverySessionEnded(counts, at)`, like the other auth events; `at` is optional, and a `Date` as the first argument throws a `TypeError`. Its constructor is internal now, like those of the other events the framework dispatches: a test reads the event the framework fired from `app.events` instead of building one. ### Commands and the scheduler #### Low: The built-in command classes are no longer exported *Likelihood of impact: low — apps that import a framework command class, usually in tests or a schedule.* The command classes of auth, cache, database, devtools, notifications, queue, scheduler, session and storage are exported from no entry; a command's API is its name and flags. Run a command by its name instead: ```ts // in a test const run = await app.command('queue:retry', { args: ['all'] }); // in a schedule s.command('queue:retry'); ``` `run.code` is the exit code and `run.lines` every printed line, with `✓ ` before success and `✗ ` before error lines (docs/testing.md#running-commands). #### Low: A refused command argument exits with 2 *Likelihood of impact: low — scripts and tests that check a command's exit code.* A command that refuses an argument throws `CommandArgumentsError` and exits **2**, with the message on stderr, an empty stdout and no stack. A missing module, an existing file or a missing `--force` still exits 1. - A script that tests for exit code 1 after a wrong argument gets 2 now. This covers the `make:*` generators, `start`/`dev`, `queue:work`, `schedule:work`, `queue:retry`, `queue:forget`, `queue:prune-failed`, `schedule:test`, `migrate` and the rollback commands, `publish`, `auth:end-all-sessions`, `auth:end-sessions`, `auth:reset-two-factor`, `auth:prune-tokens`, `make:auth --adapter`, `notifications:prune` and `uploads:prune` (docs/console.md). - In tests, `app.command()` returns `code: 2` for them. - An app's own command throws `CommandArgumentsError` (from `marmeon` or `@marmeon/core`) to exit with 2. - An app that copied the kit's `end-sessions.test.ts` and `two-factor.test.ts` takes their current version: they expect 2. #### Low: dev and start are reserved for the launcher *Likelihood of impact: low — apps or packages with a command named `dev` or `start`.* The launcher always answered `marmeon dev` and `marmeon start` itself, so such a command was unreachable. Registering one now stops the app with K8: rename it. #### Low: The scheduler writes timeZone, and a task definition is read-only *Likelihood of impact: low — apps that set the time zone of a task or a schedule.* - `.timezone('Europe/Berlin')` becomes `.timeZone('Europe/Berlin')`, and `timezone` in `TaskDefinition` and `ScheduleConfig` becomes `timeZone`. `SCHEDULE_TIMEZONE` stays. - `TaskDefinition` is read-only; code that mutated one no longer compiles. - `.description()` is shown in `schedule:list` and must be one line of text; anything else is refused (Q5). #### Low: The scheduler names the time a task was due dueAt *Likelihood of impact: low — listeners on the scheduler's events or its `schedule.task` channel, and tests that read a task run.* `event.minute` of `ScheduledTaskStarting`, `ScheduledTaskFinished`, `ScheduledTaskFailed` and `ScheduledTaskSkipped`, and `minute` of `TaskResult`, are `dueAt`: a point in time in epoch milliseconds, not a minute of the hour. The same holds for `ScheduleTaskMessage`, the report on the `schedule.task` channel. In the devtools, a schedule entry reads `content.dueAt` (`assertRecorded('schedule')`, the JSON API); entries written before the upgrade still show, without their due time. A scheduler event built in a test takes `{ task, dueAt, reason, … }`; one without a numeric `dueAt` throws a `TypeError`. #### Low: modules:check and schema:project are steps of marmeon build *Likelihood of impact: low — scripts that call `marmeon modules:check` or `marmeon schema:project`.* Both are hidden commands that `marmeon build` runs, and a hidden command is no longer API: it may change in any release. `serve`, which `marmeon start` and `marmeon dev` run, stays API. Run `marmeon build`. ### Formats #### Low: schedule:list --json writes format 2 *Likelihood of impact: low — scripts that read `schedule:list --json`.* `options.overlapMinutes` is `options.overlapSeconds` (30 minutes is 1800), and each task has a `description`, a string or `null`. #### Low: The live stream carries its protocol version *Likelihood of impact: low — apps with live updates notice it once, during the rollout.* Nothing to change. The stream URL carries `v=1` and the messages between nodes carry `"v":1`; a stream request of another version gets a 204, and a message without the mark is ignored. A tab opened before the upgrade stops getting live updates until its next visit reloads it. During a rollout from 0.4, live hints between old and new nodes are lost; an end is bounded by `LIVE_MAX_STREAM_SECONDS`. ## Upgrading to 0.4.0 from 0.3.0 #### High: Upgrade with every process of the old release stopped *Likelihood of impact: high — every app.* 0.4.0 cannot run next to 0.3: it renames the session and remember-me cookies, gives API tokens a new form, marks sessions, queued jobs and the page protocol with a format version, and reads no record of the old release. Upgrade in this order ([the upgrade that stops every process](https://marmeon.com/docs/deployment.md#the-upgrade-that-stops-every-process)): 1. **Before, while 0.3 runs.** Let the queue run empty: `marmeon queue:work --stop-when-empty`, until `marmeon queue:size` shows nothing waiting or delayed (a job delayed into the future does not run empty). Retry or give up what `marmeon queue:failed` lists: failed jobs of 0.3 cannot be retried afterwards. Plan to issue every API token again, and tell your users that they sign in again. 2. **In development**, in this order: 1. Move every framework package to 0.4.0 at once: `pnpm up --latest "@marmeon/*" marmeon`. Afterwards `package.json` names every `@marmeon/*` package and `marmeon` at exactly `0.4.0`; never upgrade one alone ([how to upgrade](https://marmeon.com/docs/releases.md#how-to-upgrade)). On the first day after the release, pnpm holds the new versions back ([the first day after a release](https://marmeon.com/docs/releases.md#the-first-day-after-a-release)). 2. Rename the environment variables in the files of the repository (`.env`, `.env.test`, `.env.example`, the compose file, the CI configuration) and give Redis and Postgres the names they now require. `make:auth`, `migrate`, `db:types` and `route:types` start the app, and 0.4.0 stops at the start while an old name is set or `REDIS_PREFIX` or `DB_DATABASE` is missing (K6) ([environment variables](https://marmeon.com/docs/upgrading.md#high-environment-variables-are-named-after-what-they-configure-and-their-unit), [Redis](https://marmeon.com/docs/upgrading.md#high-an-app-with-marmeonredis-sets-app_name-or-redis_prefix), [Postgres](https://marmeon.com/docs/upgrading.md#high-an-app-on-postgres-sets-db_database-or-a-db_url-with-the-databases-name)). The environment of the servers and the platform follows in step 4. 3. An app made with `make:auth`: remove the auth module from `bootstrap/app.ts`, run `marmeon make:auth --force` and delete the files of 0.3 it leaves ([the kit](https://marmeon.com/docs/upgrading.md#high-apps-made-with-the-starter-kit-take-its-auth-module-again)). Until then the app does not load. 4. Rewrite the migrations before anything runs them ([a migration is a plan](https://marmeon.com/docs/upgrading.md#high-a-migration-is-a-plan-up-and-down-describe-the-change-instead-of-running-it)). 5. An app made with `make:auth` on 0.3: add the migrations of its auth tables ([the kit's migrations](https://marmeon.com/docs/upgrading.md#high-apps-made-with-makeauth-on-03-write-the-migrations-of-their-auth-tables)). 6. Run `marmeon agents:sync` and commit `AGENTS.md` and `CLAUDE.md`, which are new in this release: without them `marmeon check` reports `agents` as skipped ([coding agents](https://marmeon.com/docs/agents.md)). Optionally, `marmeon make:lint-config --force` writes the lint preset anew with the rule that refuses imports of `@marmeon/*/internal`; it replaces your changes to `.oxlintrc.json`, so add them back, and pass `--boundaries` if you use it ([lint](https://marmeon.com/docs/console.md#lint)). Also optionally, `securityHeaders()` from `@marmeon/http` replaces `middleware/SecurityHeaders.ts` in the `global` middleware of `bootstrap/app.ts`. If you turned on HSTS in that file, pass it on, as `securityHeaders({ hsts: { maxAge: 31_536_000, includeSubDomains: true } })`, or the header is no longer sent ([the other security headers](https://marmeon.com/docs/csp.md#the-other-security-headers)). 7. Run `marmeon migrate` on the development database, then `marmeon db:types` and `marmeon route:types`, and commit what they write: until then their `--check` fails with "generated by another version of Marmeon". If a command stops at the start, its message names what is missing; a queued listener of your own needs its name first ([queued listeners](https://marmeon.com/docs/upgrading.md#high-a-queued-listener-needs-a-stable-name-or-the-app-does-not-start)). 8. Make the changes of the other entries below. The compiler, `marmeon check` and the tests point at most of them. 3. **Stop every process of 0.3** on every machine: web, workers, the scheduler, cron jobs and every CI or release job that runs `marmeon`. With the queue on Redis nothing makes a forgotten worker fail, so stop each one. 4. **Set the environment of the servers and the platform to the new names, with `REDIS_PREFIX` and `DB_DATABASE` where they apply (0.3 reads none of the new names, and 0.4.0 stops at the start on an old one), deploy, run `marmeon migrate --force`, then `marmeon auth:end-all-sessions --force --keep-reset-tokens` (apps with `@marmeon/auth`), then start the new release.** Until `migrate` has run, every query fails with D2 and `/up/ready` is red. The second command deletes the sign-ins with their remember-me tokens, revokes the API tokens that are left and rotates every session key, so nothing of 0.3 signs anyone in. After the kit's migrations it reports `0 sign-ins deleted` and `0 API tokens revoked`, because those migrations deleted both already; the session keys it rotates are what it is still run for. 5. **After the start**, issue the API tokens again and hand them out. What is lost: - Every session and every "keep me signed in" token. Users sign in again, with their second factor where they have one; a sign-in that waited for its second factor during the upgrade ends too. - Every API token ([the API token entry](https://marmeon.com/docs/upgrading.md#high-api-tokens-have-a-new-form-and-every-token-is-issued-again)). - What an open tab had typed and not sent: the tab gets a `409` on its next request and loads the page anew. If you cache HTML documents publicly with a `max-age`, a tab can get an old document once after that reload ([deployment](https://marmeon.com/docs/deployment.md)). - The jobs of 0.3 that had not run, queued listeners, mails and notifications included. Their records carry no version: a worker of 0.4.0 fails each at once (Q1), logs and reports it and keeps its payload readable in `queue:failed`, but none can be retried, so the mail or notification it would have sent is not sent ([deploying while jobs wait](https://marmeon.com/docs/queues.md#deploying-while-jobs-wait)). Everything else stays: users, passwords, second factors and recovery codes, passkeys, reset links (with `--keep-reset-tokens`), uploads, notifications and the cache, as long as the app keeps its Redis prefix and its database name ([Redis](https://marmeon.com/docs/upgrading.md#high-an-app-with-marmeonredis-sets-app_name-or-redis_prefix), [Postgres](https://marmeon.com/docs/upgrading.md#high-an-app-on-postgres-sets-db_database-or-a-db_url-with-the-databases-name)). From this release on, a job a worker does not know waits up to six hours for a worker that knows it, instead of failing after its tries; a queue driver of your own honours the new `availableAt` option of `release()` ([queue drivers](https://marmeon.com/docs/drivers.md#queue-drivers-and-failed-job-stores)). When you rotate `APP_KEY` later, keep the old key in `APP_PREVIOUS_KEYS`, or everyone is signed out again. There is no way back: 0.3 reads neither the cookies, the sessions and the jobs nor the record of migrations that 0.4.0 writes. #### High: Apps made with the starter kit take its auth module again *Likelihood of impact: high — apps made with `make:auth`.* The kit's controllers, commands, listeners, translations and tests changed with the entries of this release, and nothing updates them in an app. Once the packages are at 0.4.0 and the environment is renamed ([the stopped upgrade](https://marmeon.com/docs/upgrading.md#high-upgrade-with-every-process-of-the-old-release-stopped), step 2), the app does not even load: the kit's module of 0.3 imports names that 0.4.0 no longer exports, such as `Lockout`, so `make:auth`, a command of `@marmeon/auth`, is not offered either (`marmeon list` shows only the built-in commands). On a clean working tree: 1. Remove the auth module from `bootstrap/app.ts`: the line `import auth from '#modules/auth';` and `auth` in `modules`. 2. Run `marmeon make:auth --force`. It writes the module again and adds it to `bootstrap/app.ts` again. It keeps every migration the app has and adds only the ones it lacks. 3. Delete the files of 0.3 that the kit no longer has. `make:auth` deletes nothing, and the type check fails on what they import: ```sh git -C modules/auth rm account-failures.ts account-failures.test.ts throttle.ts email-change.ts tasks/PruneEmailChanges.ts commands/EndSessionsCommand.ts commands/ResetTwoFactorCommand.ts passkeys.ts passkeys-browser.test.ts ``` 4. Look at `git diff` and put your own changes back. The files that go, in `modules/auth`: - `account-failures.ts` and `account-failures.test.ts` (sign-ins are limited inside `Auth.attempt()` now); - `throttle.ts` (password checks are limited by `@marmeon/auth`); - `email-change.ts` and `tasks/PruneEmailChanges.ts` (a change of address is `EmailChange` now); - `commands/EndSessionsCommand.ts` and `commands/ResetTwoFactorCommand.ts`: `auth:end-sessions` and `auth:reset-two-factor` come with `@marmeon/auth`, and two commands of one name stop every `marmeon` command with K8. A command you customized keeps working under another name. Tests import the classes from `@marmeon/auth`; pass the address as it is stored (lower case); - `passkeys.ts` and `passkeys-browser.test.ts` (the browser side of passkeys is `@marmeon/auth/passkeys/browser`). New in the module: `password-errors.ts`, `listeners/QueueLockoutMail.ts` (without it the owner of a locked account gets no mail), `listeners/NotifyAboutEmailChange.ts`, and the tests `login-limits.test.ts` and `route-limits.test.ts`. `AuthServiceProvider.ts` no longer binds `SignInStore` (the binding is harmless but redundant). Without `--force`, port the files from `packages/auth/stubs/react/modules/auth` of the installed version; the compiler points at most places. There is no way back. See [the starter kit](https://marmeon.com/docs/starter-kit.md). #### High: A migration is a plan: `up` and `down` describe the change instead of running it *Likelihood of impact: high — every app with migrations, the copies of the starter kit's included.* `marmeon migrate` takes the steps a migration describes and runs them, and the app knows its schema from these plans, not from the database. In `modules/*/migrations`: - `up: async (schema) =>` and `down: async (schema) =>` become `up: (schema) =>` and `down: (schema) =>`. Find them with `grep -rnE '(up|down): async \(schema\)' modules`. - `await schema.create(`, `.alter(`, `.drop(`, `.dropIfExists(` and `.rename(` lose the `await`. Find them with `grep -rnE 'await schema\.(create|alter|drop|dropIfExists|rename)\(' modules`. - Data written through `schema.db` moves into `schema.data(async (db) => { … })`. - Raw DDL (`` sql`…`.execute(schema.db) ``) becomes `schema.raw(sql`…`)`. A branch on `schema.driver` becomes `schema.raw({ sqlite: …, pgsql: … })`, or reads `driver` in `schema.data(async (db, { driver }) => …)`. Marmeon records no owner, secret, soft-delete or timestamps mark for what raw SQL makes. - `schema.hasTable()` and `schema.hasColumn()` are gone: a migration describes one change. Use `dropIfExists`, or SQL with `if exists` where a table may be missing. - A plan is deterministic: no time, environment, file or database content may decide which steps `up` adds. - A migration that changes a table created by raw SQL with `schema.alter()` or `schema.rename()` stops with D19, even when both ran already. Rewrite the raw `create table` in the old migration as `schema.create()` (this keeps `.secret()` and `softDeletes()`), or make the change in raw SQL too. - On Postgres, an index whose default name is longer than 63 bytes stops with D5. For a migration that ran already, pass the name Postgres stored (`select indexname from pg_indexes where tablename = '…'`); in a new migration, a short name of your own, so that a later `dropIndex` finds it. Rewrite the files before the first `marmeon migrate` of 0.4.0. That run adds a `checksum` column to `migrations` and records the checksum of every migration file as it is then; from then on `migrate` and `migrate:status` warn about a file that changed after it ran. Editing a migration that ran changes nothing in the database. There is no way back. See [Migrations](https://marmeon.com/docs/migrations.md) and [raw SQL](https://marmeon.com/docs/migrations.md#raw-sql). #### High: Apps made with `make:auth` on 0.3 write the migrations of their auth tables *Likelihood of impact: high — apps made with `make:auth` on 0.3, and apps with a `sign_ins` table from `make:sign-ins-table`.* The kit's tables changed: API tokens are found by a unique hash, a device's remember-me token lives on the row of its sign-in and `remember_tokens` goes, every account has a session key, and an open change of address has a table of its own, `email_changes`, instead of three columns of `users`. A migration the framework shipped never changes, so nothing writes these changes for an app made on 0.3. Until they have run, `/up/ready` is red and names what is missing. 1. Take the kit again first ([the kit](https://marmeon.com/docs/upgrading.md#high-apps-made-with-the-starter-kit-take-its-auth-module-again)). `make:auth --force` keeps every migration the app has and adds the one it lacks, `0001_01_01_000007_create_email_changes_table`. `migrate` runs it although migrations with later timestamps ran already: it creates a new table and changes none. An app that ports the kit by hand copies that file from the kit instead. Never write a second `email_changes` table: `migrate` then fails. 2. Add these migrations to `modules/auth/migrations`, named with the current timestamp so that they sort after every migration that ran, in this order. Each one ends what it touches: the upgrade ends every session anyway. ```ts // _reissue_personal_access_tokens.ts — every token is deleted: its form is gone and no code reads it. import { defineMigration } from '@marmeon/database'; export default defineMigration({ up: (schema) => { schema.data(async (db) => { await db.deleteFrom('personal_access_tokens').execute(); }); schema.alter('personal_access_tokens', (table) => table.unique('token_hash')); }, down: (schema) => schema.alter('personal_access_tokens', (table) => table.dropUnique('personal_access_tokens_token_hash_unique')), }); ``` ```ts // _add_remember_columns_to_sign_ins.ts — the remember-me token moves onto the sign-in row; every sign-in ends. import { defineMigration } from '@marmeon/database'; export default defineMigration({ up: (schema) => { schema.data(async (db) => { await db.deleteFrom('sign_ins').execute(); }); schema.alter('sign_ins', (table) => { table.dropUnique('sign_ins_remember_selector_unique'); table.dropColumn('remember_selector'); }); // A column cannot be marked secret later: the selector is made again. schema.alter('sign_ins', (table) => { table.string('remember_selector', 32).nullable().secret().unique(); table.string('remember_validator_hash', 64).nullable().secret(); table.string('remember_previous_validator_hash', 64).nullable().secret(); table.timestamp('remember_rotated_at').nullable(); table.timestamp('remember_created_at').nullable(); table.string('remember_fingerprint', 64).nullable(); }); }, down: (schema) => { schema.alter('sign_ins', (table) => { table.dropColumn('remember_validator_hash'); table.dropColumn('remember_previous_validator_hash'); table.dropColumn('remember_rotated_at'); table.dropColumn('remember_created_at'); table.dropColumn('remember_fingerprint'); table.dropUnique('sign_ins_remember_selector_unique'); table.dropColumn('remember_selector'); }); schema.alter('sign_ins', (table) => { table.string('remember_selector', 32).nullable().unique(); }); }, }); ``` ```ts // _fill_empty_session_keys.ts — a random key for every account without one, from the database's own generator. import { defineMigration, sql } from '@marmeon/database'; export default defineMigration({ up: (schema) => { schema.data(async (db, { driver }) => { if (driver !== 'pgsql' && driver !== 'sqlite') throw new Error(`fill_empty_session_keys: no source of random bytes known for "${driver}"`); const key = driver === 'pgsql' ? sql`replace(gen_random_uuid()::text || gen_random_uuid()::text, '-', '')` : sql`lower(hex(randomblob(32)))`; await db.updateTable('users').set({ session_key: key }).where('session_key', 'is', null).execute(); }); }, down: () => {}, }); ``` ```ts // _drop_remember_tokens_table.ts — the tokens are not copied; "keep me signed in" works again after the next sign-in. import { defineMigration } from '@marmeon/database'; export default defineMigration({ up: (schema) => schema.drop('remember_tokens'), down: (schema) => schema.create('remember_tokens', (table) => { table.id(); table.foreignId('user_id').constrained().cascadeOnDelete(); table.string('selector', 32).unique(); table.string('validator_hash', 64).secret(); table.string('previous_validator_hash', 64).nullable().secret(); table.timestamp('rotated_at').nullable(); table.timestamp('last_used_at').nullable(); table.timestamp('expires_at'); table.string('account_fingerprint', 64).nullable(); table.timestamps(); }), }); ``` ```ts // _drop_pending_email_columns_from_users.ts — an open change of address is not carried over; its owner asks again. import { defineMigration } from '@marmeon/database'; export default defineMigration({ up: (schema) => schema.alter('users', (table) => { table.dropColumn('pending_email'); table.dropColumn('pending_email_token'); table.dropColumn('pending_email_expires_at'); }), down: (schema) => schema.alter('users', (table) => { table.string('pending_email', 255).nullable(); table.string('pending_email_token', 64).nullable().secret(); table.timestamp('pending_email_expires_at').nullable(); }), }); ``` 3. Once the environment variables are renamed ([environment variables](https://marmeon.com/docs/upgrading.md#high-environment-variables-are-named-after-what-they-configure-and-their-unit)), run `marmeon migrate` (in production as step 4 of [the stopped upgrade](https://marmeon.com/docs/upgrading.md#high-upgrade-with-every-process-of-the-old-release-stopped)), then `marmeon db:types`. Code that read `users.pending_email*` reads nothing now: a change of address goes through `EmailChange` and `EmailChangeStore`. An app without the kit but with a `sign_ins` table from `make:sign-ins-table` needs the sign-in migration above and drops its own `remember_tokens` table; an app with a `UserProvider` and no `sign_ins` table runs `marmeon make:sign-ins-table` ([sign-ins](https://marmeon.com/docs/authentication.md#sign-ins)). A `remember_tokens` table created under another migration name is not dropped for you. With a user table of your own, give every account without a session key a random one, as the third migration does. There is no way back; the tokens and columns these migrations drop hold nothing that still works after the upgrade. #### High: The app reads its schema from the migrations and refuses queries while one is pending *Likelihood of impact: high — every app with a database.* - An app that starts before `marmeon migrate` refuses every query with D2 (`MigrationStateError`) and readiness is red. It recovers within a second after `migrate`, without a restart. Scripts and `marmeon tinker` against a database that is not migrated set `DB_MANAGED=false`. - `table_owners`, `secret_columns` and `schema_markers` of 0.3 stay in the database, and `migrate` names them. Drop them by hand once no process of 0.3 runs, on every connection that has them. The record of migrations of 0.3 is read as it is. - Tables and columns made with `schema.raw()` or by another tool are not in `Tables` and `Relations` and have no relations, kinds or marks: `with()` on them stops working and code that used their types fails to compile. Create them with `schema.create()`, or type them for reading with `db.withTables<{ … }>()`. - `selectAll()` and `returningAll()` name the columns the migrations know: a column that raw SQL or another tool added no longer comes back, so name it in the query. A whole-row value of a migration table (`to_jsonb(t)`, `eb.table('t')`) fails with D9. The compiled SQL lists the columns instead of `select *`; update query snapshots. - Raw SQL in a migration that renames or drops a table or column the migrations know rolls the migration back (D3): use `schema.alter()` or `schema.rename()`. A new migration with an older timestamp that changes a table a migration already run has changed is refused until it is renamed. - Dropping or renaming a column breaks every `selectAll()`, `returningAll()` and relation of that table in processes of the release before. Drop or rename a column only in the release after the one that stops using it; `retire()` takes it out of use first. - Own tables without a record of migrations are kept: `migrate` creates `migrations` and names the tables it did not make. A database another tool manages (with a `migrations` table of its own, say) gets `managed: false` or `DB_MANAGED=false`. - `Migrator.onOneConnection()`, `owners()`, `secrets()` and `markers()` are removed: use `migrator.projection()`. A `switch` over `MigrationStateError.reason` handles the new `'unmanaged'`. - Tests that build tables with raw DDL on a managed connection use migrations instead. There is no way back. See [how the app knows its schema](https://marmeon.com/docs/migrations.md#how-the-app-knows-its-schema). #### High: Environment variables are named after what they configure and their unit *Likelihood of impact: high — every app that sets one of the old names in a `.env` file, its deployment, a compose file or CI.* Rename these variables in `.env`, `.env.test` and `.env.example`, and wherever else the environment is set: compose files, CI, and the server or platform (in step 4 of [the stopped upgrade](https://marmeon.com/docs/upgrading.md#high-upgrade-with-every-process-of-the-old-release-stopped)). The values stay the same; nothing is converted. The `.env.test` of an app made on 0.3 sets `MAIL_MAILER=array`: until it says `MAIL_DRIVER=array`, every test stops with K6. An old name that is set stops the start in every environment, even next to the new one, names its replacement and is never read; `marmeon check` reports it too. | Old | New | | --- | --- | | `DB_CONNECTION` | `DB_DRIVER` | | `QUEUE_CONNECTION` | `QUEUE_DRIVER` | | `DB_QUEUE_CONNECTION` | `QUEUE_DATABASE_CONNECTION` | | `DB_QUEUE` | `QUEUE_DATABASE_QUEUE` | | `DB_QUEUE_RETRY_AFTER` | `QUEUE_DATABASE_RETRY_AFTER_SECONDS` | | `REDIS_QUEUE_CONNECTION` | `QUEUE_REDIS_CONNECTION` | | `REDIS_QUEUE` | `QUEUE_REDIS_QUEUE` | | `REDIS_QUEUE_RETRY_AFTER` | `QUEUE_REDIS_RETRY_AFTER_SECONDS` | | `MAIL_MAILER` | `MAIL_DRIVER` | | `AUTH_PASSWORD_TIMEOUT` | `AUTH_PASSWORD_TIMEOUT_SECONDS` | | `AUTH_RESET_EXPIRE` | `AUTH_RESET_MINUTES` | | `AUTH_RESET_THROTTLE` | `AUTH_RESET_THROTTLE_SECONDS` | | `AUTH_EMAIL_CHANGE_THROTTLE` | `AUTH_EMAIL_CHANGE_THROTTLE_SECONDS` | | `SESSION_LIFETIME` | `SESSION_LIFETIME_MINUTES` | | `UPLOADS_LIFETIME` | `UPLOADS_LIFETIME_MINUTES` | | `UPLOADS_SEND_WITHIN` | `UPLOADS_SEND_WITHIN_MINUTES` | | `LIVE_REDIS_CONNECTION` | `LIVE_CONNECTION` | | `LIVE_HEARTBEAT` | `LIVE_HEARTBEAT_SECONDS` | | `LIVE_RETRY` | `LIVE_RETRY_MILLISECONDS` | | `MAX_BODY_SIZE` | `SERVER_MAX_BODY_SIZE` | | `HEALTH_PATH` | `SERVER_HEALTH_PATH` | | `ASSET_VERSION` | `SERVER_ASSET_VERSION` | | `SHUTDOWN_DELAY` | `SERVER_SHUTDOWN_DELAY_SECONDS` | | `KEEP_ALIVE_TIMEOUT` | `SERVER_KEEP_ALIVE_TIMEOUT_SECONDS` | | `TRUSTED_PROXIES` | `SERVER_TRUSTED_PROXIES` | | `SSR_ENABLED` | `SERVER_SSR_ENABLED` | | `OTEL_TRUST_TRACEPARENT` | `MARMEON_OTEL_TRUST_TRACEPARENT` | | `OTEL_RECORD_QUERY_VALUES` | `MARMEON_OTEL_RECORD_QUERY_VALUES` | `PORT`, `HOST` and the names of the OpenTelemetry specification (`OTEL_SDK_DISABLED` …) keep theirs. An app with files from `marmeon make:docker` runs it again with `--force`, or renames `HEALTH_PATH` in its `Dockerfile`, `SHUTDOWN_DELAY` and `TRUSTED_PROXIES` in its compose file, and `TRUSTED_PROXIES` in the systemd units of `--systemd`. A test that pins `DB_CONNECTION` pins `DB_DRIVER`. These variables are read as switches now: `MAIL_SECURE`, `MAIL_REQUIRE_TLS`, `AUTH_PRIVATE_REGISTRATION`, `AUTH_REVOKE_TOKENS_ON_PASSWORD_CHANGE`, `SESSION_ENCRYPT`, `SESSION_SECURE_COOKIE`, `SERVER_SSR_ENABLED`, `MARMEON_OTEL_TRUST_TRACEPARENT`, `MARMEON_OTEL_RECORD_QUERY_VALUES` and `DEVTOOLS_ENABLED`. They take `true`, `false`, `1` and `0` in any letter case; any other text (`yes`, `off`) stops the start, and empty keeps the default (`SESSION_SECURE_COOKIE` then follows `APP_URL`). `DEVTOOLS_ENABLED=1` counts as on, so it also stops a production start. `OTEL_SDK_DISABLED` follows the OpenTelemetry specification: only `true` disables, any other value, `1` included, leaves spans on. There is no way back; the old names are never read. See [renamed variables](https://marmeon.com/docs/configuration.md#renamed-variables) and [every variable](https://marmeon.com/docs/configuration.md#every-variable). #### High: An app with `@marmeon/redis` sets `APP_NAME` or `REDIS_PREFIX` *Likelihood of impact: low — apps with `@marmeon/redis` installed whose environment sets neither variable. Apps made by `create-marmeon` require `APP_NAME` already.* The prefix of every Redis key and channel comes from `REDIS_PREFIX`, or from `APP_NAME` as a slug, and no longer falls back to `marmeon:`: two apps on one Redis without either shared their sessions, cache, rate limits, locks and queues. An app with `@marmeon/redis` installed, whichever drivers it uses, now stops at start: ```text [marmeon:K6] Invalid configuration — the application cannot start: • redis: REDIS_PREFIX — set REDIS_PREFIX, or APP_NAME (with a letter or digit) — apps on one Redis share their keys otherwise (docs/redis.md#configuration) ``` Set one of them in `.env` and wherever the environment is set (CI, and the server or platform in step 4 of [the stopped upgrade](https://marmeon.com/docs/upgrading.md#high-upgrade-with-every-process-of-the-old-release-stopped)): - `APP_NAME="My App"` gives the prefix `my-app:`. - `REDIS_PREFIX=notes-app:` is used as written; end it with the colon yourself. An empty `REDIS_PREFIX=` and an `APP_NAME` without a letter or digit count as not set. - An app whose keys live under `marmeon:` because it relied on the old default sets `REDIS_PREFIX=marmeon:` to keep them. Otherwise its cache starts empty, and jobs still waiting under `marmeon:` are not found, not even as failed ones. - Staging and production on one Redis give each its own `REDIS_PREFIX`. A named connection from `defineRedisConnection()` keeps the prefix it gives in `resolve`. There is no way back to a default prefix. See [Redis](https://marmeon.com/docs/redis.md#configuration). #### High: An app on Postgres sets `DB_DATABASE` or a `DB_URL` with the database's name *Likelihood of impact: low — apps with `DB_DRIVER=pgsql` that set neither `DB_DATABASE` nor a `DB_URL` with a path, and so used the database `marmeon`.* Postgres no longer falls back to the database `marmeon`: two apps on one server without a name of their own shared every table, from users and sessions to the cache and the jobs. Such an app now stops at start: ```text [marmeon:K6] Invalid configuration — the application cannot start: • database: DB_DATABASE — set DB_DATABASE, or DB_URL with the database's name in its path — apps on one Postgres server share their tables otherwise (docs/database.md#configuration) ``` Set one of them in `.env` and wherever the environment is set (CI, and the server or platform in step 4 of [the stopped upgrade](https://marmeon.com/docs/upgrading.md#high-upgrade-with-every-process-of-the-old-release-stopped)): `DB_DATABASE=notes`, or `DB_URL=postgres://user:secret@host:5432/notes`; the URL wins. `DB_DRIVER` is the `DB_CONNECTION` of 0.3 ([renamed variables](https://marmeon.com/docs/upgrading.md#high-environment-variables-are-named-after-what-they-configure-and-their-unit)). - An app whose tables are in the database `marmeon` sets `DB_DATABASE=marmeon`, or `/marmeon` in `DB_URL`. Any other name is another, empty database. - An empty `DB_DATABASE=` counts as not set, and so does a `DB_URL` without a path (`postgres://app@db:5432`, `postgres://app@db/`): `pg` would then read `PGDATABASE` or take the user name. - Staging and production on one server each need their own database name. - A named connection from `defineConnection()` whose `url` has no path gives it one, or sets `database`; otherwise it throws a `TypeError`. SQLite keeps its default file. There is no way back to a default name. See [database configuration](https://marmeon.com/docs/database.md#configuration). #### High: API tokens have a new form, and every token is issued again *Likelihood of impact: medium — apps that issue API tokens.* A token no longer carries its row id: it looks like `marmeon_…`, without the `|`, and is found by the unique hash of its secret. Every token issued before stops working, and the upgrade deletes them ([the kit's migration](https://marmeon.com/docs/upgrading.md#high-apps-made-with-makeauth-on-03-write-the-migrations-of-their-auth-tables), `auth:end-all-sessions`). Each app issues its tokens again and hands them to every integration, script and client that used one: plan this before you deploy. - `AUTH_TOKEN_PREFIX` is empty, or at most 16 lower-case letters, digits and `_`, ending in `_` (default `marmeon_`). Any other value stops the start, so change it before you deploy. - `AccessToken.id` is `number | string`. Code that cut the id out of a token reads it from `AccessTokenStore.list()` instead. - A token table of your own: delete the old rows and add `unique('token_hash')` in a migration. With UUID keys, adapt the revoke controller. There is no way back. See [the token format](https://marmeon.com/docs/api-tokens.md#the-token-format). #### High: A queued listener needs a stable name, or the app does not start *Likelihood of impact: medium — apps with queued listeners: a class with `static queue` passed to `listen(Event, Class)`.* A worker finds a queued listener by a name that a rename or a minifier cannot change. Add one to each: ```ts export class SendWelcomeMail { static readonly listener = 'accounts.send-welcome-mail'; static queue = { tries: 3 }; // … } ``` Use lower-case words with a `.` after the module, and never change the string later. The app does not start until every queued listener has one. Notifications and mails with `static queue` need none. Queued listener jobs of 0.3 do not run ([the stopped upgrade](https://marmeon.com/docs/upgrading.md#high-upgrade-with-every-process-of-the-old-release-stopped)). There is no way back. See [queued listeners](https://marmeon.com/docs/events.md#queued-listeners). #### High: An `ExceptionHandler` with a `report()` method no longer reports *Likelihood of impact: medium — apps that extended `DefaultExceptionHandler` and overrode `report()`, for example to send errors to a tracker, or bound an `ExceptionHandler` of their own with a `report()` method.* Errors go to the error reporters that providers bring, and the framework no longer calls `report()` on the handler. TypeScript does not flag the extra method, so such an app **stops reporting without a type error**; the kernel logs one warning at the first server error ("The ExceptionHandler has a report() method, which is not called any more"). - Move the code into an `ErrorReporter` (`report(report: ErrorReport)`), list it in a provider's `static errorReporters`, and remove `report()` from the handler. - `DefaultExceptionHandler` has no constructor parameters: a subclass that calls `super(logger, redactor)` drops the arguments. - An error you catch yourself while the request still answers 200 is reported with `app.container.make(ErrorReports).report(error, { source: 'request' })`. - A reporter whose constructor throws stops the start with K12; a wrong DSN no longer switches reporting off without a sound. The log line of an error is unchanged. There is no way back. See [reporting](https://marmeon.com/docs/errors.md#reporting). #### High: A `UserProvider` writes the session key with the password and compares both *Likelihood of impact: high — every app with `@marmeon/auth`: apps made with `make:auth` take the kit's `UserRepository.ts`, a provider of your own implements the methods below.* A session is bound to the account's id and session key, no longer to its password hash. A rehash after higher `HASH_*` costs keeps every sign-in, and code that writes `password` itself ends no session any more: write a new key with it, or call `AccountSessions.end()`. To end everything, run `marmeon auth:end-all-sessions`. - **Apps made with `make:auth`:** take `UserRepository.ts` from the kit and replace the tests `auth.test.ts`, `two-factor.test.ts` and `passkeys.test.ts` ([the kit](https://marmeon.com/docs/upgrading.md#high-apps-made-with-the-starter-kit-take-its-auth-module-again)). Your own calls `updatePasswordHash(id, hash, expected)` become `updatePasswordHash(id, hash, { expected })`. Tests that write `password` directly also write a `session_key`; a test double that overrides `findById` returns `sessionKey`. - **A provider of your own:** - `updatePasswordHash(id, hash, { expected?, sessionKey?, expectedSessionKey? })` returns a boolean. With `sessionKey` it writes hash and key in one statement, and only where the stored key equals `expectedSessionKey` (`IS NULL` for `null`); otherwise it returns `false`. - `updateSessionKey(id, key, expected)` is a compare-and-set in one statement (`IS NULL` for `null`); called with the stored key as both `key` and `expected`, it returns `true`. - `updateEverySessionKey(key)` is one `UPDATE` without `WHERE` and returns `{ accounts, sampleId }`; `sampleId` is required when `accounts > 0`. `auth:end-all-sessions` needs it. - `findById()` and `findForSignIn()` (before: `findForLogin()`, [renamed](https://marmeon.com/docs/upgrading.md#medium-auth-events-methods-and-types-are-named-after-signing-in)) return `sessionKey` (`null` when the account has none) from a `session_key` column (64 characters, `.secret()`), read after the write, not from a cache; otherwise `updatePassword()` and a reset fail with A5. `findForSignIn()` compares the normalized identifier exactly. - New accounts get a random key (32 bytes, base64url); `NULL` stays allowed. - The framework checks only the shape of the answers: test the compare-and-set yourself. - **JavaScript providers with the positional `expected`** now receive an object: on SQLite the binding throws, on Postgres the comparison never matches, so a sign-in that needs a rehash is refused as a wrong password. - **Every app with a `UserProvider`** installs `@marmeon/cache` and registers its provider, or the boot stops with A7: sign-ins and password checks are limited through it. Test harnesses with `discover: false` add `CacheServiceProvider` (with `CACHE_DRIVER=memory`, say). There is no way back. See [for your own user provider](https://marmeon.com/docs/authentication.md#for-your-own-user-provider). #### Medium: Auth events, methods and types are named after signing in *Likelihood of impact: high — every app with `@marmeon/auth`: the kit's `UserRepository.ts`, every provider of your own, and code that uses the auth API.* Rename what the compiler points at: | Before | After | | --- | --- | | `Login` (event) | `SignedIn` | | `Logout` (event) | `SignedOut` | | `Failed` (event) | `SignInFailed` | | `Lockout` (event) | `SignInLockedOut` | | event name `auth.login` | `auth.signed-in` | | `LoginPayload` | `SignedInPayload` | | `LoginInput` | `SignedInInput` | | `LoginVia` | `SignInVia` | | `via: 'login'` (event field, `Auth.signIn()`) | `via: 'app'` | | `auth.login(user)` | `auth.signIn(user)` | | `auth.logout()` | `auth.signOut()` | | `LoginOptions` | `SignInOptions` | | `LoginThrottle` | `SignInThrottle` | | `findForLogin()` (`UserProvider`) | `findForSignIn()` | `findForSignIn()` keeps the signature and the contract of `findForLogin()`. Rename it in the kit's `UserRepository.ts` ([the kit](https://marmeon.com/docs/upgrading.md#high-apps-made-with-the-starter-kit-take-its-auth-module-again)), in every provider of your own, and in seeders and tests that call it. In JavaScript or behind a cast, a provider with only the old name stops the boot with A5, which names `findForSignIn()`; nobody is signed in and no account is reported as unknown. The kit's `LoginController`, `ShowLoginController`, `LogoutController` and the view `Login.tsx` keep their names, and so do the routes `auth.login` and `auth.logout`. A queued listener job stored under the event name `auth.login` is never delivered to a listener of `auth.signed-in`; the jobs of 0.3 fail at once after the upgrade in any case, so let the queue run empty before ([the stopped upgrade](https://marmeon.com/docs/upgrading.md#high-upgrade-with-every-process-of-the-old-release-stopped)). There is no way back. See [Authentication](https://marmeon.com/docs/authentication.md) and [for your own user provider](https://marmeon.com/docs/authentication.md#for-your-own-user-provider). #### Medium: Password checks and sign-in limits are part of `Auth` *Likelihood of impact: medium — apps with their own sign-in, password, two-factor or passkey controllers.* `Auth.attempt()` limits password sign-ins per client and per account and dispatches `SignInLockedOut` itself, and every password check of a signed-in user runs under its throttle. - Replace `auth.confirmPassword(p)` with `(await auth.checkPassword(p)).ok`, and show `throttled` to the user. - Replace `logoutOtherDevices(p)` with `checkPassword(p)` followed by `updateSessionKey()`. - Test `TwoFactor.disable()` through `.ok`, never its truthiness. - Remove your own counting around sign-ins, `checkPassword()`, `disable()` and the passkey methods, and your own lockout dispatches; otherwise each counts twice. Tests that read the cache key `limiter:login:|` stop doing so. - Handle `throttled` from `attempt()`: `retryAfter`, and `account: true` when waiting does not help. - `new SignInLockedOut(identifier, ip, scope)` takes the scope; a listener that blocks an IP acts only on `'client'`. - Set the device cookie after a successful sign-in (`auth.deviceCookie()`) and after a reset (`broker.deviceCookie(user)`). - Code that builds `Auth` or `PasswordBroker` by hand passes a `RateLimiter` and a `SignInThrottle` as the last arguments; resolve them from the container instead. The new environment variables of the limits are optional. There is no way back. See [limits on password sign-ins](https://marmeon.com/docs/authentication.md#limits-on-password-sign-ins). #### Medium: The auth stores and the session store are abstract classes *Likelihood of impact: low — apps with their own reset-token, API-token, two-factor, sign-in, remember-me or session store, their own hasher, or test doubles of these.* - Write `extends PasswordResetTokenStore`, `AccessTokenStore`, `TwoFactorState`, `SignInStore` or `SessionStore` instead of `implements`, call `super()`, and implement every member, `forgetEveryone()` and `revokeEveryone()` included. Test doubles written as object literals (`container.instance(SessionStore, { … })`) become subclasses. User id parameters are `AuthUserId`: convert a string route parameter for a numeric id. - `RememberTokenStore` is gone: a remember-me token lives on the row of its sign-in. Move its methods into one class that `extends SignInStore`: `issueToken` instead of `create`, `consume` (it returns `signIn` now), `remembered` instead of `exists`, `forgetToken` instead of `forget`, `rebind`, `dropToken`, and `endAll` / `endEveryone` instead of `forgetUser` / `forgetEveryone`. `prune(window, days)` takes the days. Keep the guarantees their JSDoc names: user-scoped writes, an atomic revocation on theft, `commitAnyway` on expiry and theft, read-after-write for `remembered`. - A session store: `class YourStore extends SessionStore`, with `override` before `destroyUser` under `noImplicitOverride`. Extend `SessionStore` itself, never a built-in store. - A source passed to `combineFactors()` needs `factors`, `enabledSince` and `removeAll`. A store for changes of address adds `waiting()`. - A hasher of your own adds `failureFloorMs()`, returning milliseconds of 0 or more; `0` gives up the padding of failed sign-ins. - In JavaScript or behind a cast, a missing member or an invalid `failureFloorMs()` answer fails with A6. - Listeners of `EveryoneEnded` and `EverySessionEnded` stop reading `rememberTokens`. - Code that constructs `AccountSessions`, `NewPassword`, `PruneTokensCommand`, `PasswordBroker`, `TwoFactor` or `Passkeys` itself: their constructor parameters changed (`TwoFactor` and `Passkeys` take `SessionConfig` last); resolve them from the container. - Removing a passkey through the package API instead of the kit's controller: call `updateSessionKey()` afterwards, as the controller does, so that the sessions of a cloned passkey end. There is no way back. See [your own stores](https://marmeon.com/docs/authentication.md#your-own-stores). #### Medium: The session and remember-me cookies are named `__Host-…` over https *Likelihood of impact: medium — apps that set `SESSION_COOKIE` or `AUTH_REMEMBER_COOKIE`, run behind a TLS proxy, or name these cookies in tests.* With `Secure` cookies the two cookies carry the `__Host-` prefix and no `Domain`. The cookies of 0.3 are never read ([the stopped upgrade](https://marmeon.com/docs/upgrading.md#high-upgrade-with-every-process-of-the-old-release-stopped)). - `AUTH_REMEMBER_COOKIE` defaults to `marmeon_remember` (before: `remember_web`). An app that sets it checks the name. - If `SESSION_COOKIE` or `AUTH_REMEMBER_COOKIE` starts with `__Host-` or `__Secure-`, remove the prefix: the framework adds it, and the app does not start otherwise. - Behind a TLS proxy, serve with `APP_URL=https://…`. - Tests that read or set these cookies by name take the names from `cookieNames(app)` (`@marmeon/auth/testing`) or `sessionCookieName()` / `rememberCookieName()`: with an https `APP_URL` the literal names no longer match. - `ctx.cookies` no longer shows cookies whose names are not RFC 6265 tokens (`a[b]`, `x:y`). There is no way back. See [the `__Host-` prefix](https://marmeon.com/docs/session.md#the-__host--prefix). #### Medium: Pages and visits give `PageInfo`, not the page object *Likelihood of impact: medium — apps that read protocol fields of `usePage()`, of what `router.visit()` and `router.reload()` resolve to, or of visit callbacks.* `usePage()`, `router.visit()`, `router.reload()`, `router.on('success')`, `onSuccess` and `VisitException.page` give `PageInfo`: `props`, `url`, `component`, `route`, `locale`, `query` and `flash`, read-only. For the fields that are gone: | Before | After | | --- | --- | | `.version` | `useNewVersion()` or `router.on('version')` | | `.deferredProps` | `` or `` | | `.layers` | `useLayer()` | | `.csrf` | `xsrfToken()` from `@marmeon/http/client` (same-origin requests pass by Fetch Metadata anyway) | | `.epoch` | `tabSync` | `@marmeon/react` exports only the app's API now: - Remove imports of `Backdrop` and `ErrorPage`: the built-in error page and layer backdrop still apply; to replace them, add `modules/errors/views/Error.tsx` or `modules/layers/views/Backdrop.tsx`. - `SHORT_PENDING_DELAY` becomes `usePending(name, { delay: 'short' })`, `pagesAround` becomes ``; `layoutsOf` has no replacement. - `pageQuery` is no longer in `@marmeon/http/client`: use `useQueryState()`, which also fills in the defaults. - `MarmeonApp` and `MarmeonAppProps` are no longer exported: the app's entry is `createMarmeonApp()`. There is no way back. See [Pages](https://marmeon.com/docs/pages.md). #### Medium: A controller passes the status and headers of a result as options *Likelihood of impact: high — apps that answer with another status than 200 from a controller.* ```ts this.view('notes/Edit', props, 422); // before this.view('notes/Edit', props, { status: 422 }); this.json(data, 201); // before this.json(data, { status: 201 }); this.redirect(url, 301); // before this.redirect(url).status(301); ``` The same goes for the standalone `view()` and `json()` of `@marmeon/http`, whose headers move from a further argument into `{ headers }`, and for `new RedirectResult(url, status)`, which becomes `new RedirectResult(url).status(status)`. The compiler points at each call; a number that slips through at run time throws a `TypeError` that names `{ status: 422 }`. There is no way back. See [Responses](https://marmeon.com/docs/responses.md). #### Medium: A middleware adds to the request context and never replaces a key *Likelihood of impact: medium — apps with middleware of their own, or code that assigns to `ctx`.* - `next()` refuses every key the context has already and the names every object has (`then`, `toJSON`, `constructor`). A reserved key (`request`, `params`, `route`, `query`, `input`, `inputRead`, `cookies`, `ip`, `nonce`, `expectsJson`, `body`, `pageQuery`) in what a middleware declares does not compile; any key given to `next()` that is reserved or present fails when the request runs with a `TypeError` (H8) and a 500. Give the value a key of its own (`next({ activeTeam })`). A middleware may not replace a key an earlier one set (`user` after `authenticate()`). Adding a new key works as before. - The context is frozen one level deep, and so are `ctx.params` and `ctx.route`: `ctx.team = …`, `Object.assign(ctx, …)` and assignments to `ctx.params` throw a `TypeError`; use `next({ … })`. Values inside the other keys (the `user` object, `ctx.query`, `ctx.request.headers`) stay changeable. - A loaded route is frozen: `route.name()`, `route.internal()`, `route.block()`, `route.middleware.push(…)` or `route.reserved = …` after `Router.load` throw a `TypeError`. Set these inside `defineRoutes()`. - Two middleware that declare the same key in `static adds` stop the start with H8, naming the route, the key and both, for instance `authenticate()` on a group and again on a route: remove one. `marmeon check` reports it. - A middleware that adds keys declares them: `static adds = ['team'] as const` in a class, `defineMiddleware(name, handle, { adds: ['team'] })` for an object. Without it, only the run-time check applies. There is no way back. See [adding to the context](https://marmeon.com/docs/middleware.md#adding-to-the-context). #### Medium: `useForm` takes the route parameters as an option *Likelihood of impact: high — apps with forms whose route has parameters, and every app made with `make:auth`.* ```ts useForm('notes.update', { note: id }, initial, options); // before useForm('notes.update', initial, { params: { note: id }, ...options }); useForm('notes.store', {}, initial); // before useForm('notes.store', initial); ``` The compiler points at each call; where it cannot see one (untyped code), the old forms throw a `TypeError` when the component renders. Apps made with `make:auth` take the kit's views ([the kit](https://marmeon.com/docs/upgrading.md#high-apps-made-with-the-starter-kit-take-its-auth-module-again)) or edit them as the compiler shows. There is no way back. See [Forms](https://marmeon.com/docs/forms.md). #### Medium: The database's types have names of their own, and a module's database runs queries only *Likelihood of impact: medium — apps that name query-builder types or run DDL or raw SQL through a module's `Database`.* - `Kysely` becomes `Connection`, `SelectQueryBuilder` becomes `SelectQuery`; `Selectable`, `Insertable<…>` and `Updateable<…>` become `Row<'t'>`, `NewRow<'t'>` and `RowUpdate<'t'>` (for a table type not in `Tables`: `RowOf`, `NewRowOf`, `RowUpdateOf`). All come from `@marmeon/database` and are the same types; `Transaction` and `sql` keep their names. - `queue.using(x)` takes only a transaction (`trx` from `connections.transaction()`): `queue.using(db)` does not compile. Pass the transaction, or dispatch without `using()`. - `Database<'module'>` offers `selectFrom`, `selectNoFrom`, `fn`, `case`, `dynamic` and `isTransaction`, plus `insertInto`, `updateTable`, `deleteFrom` and `transaction()` for the module's own tables. `schema`, `executeQuery`, `getExecutor`, `destroy`, `introspection`, `$extendTables`, `$omitTables` and `$pickTables` are gone: code that runs `` sql`…`.execute(db) `` with a module's database, changes the schema or closes the connection injects the unscoped `Database`, or moves into a migration. `Database` without a module name is unchanged. - A statement kind the secret guard does not know is refused at run time, and so is a function name that is not an identifier, in `fn.agg` and quoted (`fn('"MyFunc"')`) too: write a plain or schema-qualified name (`pg_catalog.lower`), or use `` sql`…` ``. There is no way back. See [table types](https://marmeon.com/docs/queries.md#table-types) and [module boundaries](https://marmeon.com/docs/queries.md#module-boundaries). #### Medium: The migrations of a module come only from the app or its workspace *Likelihood of impact: low — apps with a module that reads its `migrations` from a package in `node_modules`, a link to another repository, or a place outside the app.* A module whose migrations lie in `node_modules` or outside the app and its workspace stops the start with D20: Bun with a symlink backend, Deno's npm cache, a `link:` to another repository, a volume outside the app root, a link to `node_modules` or outside in a subfolder of `migrations`, a real `node_modules` inside it, and a workspace root that everyone can write or another user owns. Monorepos with `pnpm-workspace.yaml` or `workspaces` and the lockfile in their root are not affected. Move the files, with the same names, into a module of your app and point `migrations` at them; new timestamps would make new migrations that create the tables a second time. If the app's module has another name, run `UPDATE migrations SET module = '' WHERE module = ''` once. A package brings its migrations through `marmeon publish`. There is no way back. See [migrations from a package](https://marmeon.com/docs/migrations.md#migrations-from-a-package). #### Medium: The page client's adapter API moves to `@marmeon/http/client/adapter` *Likelihood of impact: low — apps that drive the client core, write client features of their own or import page-protocol names.* - `useFeature()` and `navigator.use()` take only a stable `FeatureHandle`; `@marmeon/http/client` offers two, `hooks` and `tabSync`. Every other handle (`actions`, `islands`, `layers`, `live`, `liveValidation`, `prefetch`, `optimistic`, `remember`, `guard`, `instant`, `revalidateOnBack`, `queryState`, `selection`, `uploads`, `viewTransitions`, `devtools`), its API type, `Navigator`, `defineFeature` and the other building blocks of the client core come from `@marmeon/http/client/adapter`, which may change in any minor release. A handle that `defineFeature()` did not make throws a `TypeError`, and a feature it made is frozen. - `VisitOptions.ignoreGuards` takes `IgnoredGuard` (`message`, `active()`); a custom `ProgressIndicator` receives a `ProgressSource` instead of the navigator. - `pageInfo`, `pageName`, `scriptJson`, `ERROR_PAGE`, `LAYER_BACKDROP` and `matchesPath` move from `@marmeon/http/page` to `@marmeon/http/client/adapter`. - The page protocol has its own entry: the `*_HEADER` constants, `PAGE_SCRIPT_ID`, `MAX_LAYER_DEPTH`, the types `PageObject`, `RegionObject`, `OnceInfo`, `LayerInfo`, `LiveHint`, `LiveSubscription`, `RegionKind`, `RegionOutcomeStatus` and `LayerClose`, and `isPageObject`, `isPrefetch`, `isActionRequest` and `regionOf` come from `@marmeon/http/protocol`, no longer from `@marmeon/http` or `@marmeon/http/page`. Augmentations of `@marmeon/http/page` (`Views`, `SharedProps`, `FlashData`) stay. - No longer exported, without replacement: the `DEFAULT_*` constants, `SCROLL_REGION_ATTRIBUTE` (write the `scroll-region` attribute), `matchesRouteName`, `confirmRequest` and `nativeConfirm`, `isSensitiveField` and `SENSITIVE_FIELD` (use `isSensitiveRememberField`), and from the client entries of devtools and table `DevtoolsBar`, `installDevtoolsHook` and `parseSort`, `sortValue`, `propOf` (for a column's sort value write `-name` or `name`). There is no way back. See [writing a UI adapter](https://marmeon.com/docs/package-pages.md#writing-a-ui-adapter). #### Low: The page protocol has a version *Likelihood of impact: low — apps with a client of their own that sends `x-marmeon` headers, and tests that set them by hand.* A request of another protocol version gets a `409` before any controller runs, and the tab loads the page anew. A client of your own sends `x-marmeon: 1`. In tests, replace a hand-set `x-marmeon: 'true'` with the helpers of the test app (`navigating()`, `acting()`, `island()` …) or with `PROTOCOL_VERSION` from `@marmeon/http/protocol`. There is no way back. See [a tab of another protocol version](https://marmeon.com/docs/navigation.md#a-tab-of-another-protocol-version). #### Low: Test doubles come from `/testing`, and the internals of the packages are no longer exported *Likelihood of impact: medium — app tests that import fakes, and code that imported names the docs do not describe.* | Name | Import from | | --- | --- | | `TestClock`, `EventFake` | `@marmeon/core/testing` | | `QueueFake` | `@marmeon/queue/testing` | | `StorageFake`, `ExpectedContents` | `@marmeon/storage/testing` | | `ScheduleTester` | `@marmeon/scheduler/testing` | | `MailFake` | `@marmeon/mail/testing` | | `NotificationFake` | `@marmeon/notifications/testing` | | `twoFactorCode`, `authenticatedSession` | `@marmeon/auth/testing` | | `DevtoolsTester` | `@marmeon/devtools/testing` | | `BroadcastRecorder`, `LiveStreamReader`, `RecordedRefresh`, `LiveEvent` | `@marmeon/live/testing` | Tests that go through `createTestApp()` (`app.mail`, `app.notifications`, `app.queue` …) change nothing. Further: - `createHttpKernel()` and `TestApp.kernel` offer `fetch`, `request` and `settle` only. A test that faked the peer with Hono's env argument (`{ incoming: { socket: { remoteAddress } } }`) passes `{ remoteAddress }`. - `PinoLogger` is not exported: use `createPinoLogger()`. - `LocalDisk`, `MemoryDisk` and `S3Disk` are not exported: configure the disk in `defineStorage()`, or implement `Disk` for a driver of your own. - `MarmeonEntries` and `MarmeonPluginApi` (`@marmeon/vite`) become `MarmeonOptions['entries']`. - `new DatabaseHealthCheck(connections)` goes: `DatabaseServiceProvider` registers the check. - Every other name that left a package was not documented and lives under its `/internal` subpath, which may change in any release: the generated lint config forbids importing it, and `marmeon check` reports such imports. An app that needs one should open an issue. There is no way back. See [Fakes](https://marmeon.com/docs/fakes.md). #### Low: Some packages and options are experimental *Likelihood of impact: low — apps that use devtools, live, otel, table or tinker.* Nothing to change. These may change in a minor release now: `@marmeon/devtools`, `@marmeon/live`, `@marmeon/otel`, `@marmeon/table` (with `@marmeon/react/table` and `/table-tanstack`), `marmeon tinker`, the devtools feature of `@marmeon/http/client`, the Vite options `pages` and `lang`, the `devtools`, `broadcast` and `live()` helpers of the test app, and `ResolvePage.features`. See [experimental](https://marmeon.com/docs/releases.md#experimental). #### Low: The app's definition is apart from the options that boot it *Likelihood of impact: low — apps whose definition carries `env`, `phase`, `container` or `override`, and tests that pass `env` inside the definition.* - Move `env`, `phase`, `container` and `override` from the definition in `bootstrap/app.ts` into `createApplication(definition, { … })`. - `createTestApp({ ...definition, env })` becomes `createTestApp(definition, { env })`. The option layers over `.env` and the process environment instead of replacing them, so pin every key the test depends on, such as `DB_DRIVER`. - A package that augmented `ApplicationOptions` augments `ApplicationDefinition` and reads `app.definition` instead of `app.options`. There is no way back. See [Modules](https://marmeon.com/docs/modules.md). #### Low: The schemas of the framework's queued payloads are Standard Schemas *Likelihood of impact: low — code that passed such a schema to Valibot, for example `v.parse(SignedIn.schema, …)`.* For types, use `EventPayload`, `JobPayload<…>` or the named `…Payload` types; to validate, `SignedIn.schema['~standard'].validate(value)`. Run-time behaviour does not change. There is no way back. #### Low: `marmeon` exits with 2 when a command is called wrongly *Likelihood of impact: low — scripts that read exit code 1 as "called wrongly".* Check for 2 instead. Scripts that only test for a non-zero exit need no change. There is no way back. See [exit codes](https://marmeon.com/docs/console.md#exit-codes). #### Low: A cache store of your own is a driver, and its locks a `LockStore` *Likelihood of impact: low — apps with a cache store of their own, or code that typed a variable as `CacheStore` and locked through it.* - Register the store as a driver: `static cacheDrivers = { name: factory }` on a provider, whose factory returns `{ store, locks }`. The methods `lock`, `unlock`, `forceUnlock` and `lockOwner` move to the `LockStore` returned as `locks` (one object may be both). - `CacheStore` has no lock methods: `store.lock()` on a `CacheStore` does not compile; `new Lock(store, …)` takes a `LockStore`. - `CacheConfig.driver` is a `string`, so an exhaustive `switch` over it stops narrowing. `CACHE_DRIVER` accepts any lower-case name; a name no provider brought is refused at `boot()` with the known names. Apps that only use `Cache`, `cache.lock()` and `RateLimiter` change nothing. There is no way back. See [locks](https://marmeon.com/docs/cache.md#locks). #### Low: The passkey types come from `@marmeon/auth/passkeys` *Likelihood of impact: low — code that types passkey values with the types of `@simplewebauthn/browser` or `/server`.* Take the types from `@marmeon/auth/passkeys`. A value typed with the other ones may no longer compile against `Passkeys.register()`, `signIn()` or `confirm()`: `prf` values are base64url strings, and `attestationFormats` is `string[]`. There is no way back. See [Passkeys](https://marmeon.com/docs/passkeys.md). #### Low: A package's `"marmeon"` field holds only the keys the protocol knows *Likelihood of impact: low — apps that use a package with another key in the `"marmeon"` field of its `package.json`.* An unknown key (a misspelt `provider`, a `migrations` key) or a field that is `null`, `false` or a string stops the next start or `marmeon discover` with a message naming the package and the key. The package has to be fixed; until then use a version without the key, or `pnpm patch` / `overrides` it. A package author keeps `providers`, `browser` and `experimental` only, and declares migrations on the provider as `static migrations`. There is no way back. See [the package protocol](https://marmeon.com/docs/package-development.md#the-package-protocol). #### Low: `next()` takes the extension when any member of a union adds keys *Likelihood of impact: low — middleware declared with a union whose members add keys, such as `defineMiddleware<{ user: User } | {}>` or `next: Next` in a class, that calls `next()` without an argument.* Such a middleware no longer compiles: the next handler would read a key that was never set. Pass the extension to `next(…)`, or declare the keys as optional in one type (`{ user?: User }`). `{}` and `object` still allow `next()` without an argument. Run-time behaviour does not change. There is no way back. See [adding to the context](https://marmeon.com/docs/middleware.md#adding-to-the-context). ## Upgrading to 0.3.0 from 0.2.0 #### High: A server listens on 127.0.0.1 unless `HOST` says otherwise *Likelihood of impact: high — every app that runs `marmeon start` or `marmeon dev` outside the generated Docker image or the systemd unit and has to be reached from another machine.* Before, a server without `HOST` listened on every interface. Now `HOST` defaults to `127.0.0.1` in every environment, and `startServer()` falls back to it as well, so the server answers only the machine it runs on. A buildpack or PaaS that runs `marmeon start` itself, a load balancer or proxy on another host and a phone on the LAN that tests `marmeon dev` no longer reach it. Set the interface the server must answer on: ```sh HOST=0.0.0.0 ``` Behind a proxy on the same machine, in the generated image (its Dockerfile sets `HOST=0.0.0.0`) and with the systemd unit (`HOST=127.0.0.1`), nothing changes. Code that calls `heldOnLoopback(port, undefined)` directly has to pass the host, a plain `string`. The start line shows `127.0.0.1` as `http://localhost:PORT`. On macOS a program on `::` or `::1` with the same port does not stop a server on `127.0.0.1`, and `localhost` then reaches that program: before listening, the start tries `[::1]:PORT` and warns once when something answers (`PORT=0` skips the check). The way back is `HOST=0.0.0.0`, which listens on every interface as before. See [Configuration](https://marmeon.com/docs/configuration.md) and [Deployment](https://marmeon.com/docs/deployment.md). #### High: Accounts keep a session key that `UserProvider.updateSessionKey()` compares and sets *Likelihood of impact: high — apps made with `make:auth` and every custom `UserProvider` or `RememberTokenStore`.* `AccountSessions.end(id)` is new: it ends every session of an account on any session driver by deleting its remember-me tokens, rotating its session key and removing the session rows a store can find. For it, and for the races around password changes and signing out other devices, `UserProvider.updateSessionKey(id, key, expected)` is now a compare-and-set, `RememberTokenStore` has an `exists()` and `auth.updateSessionKey()` returns a `boolean`. A provider that returns nothing from `updateSessionKey()` makes the call throw, with the remedy in its message. What the app has to do: - **Apps made with `make:auth`:** add a nullable, secret `session_key` column to `users` (`table.string('session_key', 64).nullable().secret()`), and take `updateSessionKey()` and the `sessionKey` in `#credentials` from the stub's `UserRepository.ts`. Port `commands/ResetTwoFactorCommand.ts`: inject `AccountSessions`, call `end()` before removing the factors and check the factors again afterwards; without it `auth:reset-two-factor` leaves a lost device signed in, which can enrol a first factor of its own. Optionally copy `commands/EndSessionsCommand.ts` and register it for `marmeon auth:end-sessions --force`. - **A custom `UserProvider`:** `updateSessionKey(id, key, expected: string | null | undefined): Promise`. With a string or `null` it writes only if the stored key equals `expected` (`IS NULL` for `null`), in one statement, and returns whether it wrote; with `undefined` it writes regardless. `findById` has to hand the key back as `sessionKey`. - **A custom `RememberTokenStore`:** `exists(cookie): Promise`, by selector and consistent with `forgetUser()` at once (no cache, no lagging replica). - Code that uses the result of `auth.updateSessionKey()`: `false` means this session was ended meanwhile and is signed out. There is no way back; the interfaces require the new members. See [Authentication](https://marmeon.com/docs/authentication.md). #### High: Changing a second factor needs a second factor proven in the last 15 minutes *Likelihood of impact: high — apps with two-factor authentication or passkeys, made with `make:auth` or with their own routes for these methods.* `TwoFactor` (`begin`, `setup`, `regenerateRecoveryCodes`, `disable`) and `Passkeys` (`registrationOptions`, `register`, `remove`, `release`) require the second factor proven within the last 15 minutes (`FACTOR_CHANGE_MAX_AGE`) on an account that has one, and throw otherwise. Without the new middleware the two-factor and passkey routes answer 500 for such accounts once the proof is older, and the e-mail change and the API-token creation are refused only by this middleware. `confirm()` records a fresh proof only for the first factor, and registering the first passkey drops a TOTP setup begun before it. Add `confirmedSecondFactor({ verify: 'auth.two-factor.verify' })` after `confirmedPassword()` (accounts without a factor pass it): ```ts import { confirmedSecondFactor } from '@marmeon/auth/two-factor'; const factors = sudo.middleware(confirmedSecondFactor({ verify: 'auth.two-factor.verify' })); factors.post('/settings/tokens', CreateAccessTokenController); ``` and register these routes on `factors`: the two-factor settings page, setup, recovery codes and disable, the passkey page, options, store, release and remove, and `POST /settings/tokens`. For `PUT /settings/email`, add `.middleware(confirmedSecondFactor({ verify: 'auth.two-factor.verify' }))` after `confirmedPassword()` in its own chain and keep `throttle('email-change')`, as the stub does. Leave it off two-factor confirm, verify, the step-up routes and the passkey rename. The stub's `routes.ts` shows all of it. Also add `await twoFactor.requireRecentProof('changeEmail')` at the start of your `UpdateEmailController`, as the stub does, so an e-mail route added without the middleware is refused too. There is no way back. See [Two-factor authentication](https://marmeon.com/docs/two-factor-authentication.md). #### High: The `cookie` session driver is gone *Likelihood of impact: low — only apps that set `SESSION_DRIVER=cookie`.* A session kept in the cookie lives in the browser, so the server cannot end it: signing out other devices, a password change or `AccountSessions.end()` never reached it. `SESSION_DRIVER` accepts `file` (the default), `database`, `redis` or `memory`, and an app that still sets `cookie` fails at boot with a message naming the four. Choose one: `file`, `database` (publish the table with `make:session-table`) or `redis`. Existing cookie sessions end once; users sign in again. In code: `CookieSessionStore` (`@marmeon/session`) and `COOKIE_SESSION_WARNING` (`@marmeon/auth`) are removed; `SessionConfig['driver']` no longer includes `'cookie'`, so a comparison against it stops compiling; `new UserSessions(store)` requires its store. There is no way back. See [Sessions](https://marmeon.com/docs/session.md). #### High: Remember-me tokens are bound to the account state and need an `account_fingerprint` column *Likelihood of impact: high — apps made with `make:auth` and every app with its own `RememberTokenStore` or `UserProvider`.* Before, a remember-me token signed the account in as long as its row existed. Now each token stores the fingerprint of the account state the sign-in verified (the one sessions keep: a SHA-256 of the id, the password hash and the session key), and a cookie signs in only while the account still has it. A password reset, a new password, a new session key, `AccountSessions.end()` and a rehash after changed `HASH_*` costs therefore end every remember-me token of the account, not only its sessions. A token without a fingerprint is refused. `attempt()` also compares the account it verified with a fresh `findById()` after the password check, and answers `invalid-credentials` if the hash or the key changed meanwhile. What the app has to do: - **Add the column before the new code serves requests.** Until `remember_tokens.account_fingerprint` exists, remember-me sign-ins and requests with a remember-me cookie fail with a database error. Apps made with `make:auth` before this release need a migration, named with the current timestamp: ```ts import { defineMigration } from '@marmeon/database'; export default defineMigration({ up: (schema) => schema.alter('remember_tokens', (table) => table.string('account_fingerprint', 64).nullable()), down: (schema) => schema.alter('remember_tokens', (table) => table.dropColumn('account_fingerprint')), }); ``` Run it with `marmeon migrate`. The remember-me cookies of existing devices stop working once; those users sign in again. - **A custom `RememberTokenStore`:** `create(userId, expiresAt, fingerprint)` takes the fingerprint (a third, required parameter), stores it and returns it from `consume()` as `fingerprint`. `rebind(userId, cookie, fingerprint)` is optional: it keeps the device that changes its own key (`updateSessionKey()`, `logoutOtherDevices()`) signed in. Without it that device signs in again. - **A custom `UserProvider`:** `findForLogin()` returns `sessionKey` exactly as `findById()` does. If only one of them returns a key, `attempt()` throws an error that names the provider. There is no way back; a token without a fingerprint is never accepted. See [Authentication](https://marmeon.com/docs/authentication.md#remember-me). #### High: `marmeon start` refuses a development `NODE_ENV` that comes from `.env` *Likelihood of impact: high — every app that runs `marmeon start` or `pnpm start` locally, and every server, container, CI job or end-to-end test that gets `NODE_ENV` from a `.env` file.* Before, `marmeon start` served the app with the development tools (Vite, devtools, mail previews, error pages with source code) whenever `.env` said `NODE_ENV=development`, which is what the starter `.env` says, and only logged a warning. Now `marmeon start` and the hidden `marmeon serve` exit with 1 before any app code loads when `NODE_ENV=development` or `test` comes from `.env` alone. The message names the way out. `marmeon dev`, a `NODE_ENV` set in the process environment, and a `.env` without `NODE_ENV` or with `production` are unchanged. `queue:work` and `schedule:work` only warn, as before. What the app has to do: - **To try the build on your machine:** `NODE_ENV=production marmeon start` (`pnpm start` is the same, the app's `start` script is `marmeon start`). - **To run the development stack through `start` on purpose:** set `NODE_ENV=development` in the shell, or use `marmeon dev`. - **Servers, containers, systemd units, CI jobs and `webServer` entries of end-to-end tests** that relied on `.env` for `NODE_ENV` set `NODE_ENV=production` in the real environment. The generated Docker image and a server that already sets it need no change. The way back is `NODE_ENV=development` in the process environment, which is only worth it on a machine that is meant to run the development stack. See [Configuration](https://marmeon.com/docs/configuration.md) and [Deployment](https://marmeon.com/docs/deployment.md). #### Medium: A passkey confirms sudo mode, and some actions ask for the password again *Likelihood of impact: medium — apps that bind passkeys, and apps that call `Passkeys.remove()` or `TwoFactor.regenerateRecoveryCodes()` themselves.* A passkey proven now, with user verification, confirms sudo mode like a typed password, and a passwordless passkey sign-in counts as a fresh confirmation. So `passwordRecentlyConfirmed()` and `confirmedPassword()` no longer mean "a password was typed". This applies the moment the app upgrades: a passwordless passkey sign-in reaches `confirmedPassword()` routes straight away, whether or not the app adds the passkey confirmation routes. In a kit app made before this release the e-mail and API-token forms do not ask for the current password, so a passkey holder (who also passes `confirmedSecondFactor()`) can change the address or create a token until the app copies those fields. An action that lets whoever holds the passkey stay in the account has to ask for the current password in its own form, as the kit does for the e-mail change, API-token creation, removing any passkey and regenerating recovery codes. - `Passkeys.remove(id, password)` needs the password for every passkey; a call without one gets `invalid-password`. - `TwoFactor.regenerateRecoveryCodes(password)` takes the password and returns a `Result` (`invalid-password` | `throttled`) instead of the codes. - A `throttled` error from a password check may carry `account: true`: the account's cap held it up, and signing in again with the password lifts it. Password checks count per sign-in (5 a minute, 20 an hour) plus a per-account cap of 20 an hour for sessions that did not begin with a typed password. Existing sign-ins count against that cap until the user signs in again with the password. `takePasswordCheck()`, `clearPasswordCheck()` and `Auth.passwordCheckScope()` are public for app code. - `TwoFactorChallengeFailed.during` can be `'confirm'`; an exhaustive `switch` over it stops compiling until it handles the value. - Apps built from the kit: copy the current-password fields on the e-mail, API-token and recovery-code forms first, then the passkey confirmation controllers and routes (`auth.password.confirm.passkey.options`, `auth.password.confirm.passkey`), the new `throttle.ts` (per sign-in, with `auth`) and the sign-out of other devices in `RemovePasskeyController` from `packages/auth/stubs/react/modules/auth`. Sudo mode also needs a confirmation made within the current sign-in, a typed password or a passkey proven now. After `auth.login(user)` (a magic link, OAuth, impersonation) a route behind `confirmedPassword()` asks again, even once the second factor is completed. A confirmation older than the current sign-in, including one left in the session by an earlier account, does not count. There is no way back. See [Authentication](https://marmeon.com/docs/authentication.md#sudo-mode) and [Passkeys](https://marmeon.com/docs/passkeys.md#confirming-sudo-mode). #### Medium: Sign-ins, remember-me cookies and second-factor proofs have upper bounds *Likelihood of impact: medium — apps with `twoFactor()` areas, apps whose users stay signed in for more than a day, and apps with their own `RememberTokenStore`.* - `twoFactor()` without `maxAge` accepts a proof for 24 hours (`TWO_FACTOR_MAX_AGE`) instead of for the whole session; pass `maxAge` (seconds) for another window, there is no "never". A remember-me sign-in carries the proof of the device that made the token, so a token older than the window asks for the factor again. - `AUTH_REMEMBER_DAYS` accepts 0 to 30 (default 30); a value outside that stops the boot. A token older than the setting is refused even if its row says otherwise, and `auth:prune-tokens` deletes it, so schedule that command (the kit runs it daily). With `0` no remember-me cookie is made, a presented one signs nobody in and the kit hides the checkbox. - A sign-in lasts at most `AUTH_SESSION_MAX_HOURS` (default 24, up to 720) from the moment it was made, however active the user is, so users without remember-me are signed out 24 hours after signing in. A session restored by a remember-me cookie also ends with that token. Sessions open at deploy time start their clock at their next request, so this limit cuts nobody off at deploy. A valid remember-me cookie signs the user in again in the same request. Raise the value if 24 hours is too short; tests that jump the clock past 24 hours need a higher value too. - A custom `RememberTokenStore`: `prune(maxAgeDays: number)` deletes expired tokens and those made `maxAgeDays` or more days ago, and `consume()` must return a valid `createdAt` and `expiresAt`, or every remember-me sign-in is refused. - Apps made with `make:auth`: `ShowLoginController` passes `remember: config.remember`, and `Login.tsx` renders the checkbox only when it is true (see the stub). The way back is a larger `AUTH_SESSION_MAX_HOURS` (at most 720) and a `maxAge` on `twoFactor()`; the 30-day cap on remember-me has none. See [Authentication](https://marmeon.com/docs/authentication.md). #### Medium: The session cookie ends when the browser closes *Likelihood of impact: medium — every app with sessions; no configuration changes, but what users notice does.* The session cookie and `XSRF-TOKEN` are sent without `Max-Age`. The server still ends a session after `SESSION_LIFETIME` of inactivity and a sign-in after `AUTH_SESSION_MAX_HOURS`, whatever the browser keeps. - Users who do not tick "Keep me signed in" are signed out when the browser closes (unless the browser restores its session, and then it keeps the cookie). - A guest's session data ends at browser close: the chosen locale, the intended URL, flash data and anything the app keeps in the session, such as a cart. Keep what has to outlive the browser somewhere else. - Remember-me users go through a remember-me sign-in after every browser restart: the token rotates, `viaRemember()` is true, the session is new (new CSRF token, no old input), sign-in events fire more often, and `twoFactor()` areas ask again once the token's factor proof is older than their `maxAge`. - App tests that assert `Max-Age` on the session cookie or `XSRF-TOKEN` need updating. There is no way back; remember me is how a user stays signed in across a browser restart. See [Sessions](https://marmeon.com/docs/session.md). #### Medium: A second factor, a passkey and an API token need a confirmed address *Likelihood of impact: medium — apps made with `make:auth` that let anyone register or have users with unconfirmed addresses, apps with a custom `TwoFactorState`, and apps that listen to `TwoFactorDisabled` or `PasskeyRemoved`.* Before, an account with an unconfirmed address could add an authenticator app or a passkey and create API tokens. Someone who registered a victim's address first could add a factor and wait; the victim's password reset did not remove it. Now the starter kit puts authenticator setup and confirm, the passkey options and store routes and API-token creation behind `verified()` in every registration mode, and an unconfirmed address sees a notice with a resend link instead of the setup controls. And a password reset of an account whose address was never confirmed (`email_verified_at` and `first_verified_at` are `null`) removes, in the same transaction as the new hash, every passkey, the authenticator (a pending setup too), the recovery codes and the API tokens. What the app has to do: - **Apps made with `make:auth`:** copy `routes.ts` (the `verified()` group for the factor and token routes), the two settings controllers and views, the language keys and the `NotifyAboutTwoFactorDisabled` and `NotifyAboutPasskeyRemoved` listeners from `packages/auth/stubs/react/modules/auth`. Your own routes that add a factor or create a token need `verified()` too. - **A custom `TwoFactorState`** implements `removeAll(userId): Promise`. TypeScript refuses a source without it, and a password reset throws a `TypeError` before the reset token is spent when the bound source has none. - **Listeners:** `TwoFactorDisabled.via` can be `'reset'` and `PasskeyRemoved` has a `via` (`'user'`, `'reset'`; jobs queued before the upgrade read as `'user'`). Handle the new value; the kit sends one `disabled_by_reset` mail instead of one mail per factor. - **The `UserProvider`** has to load `email_verified_at`. Without it the reset keeps the factors and logs a warning once. - Creating an API token now needs a confirmed address, like adding a factor. There is no way back. See [Security](https://marmeon.com/docs/security.md), [Two-factor authentication](https://marmeon.com/docs/two-factor-authentication.md) and [Email verification](https://marmeon.com/docs/verification.md). #### Medium: Open uploads are capped per session and in total *Likelihood of impact: medium — apps with file upload fields; forms that take many or large files in one session notice, and apps with an existing `temporary_uploads` table need one migration.* Before, a client could ask for any number of upload targets and leave the files unsent for a day. Now a session may hold `UPLOADS_MAX_OPEN` open uploads (default 20) with at most `UPLOADS_MAX_OPEN_MB` megabytes announced (1024), and all sessions together at most `UPLOADS_MAX_OPEN_TOTAL_MB` (10240, `0` turns this one off). Every open upload counts for at least 64 KiB. A target past a limit gets a 429 with `Retry-After`; a file larger than a limit could ever take gets a 422 with the real maximum. The bytes of a file are cut off at the announced size (a 413 above it), and on S3 the presigned POST binds that size. `uploads:prune` deletes unused uploads as soon as their token expires (`UPLOADS_LIFETIME`, default 120 minutes), not only after 24 hours; used uploads still go by age. What the app has to do: - **An existing `temporary_uploads` table** gets the two indexes the counts use. Add the migration shown in [File storage](https://marmeon.com/docs/storage.md#the-uploads-table), named with the current timestamp, and run `marmeon migrate`. Without it the counts scan the table. Tables made by the current `make:uploads-table` have them. - **Forms with many or large files per session** raise `UPLOADS_MAX_OPEN` and `UPLOADS_MAX_OPEN_MB`, and `UPLOADS_MAX_OPEN_TOTAL_MB` for a busy app. - **Keep `uploads:prune` scheduled every hour;** it is also what frees the room an abandoned upload takes. - **A client of your own** has to announce the true file size with the target, as the built-in client does. The way back is high values for the three variables, or `0` for the total; the per-session limits cannot be switched off. See [File storage](https://marmeon.com/docs/storage.md#uploads). #### Medium: Vite reads no `.env` file and no `VITE_*` variable *Likelihood of impact: low — only apps that read `import.meta.env.VITE_*`, or set their own `envDir` or `envPrefix` in the Vite config.* Before, Vite read the `.env*` files and wrote every `VITE_*` variable that client code reads, from those files or from the process environment, into the public bundle. Now `marmeon()` sets `envDir: false` and a prefix no variable uses, so `import.meta.env.VITE_*` is `undefined` in client and server (SSR) code, without an error. `MODE`, `DEV`, `PROD`, `SSR` and `BASE_URL` stay. Without `viteEnv`, the plugin refuses at start an app's own `envDir` or `envPrefix`, and a prefix another plugin adds; the message names `viteEnv: true`. What the app has to do: - Move the values to [shared props](https://marmeon.com/docs/configuration.md#values-for-the-browser), or set `marmeon({ viteEnv: true })` in `vite.config.ts` (and in `vitest.config.ts` if the tests read them). - An app that sets its own `envDir` or `envPrefix` fails to start until it sets `viteEnv: true`. The way back is `marmeon({ viteEnv: true })`; then every `VITE_*` variable of the process and of the `.env` files is public again. See [Vite](https://marmeon.com/docs/vite.md#environment-variables). #### Medium: Apps made with the starter kit copy its security fixes by hand *Likelihood of impact: medium — every app made with `make:auth` or `create-marmeon` before this release; the code stays as it is, the apps own their copies of the kit and only gain the fixes below when they copy them.* An app owns the files `make:auth` and `create-marmeon` wrote, so a framework update changes none of them. Each change below is in `packages/auth/stubs/react/modules/auth` (or the new-app template); compare your copy with it. Ordered by what it protects, security fixes first: - **Sign-in limits per client and per account** (security). Without them an IPv6 host owns a whole /64 of rate-limit buckets, one client can try unlimited passwords at argon2 cost, and guesses spread over many clients against one account are never stopped. - Copy `AuthServiceProvider.ts` (every address-based limit keys on `clientKey(ctx.ip)` from `@marmeon/cache`, and the new `login-client` limit of 30 a minute), `controllers/LoginController.ts` (the key is `login:|`) and `routes.ts` (`throttle('login-client')` on `POST /login`). In your own limiters, replace `by(ctx.ip)` with `by(clientKey(ctx.ip))`. - For the ceiling of 100 failed password sign-ins an address may take a day (the 101st gets `auth.login.locked`, even with the right password): copy `account-failures.ts`, `jobs/SendLockoutMailJob.ts` and `mail/LockoutMail.ts`, add the `login.locked` and `mail.lockout.*` texts to `lang/en.ts` and `lang/de.ts`, register the job in `index.ts`, and update `LoginController` (takes `Queue`), `ResetPasswordController` and `PasskeySignInController` (take `RateLimiter`). Anyone who knows an address can lock its password sign-in for a day; the owner gets back in with a password reset or a passkey. Use the `database` or `redis` cache store and keep `cache:prune` scheduled, since each address tried leaves a cache entry for a day. - If you keep `auth.test.ts`, `@marmeon/server` becomes a dev dependency. - **A rehash never writes an old password over a reset** (security). Without it, a password reset that lands between a sign-in's password check and its rehash is overwritten by the old password. In `UserRepository.ts`, `updatePasswordHash(id, hash, expected?)` returns a `boolean` and writes only `where password = expected` in one statement (as the stub does; the column is a secret, so the comparison is a raw `sql` fragment). A provider that returns nothing still works but keeps the race. - **Secret files stay out of git** (security; new apps only get this by themselves). Without it only `.env` is ignored, and `make:docker`'s `.env.production` with production secrets can be committed by `git add -A`. Add to `.gitignore`: ``` .env* !.env.example !.env.test ``` Run `chmod 600 .env` (a `.env` copied from `.env.example` is readable by group and others; `marmeon key:generate` now creates it as 0600 and tightens an existing one before writing the key). If `.env.production` is already committed, run `git rm --cached .env.production` and rotate every secret in it. `.env.test` stays committed, so it must never hold real credentials. - **At most one "account exists" mail per address and hour** (security: abuse). Without it anyone can flood an owner's inbox through the public sign-up form of an app with private registration. Copy `jobs/SendAccountExistsMailJob.ts` (it takes a `RateLimiter`, keys on the hash of the stored address and clears the window if mailing throws). The sign-up answer does not change. - **The remember-me mail** (text and mails only). The owner is now told about every old or altered remember-me cookie, not only about the validator replaced just before. Reword `mail/SignInMail.ts` and the matching keys in `lang/en.ts` and `lang/de.ts` from the stub. There is no way back for the framework side; each copy is yours to take or leave. See [Starter kit](https://marmeon.com/docs/starter-kit.md), [Rate limiting](https://marmeon.com/docs/rate-limiting.md#keys-and-the-clients-address) and [Configuration](https://marmeon.com/docs/configuration.md). #### Low: Confirming a second factor can answer `signed-out` *Likelihood of impact: low — only apps with their own controllers for `TwoFactor.confirm()` or `Passkeys.register()`, or built from the kit before this release.* Confirming an authenticator app or registering a passkey checks, inside the transaction that stores the factor, that the session still belongs to the account. A sign-out elsewhere, a password change or a deleted account that lands first makes `TwoFactor.confirm()` and `Passkeys.register()` return the new error kind `signed-out`, and nothing is stored. - `ConfirmError` and `RegisterError` have the new kind; an exhaustive `switch` over them stops compiling until it handles it. - Apps built from the kit: add the `signed-out` case to `ConfirmTwoFactorController` (redirect to `auth.login`) and `RegisterPasskeyController` (answer 401), and let `Passkeys.tsx` go to the sign-in on a 401, as in `packages/auth/stubs/react/modules/auth`. - A custom `UserProvider` whose `updateSessionKey` skips no-op writes must still return `true` for `updateSessionKey(id, k, k)`; a provider that answers otherwise gets an error naming the rule. - `TwoFactor`'s constructor takes `Connections` as its last parameter. Only code that builds it by hand notices; the container resolves it. There is no way back. See [Authentication](https://marmeon.com/docs/authentication.md). #### Low: `LiveStreamRequest` takes `accounts` instead of `account` *Likelihood of impact: low — only code that calls `LiveHub.open()` itself.* A live stream is now filed under one keyed scope per key of `APP_KEY` and `APP_PREVIOUS_KEYS`, so an end announced during a key rotation closes the streams of processes on the old and on the new key alike. `LiveStreamRequest.account?: string` became `accounts?: readonly string[]`. The built-in live endpoint does this itself. Code that calls `LiveHub.open()` passes `accounts: LiveTokens.accountScopes(scope)` instead of `account: LiveTokens.accountScope(scope)`. TypeScript flags the old property. The way back is none; the old property is gone. See [Real-time](https://marmeon.com/docs/realtime.md). ## Upgrading to 0.2.0 from 0.1.3 #### High: Every route has to say who may call it *Likelihood of impact: high — every app with routes that has not stated an access decision.* The app refuses to start (and `marmeon route:types` and `marmeon build` exit 1) while a route does not say who may call it. The error is a `RouteAccessError`; it lists each route with its methods, path, name, controller and the file and line that registered it: ``` 2 routes do not say who may call them: GET /posts posts.index PostController modules/posts/routes.ts:4 POST /posts posts.store Closure modules/posts/routes.ts:5 Say it with one of these: - can(Policy, 'ability', 'param') as the request's `authorize`, or on its registrar: Route.authorize(can(…)) - a check of your own: Route.authorize((ctx) => …) or `authorize` in defineRequest() - everyone, last: Route.authorize(everyone) says anyone its middleware lets through may call it — nothing else about it is checked See docs/authorization.md#every-route-decides. ``` Start the app, then decide each route listed: - `can(Policy, 'ability', 'param')` wherever the route reaches a record that belongs to someone, as the request's `authorize` or on the registrar: `Route.authorize(can(…))`. - `everyone` where the route's middleware is the whole decision: `Route.middleware(authenticate()).authorize(everyone)`, or `defineRequest({ authorize: everyone })`. - A route file that decides once for all its routes: `const Route = Root.authorize(everyone)`. That is the old behaviour, now written down. A route that is open to `everyone` and loads a record from the URL without `scopedBy` is refused as well. Give it a policy, scope the binding (`bind('child', Binder, { scopedBy: 'parent' })`), or, for a route that only reads (`GET`/`HEAD`) and whose records are really public, mark the binding `bind('param', Binder, { public: true })`. A write under `everyone` is never excused by `public`. With `tableRoutes(…)` under a registrar that only says `everyone`, give every action, bulk action and export its own `.authorize(…)`. `Router.dispatch` refuses undecided routes and open unscoped bindings too, so tests that dispatch a route need a decision as well. `FRAMEWORK_ROUTES` is no longer exported from `@marmeon/http` or `@marmeon/router`, and without that marker `load()` throws for any path under `/_marmeon/`; a package that used it moves its routes to a prefix of its own and decides them like an app does. Routes are registered synchronously now: the root registrar is sealed once the route files have loaded, so a `defineRoutes(async …)` callback, or a registrar kept and used after loading, fails at load. Move the `await` out of the route file. A request's `authorize` that returns a truthy value other than `true` (possible from untyped code only) now answers 403. There is no way back to routes without a decision. See [Authorization](https://marmeon.com/docs/authorization.md#every-route-decides). #### Medium: `Auth.attempt()` and `Auth.login()` can wait for a second factor *Likelihood of impact: medium — only when an account has a second factor (TwoFactorState bound); an app that does not bind two-factor authentication never sees the new case.* `attempt()` can now fail with `{ kind: 'two-factor-required', factors }` after a right password, and `login()` returns `'signed-in' | 'two-factor-required'` instead of `void`. In that case nobody is signed in: no `Login` event, no remember-me cookie. A caller that ignores the new case leaves the user signed out. Before: ```ts const signedIn = await auth.attempt(email, password); if (!signedIn.ok) throw new ValidationError({ email: ['These credentials do not match.'] }); await auth.login(newUser); return redirect('/dashboard'); ``` After: ```ts const signedIn = await auth.attempt(email, password); if (!signedIn.ok) { if (signedIn.error.kind === 'two-factor-required') return redirect('/two-factor-challenge'); throw new ValidationError({ email: ['These credentials do not match.'] }); } if ((await auth.login(newUser)) === 'two-factor-required') return redirect('/two-factor-challenge'); return redirect('/dashboard'); ``` A `switch` over `error.kind` that is exhaustive fails to compile until it handles the new kind; the starter kit's login page and the `make:auth` stub do. The way back is not to bind two-factor authentication: the case never occurs without it. See [Two-factor authentication](https://marmeon.com/docs/two-factor-authentication.md). #### Low: A custom `RememberTokenStore` has to return `createdAt` *Likelihood of impact: low — only apps with their own `RememberTokenStore`; the database store of `@marmeon/auth` already does.* `consume()` now returns `createdAt` next to `userId`, `cookie` and `expiresAt`: when the token was first made, kept across rotation, written with the app's clock and a time zone. It must be the token's original creation time as a valid `Date`: never the time of `consume()`, never `new Date()`. Two-factor authentication refuses a remember-me token whose `createdAt` is not after the factor was turned on, so a wrong value lets tokens from before the factor through. TypeScript points to the store that lacks the field. Before: ```ts return ok({ userId: row.user_id, cookie, expiresAt }); ``` After: ```ts return ok({ userId: row.user_id, cookie, expiresAt, createdAt: new Date(row.created_at) }); ``` There is no way back; the interface requires the field whether or not two-factor authentication is bound (at runtime it is read only with a `TwoFactorState` bound). #### Low: `LoginVia` has a fourth member, `'passkey'` *Likelihood of impact: low — only code that switches exhaustively over `Login.via`.* A sign-in with a passkey alone reports `via: 'passkey'` next to `'attempt'`, `'login'` and `'remember'`. A `switch` over `event.via` that must be exhaustive fails to compile until it handles the new value; nothing changes at runtime for an app that does not bind passkeys. --- # Releases and Support ## Introduction This page says how Marmeon is versioned, what a version number promises, which versions get fixes and security fixes, which platforms are supported, what is public API, what a release candidate is, and how you upgrade. Every package of the framework carries the same version, so one number describes the whole framework: ```sh pnpm up --latest "@marmeon/*" marmeon ``` That command moves every framework package of an app to the newest version at once. The changes of each version are in the [upgrade guide](https://marmeon.com/docs/upgrading.md), and each release adds the merged pull requests that change something for users to the packages' `CHANGELOG.md` files and to the GitHub Release. ## One version for the whole framework Every `@marmeon/*` package, the command `marmeon` and `create-marmeon` are released together, always with the same version. The packages name each other at exactly that version. A new app gets them that way, and you keep it so: upgrade them together, never one alone. Two versions of a framework package in one app would bring two containers and two sets of tokens that do not know each other. ## What a version promises ### From 1.0 on Breaking changes come only in a major version, except for a [security hardening](https://marmeon.com/docs/releases.md#what-is-public-api). A feature to be removed is [deprecated](https://marmeon.com/docs/releases.md#deprecations) first, in a minor version, and goes in the next major version, with its entry in the upgrade guide. A minor version adds, a patch fixes; neither breaks. What is outside the [public API](https://marmeon.com/docs/releases.md#what-is-public-api) is outside this promise. [Which versions get fixes](https://marmeon.com/docs/releases.md#which-versions-get-fixes) is a separate question. Pin the exact version, as `create-marmeon` does. A fix for an older line is published under the npm dist-tag `latest-` (`latest-1`) and never moves `latest`. An app that stays on that line gets it through `pnpm up "@marmeon/*" marmeon` when its range allows the version (`^1.0.0`), or installs it by name (`pnpm add @marmeon/core@latest-1`, then the same for the other packages); an exact pin changes by hand. ### Before 1.0 Up to 0.4, Marmeon was at 0.x. A minor version, such as 0.3 to 0.4, could break, and every break has an entry in the [upgrade guide](https://marmeon.com/docs/upgrading.md); a patch never broke, except for a security hardening. 0.x gets no fixes any more: the way forward is [Upgrading to 1.0.0 from 0.4.0](https://marmeon.com/docs/upgrading.md#upgrading-to-100-from-040). ## Release candidates A release candidate, `x.y.z-rc.N`, is a preview of the release `x.y.z`. It comes under the npm dist-tag `next` and never moves `latest`, so an app only gets one when it asks: `pnpm add -E @marmeon/core@next`, and the same for every other framework package, all in the same version. To start an app from a candidate, run `pnpm create marmeon@next my-app`; on the day a candidate appears, [pnpm installs an older version](https://marmeon.com/docs/installation.md#the-first-day-after-a-release) unless you let the framework through. A package added later takes the version of the app (`marmeon add redis`, or `pnpm add -E @marmeon/redis@`), not `next`, which may be newer than the app's. [`marmeon check`](https://marmeon.com/docs/check.md#the-packages-check) finds a package that is not. From the first candidate to its release, only bug fixes, documentation and internals change; the public API is the one the release will have. The exception is a security hardening: it may come all the same and brings the next candidate. A hardening that breaks an app can move the release to the next breaking version. A candidate gets no fixes once its release has appeared: move to the release with `latest`, because `next` may still point at the last candidate. Report a bug in the issues, and a vulnerability as the [security policy](https://marmeon.com/docs/security-policy.md) describes. ## Which versions get fixes The current major version gets fixes in its latest minor version. The previous major version still gets **security fixes for 12 months** after the next major version is released, as patches on its last minor version, published under the dist-tag `latest-` like [any older line](https://marmeon.com/docs/releases.md#from-10-on). 0.x gets no fixes at all. It never had a support window, and the way forward is [Upgrading to 1.0.0 from 0.4.0](https://marmeon.com/docs/upgrading.md#upgrading-to-100-from-040). | Version | Fixes | Security fixes | |---|---|---| | Current major | latest minor version | latest minor version | | Previous major | no | 12 months after the next major is released | | Older majors | no | no | | 0.x | no | no | The docs of every release line from 1.0 on stay at `https://marmeon.com/docs//` (`/docs/1.x/`), and the docs of the version you have installed are in `node_modules/marmeon/docs/`. The [security policy](https://marmeon.com/docs/security-policy.md) explains how to report a vulnerability. ## Supported platforms A "major version" in this section means the next breaking release: a major version from 1.0 on, a minor version before. ### Node Marmeon supports the LTS lines of Node from 26 on. Today that means Node 26.10 or newer (`engines` in every package). The rules for changing it: - A line is dropped only after its end of life, and only in a major version. - Within a line, the minimum version rises in a minor version only for a security fix in Node. - Supporting a new LTS line is a minor change. ### Operating systems Linux and macOS. On Windows, use WSL 2. Supporting one more operating system is a minor change. ### TypeScript and ES modules An app needs TypeScript 7 and the options of the starter's `tsconfig.json`: `erasableSyntaxOnly`, `verbatimModuleSyntax` and a `lib` with `ESNext.Temporal`. The packages are ES modules only; there is no CommonJS build. ### Libraries the framework builds on - **Peers**: React, React DOM, Vite, Vitest, the OpenTelemetry API, TanStack Table, and the drivers an app picks (`pg`, `mjml`, the AWS SDK). Supporting one more major version of a peer is a minor change; dropping a major version is a major change. - **Kysely**: you write Kysely's builder through `@marmeon/database` and never import the `kysely` package. It is an exact dependency of the framework, not a peer. The shape of the builder (methods, `eb`, result types) is public API: a Kysely update that changes it comes only in a Marmeon major version, with an entry in the [upgrade guide](https://marmeon.com/docs/upgrading.md). An update an app does not notice comes in a minor version, with a `Low` entry there. Security fixes of Kysely are taken into every supported line. Which version that is: [database](https://marmeon.com/docs/database.md#kysely-and-its-version). - **`@faire/mjml-react`**: the components of `@marmeon/react/mail` stand on it, in an exact version that is a dependency of `@marmeon/react`. You never install or import it. The promise covers the API of `@marmeon/react/mail`: the names of its components, their prop types, their checks and what `toMjml` returns. The library under them may be updated, forked or replaced in a minor version when an app notices nothing. See [mail](https://marmeon.com/docs/mail.md#the-library-under-the-components). ## What is public API The promise of a version covers the public API. These are part of it: - The exports of each package's entry points, `.` and the documented subpaths, types included. - The contracts an app implements for authentication ([listed here](https://marmeon.com/docs/authentication.md#what-your-app-implements)): `SignInStore`, `PasswordResetTokenStore`, `AccessTokenStore` and `TwoFactorState` of `@marmeon/auth`, and `SessionStore` of `@marmeon/session`, are abstract classes your store extends. A member added later has a default, unless it is [security-relevant](https://marmeon.com/docs/authentication.md#security-relevant-members): that comes only as a security hardening or in a major version and never has a default. `UserProvider` and `Hasher` are interfaces: a security-relevant member is added the same way; any other member is optional. - Other interfaces an app implements itself, such as the drivers of cache, queue and storage: a new required member is a break. An extension arrives as an optional member, or as an optional argument a driver may ignore. - Interfaces your code is given but does not implement: `Disk`, `Storage`, `Broadcaster`, `HttpKernel`, `Prompt`, `Output`, `CommandInput` and `DevtoolsStore`. A later release may add a member to them. A disk of your own implements `DiskDriver`. - A class you extend (`Repository`, `Controller` …) may gain members in a minor release. A member of your subclass with the same name may then need another name; the [upgrade guide](https://marmeon.com/docs/upgrading.md) lists each such member with a `Low` line. - The names and defaults of environment variables. - The export condition `@marmeon/source`: its name and its meaning, as [a package in your app's workspace](https://marmeon.com/docs/package-workspace.md#a-package-in-your-apps-workspace) uses it. `@marmeon/vite` applies it to what it resolves in development and in tests. An installed `marmeon build` and `marmeon start` never add it. - The commands of `marmeon`, their flags and exit codes. A minor version may add a command. A command of your own with the same name then stops `marmeon build` and the start with K8 and needs another name; the [upgrade guide](https://marmeon.com/docs/upgrading.md) lists each new command with a `Low` line. A name in your module's group, such as `notes:prune` (the default of `make:command`), does not meet one. - The flags and exit codes of `create-marmeon` ([listed here](https://marmeon.com/docs/installation.md#options)). The files it writes are not: they follow the starter kit of its version, `marmeon-stubs.json` records where they came from, and the release notes name changes. - The JSON body of an error: the keys `message` and `errors` (a field's dotted path, a list index as a number, to a list of messages); the status code of each error class (`ValidationError` 422, `HttpError` its status); and the error codes, the [server's](https://marmeon.com/docs/errors.md#server-error-codes) and the [browser's](https://marmeon.com/docs/errors.md#error-codes) `C` and `R` alike: a code keeps its meaning and never moves to another error, and an error may get a code later. The text of a message is not API. - The documents `--json` prints, by their `format`. - The place of the documentation of an installed version, `node_modules/marmeon/docs/`, and `docs/index.json` there (`format` 1: `version` and `sections` with each page's `slug`, `label`, `title` and `file`, relative to the package). - The table schemas of the migrations the framework ships, the stubs and the `make:*` tables. The migrations the framework's packages ship, the starter kit's among them, are append-only: a released file never changes, and a change of a table is a new file ([tables](https://marmeon.com/docs/package-tables.md#tables)). - `defineMigration`, `up(schema)` and the schema builder, including which plans they accept and what they create: a migration that ran keeps its meaning. - The protocol between client and server: headers ([listed here](https://marmeon.com/docs/navigation.md#the-headers-of-the-protocol)) and the page object. - Stored and wire formats: queue payloads, sessions, encrypted values, tokens, cookies, the record of migrations and the generated files, as [listed below](https://marmeon.com/docs/releases.md#stored-and-wire-formats). - Translation keys, `@marmeon/react/styles.css` (its classes and custom properties) and the names of diagnostics channels and the shape of their messages. - The span names and the attribute names `@marmeon/otel` records ([listed here](https://marmeon.com/docs/observability.md#what-it-records)): the `{method} {route}`, `send `, `process `, `schedule `, `mail `, `notify `, `live refresh` and `render ` names, the attributes under `marmeon.`, and the ones of OpenTelemetry's semantic conventions the framework sets (`http.*`, `url.*`, `db.*`, `messaging.*`, `error.type`, `deployment.environment.name`). Dashboards and alerts are built on them, so a rename or a removal is a break. A new attribute or a new value of one is not. - The keys of a table's state in the URL ([listed here](https://marmeon.com/docs/tables.md#the-url-is-strict)): `sort` (a column alias, `-` for descending), `page` or `cursor`, `per_page`, `search` and `filter[]` (a day range as `YYYY-MM-DD..YYYY-MM-DD`), each with the table's prefix (`members_sort`). People bookmark and share these URLs. A key does not change its name or its meaning, and a value that was valid stays valid. - The field names of the JSON log line ([listed here](https://marmeon.com/docs/logging.md#the-fields-of-a-json-line)): `level`, `time`, `msg`, `appEnv`, `requestId`, `job`, `jobId`, `attempt`, `task`, `trace_id`, `span_id`, `trace_flags` and `err` with its `type`, `message` and `stack`, for an error the app logs as `{ err: error }`. The fields the framework writes for its own errors (`exception`, `stack` and sometimes `message`) are not part of this set yet. Log shippers parse them, so the name and the meaning of a field stay; a new field is not a break. The text of a message is not part of it. - The health endpoints ([health.md](https://marmeon.com/docs/health.md#liveness-and-readiness)): the path `SERVER_HEALTH_PATH` names and `/ready` below it, their status codes (`200`, `503`), and the `status` of `/up/ready`: `ok`, `failing` or `draining`. The details a check adds in development are not part of it. - The framework's data attributes that [Styling state](https://marmeon.com/docs/styling.md#styling-state) lists, plus `data-marmeon-failure` and the progress bar's `data-marmeon-progress`, and the custom properties an app sets on `:root`: the three `--marmeon-progress-*` and the four `--marmeon-failure-*` ([the framework's look](https://marmeon.com/docs/styling.md#the-frameworks-look)). A stylesheet selects on them. A new attribute or a new value of one is not a break. Any other `data-marmeon-*` attribute the components render is internal. - The entry types of `@marmeon/devtools`: a field may come to an entry, and in 1.x none is renamed or removed. Not part of it are `./internal` subpaths, anything marked `@internal` or [experimental](https://marmeon.com/docs/releases.md#experimental), a command marked `static hidden` (the snapshot lists those apart as "Hidden commands (not API)") except `serve`, which `marmeon start` runs, and the wording of messages and logs. The JSON API of the [devtools](https://marmeon.com/docs/devtools.md#for-other-tools) is covered through its `version`: the answer of `/_marmeon/devtools/api` names the version of the API, and a tool reads the other answers by it. The routes and the envelopes of the answers change only together with a new `version`; the entries inside them follow the rule of their types above. The devtools exist only in development. The same list decides, already in 0.x, whether a pull request is a `breaking` one. > [!WARNING] > **Security hardening.** A security hardening may break in a minor or a patch version. It then has an entry of its own in the > [upgrade guide](https://marmeon.com/docs/upgrading.md). Leaving a vulnerability open to keep an API protects nobody. ### Stored and wire formats Anything that outlives a process or travels between two of them is a format: a record in a queue, a session in its store, a cookie, a header between a tab and a server, a file the framework generates. Each carries a mark in a fixed place, and the meaning of that mark never changes. A reader knows a set of versions, today one per format, and treats data by that set: - **Newer than it knows:** it leaves the data alone. A newer process may be running, and what it wrote is not for an older one to overwrite, delete or guess at. The reader refuses, or treats the request as one without the data. Two things end such data all the same: a worker lets a record it cannot read fail after six hours, which takes it out of the queue, and a sign-in or sign-out on an older node ends the newer session of that request. - **Older than it supports, or without a mark:** it never interprets the data. What a migration can carry over, `marmeon migrate` carries over (the framework's tables). Everything else counts as missing: a session starts anew, a cookie is not read, a job fails with its reason and stays readable in the failed jobs. A reader never guesses and never falls back to a default. | Format | Mark | A newer version is | An older one, or none, is | | --- | --- | --- | --- | | [Page protocol](https://marmeon.com/docs/navigation.md#a-tab-of-another-protocol-version) | the header `x-marmeon: 1` on every request of the client | answered with `409` before routing, whatever the method | the same: an old tab sends `true`, or nothing | | Page object and region object (JSON) | none; new fields are optional | carried along; without `component`, `props` and `url` it is no page | read as they are | | [Live stream](https://marmeon.com/docs/realtime.md#a-stream-of-another-version) | `v=1` in the query of `GET /_marmeon/live`; the frames are frozen with it; the message between nodes (over Redis, and in the `live_hints` table) carries `"v":1` | answered with `204` and no stream, so the browser stops reconnecting; the tab asks again every 30 s until its next visit reloads it | the same: a tab of the release before sends no `v` | | [Job record](https://marmeon.com/docs/queues.md#deploying-while-jobs-wait) | `v` in the payload | put back untouched until a worker reads it; after six hours it fails and leaves the queue | failed at once with the reason, never run | | [Queued listener](https://marmeon.com/docs/events.md#queued-listeners) | the listener's `static listener` name, within its event | put back like an unknown job | failed like any record without a version | | [Session](https://marmeon.com/docs/session.md#what-a-session-stores) | `_v` in the payload | the request is a guest's; the stored session stays as it is | dropped, a new session starts | | [Session and remember-me cookies](https://marmeon.com/docs/session.md#the-__host--prefix) | the name, with `__Host-` when cookies are `Secure` | n/a | a cookie under another name is never read | | [`XSRF-TOKEN` cookie](https://marmeon.com/docs/csrf.md#the-token) | the name; the value is the session's CSRF token, unencrypted, and `xsrfToken()` of `@marmeon/http/client` reads it | n/a | a request of the client core without the cookie sends no token, and a write that needs one fails with `419`; a `` without JavaScript sends `_token` from the page data | | [Record of migrations](https://marmeon.com/docs/migrations.md#how-the-migrator-keeps-track) | the columns of `migrations` (and of `migration_lock`) | `migrate` refuses; every query on the connection fails and `/up/ready` is red | `migrate` adds `checksum` and records each file as it is then; until it ran, every query fails (D2) and `/up/ready` is red | | [Encrypted values](https://marmeon.com/docs/encryption.md#what-the-key-protects) | a version byte, and a context per use (`cookie:`, `session:`, `queue:v1:`) | `DecryptError` | `DecryptError` | | [API tokens](https://marmeon.com/docs/api-tokens.md#the-token-format) | the prefix, and a hash under its own domain | not a token: 401, like an unknown one | no longer valid: 401, like an unknown one | | [Link tokens](https://marmeon.com/docs/urls.md#a-link-that-is-used-once) (`linkToken()`) | the hash: SHA-256, in hex, of `marmeon.link-token.v1`, a NUL character and the token | a token is found by the hash of the release that made it | a hash of another scheme is not found, like an unknown token (see [moving from a hash of your own](https://marmeon.com/docs/urls.md#moving-from-a-hash-of-your-own)) | | [Generated types](https://marmeon.com/docs/queries.md#table-types) (`bootstrap/routes.ts`: 1, `bootstrap/database.d.ts`: 3) | `// @marmeon-format ` on the third line | `--check` fails with "update `@marmeon/*`"; no command overwrites it | `--check` says another version wrote it; regenerate | | [Copied files](https://marmeon.com/docs/starter-kit.md#what-the-auth-module-holds) (`marmeon-stubs.json`) | `format` in the file | `make:auth` and `publish` stop and write nothing; the check reports it as soon as a direct dependency declares migrations | `make:auth` and `publish` stop and write nothing: there is no older version | | [Schema projection](https://marmeon.com/docs/migrations.md#what-the-migrations-describe) (`.marmeon/schema.json`) | `format` in the file, and the version of `@marmeon/database` | computed again and written over: the file is a cache | computed again and written over | | [Injection lists and island marks](https://marmeon.com/docs/container.md#where-the-lists-come-from) (`.marmeon/injections.json`: 2) | `format` in the file | every module is analysed at start, as without a build, and the start says the artifacts are missing; the file stays as it is | the same: a version 1 file is not read | | [The block of `AGENTS.md`](https://marmeon.com/docs/agents.md#the-marks) | `` and ``, each on a line of its own | `agents:sync` refuses and writes nothing | the text between the marks is replaced; without marks the block is appended | | [Skills of the framework](https://marmeon.com/docs/agents.md#what-the-command-owns) (`SKILL.md`) | `marmeon-skill: "1"` under `metadata:` in the front matter | `agents:install` refuses and asks you to update marmeon | `agents:install` refuses and writes nothing: the file is the app's | | [The server in `.mcp.json`](https://marmeon.com/docs/agents.md#what-the-command-owns) | `mcpServers.marmeon`: `command` and `args` | n/a: the entry is replaced, and the command says so | n/a | | [`--json` of a command](https://marmeon.com/docs/console.md) | `format`, the first key | n/a: the command prints its newest | n/a | | [Results of `marmeon mcp`'s tools](https://marmeon.com/docs/mcp.md#tools) | `format`, the first key of the document; the tool names and input schemas | n/a: the server answers in its newest | n/a | Some formats have no version of their own and are kept stable another way: - **Signed URLs, upload tokens and live tokens** are tied to `APP_KEY` through a key derived per purpose (`marmeon:`, so a signature is never also a cookie or session key). A change of the form arrives as a new parameter or a new derivation, so an old link or token fails closed. Links in mails live long, so a signed URL only ever grows. An upload token starts with `tu_`, which serves as its version. - **Messages between nodes** (live updates over Redis, the tab sync) carry a `kind` or a `v`. A reader drops a message it does not know. Such a message never carries data: it tells a tab to ask the server, which answers through the route and its authorisation. - **The envelopes of cache entries and the values the framework stores in them** have no mark and are frozen: the file store's `{ value, expires }`, the rows of the `cache` and `cache_locks` tables, and the Redis value, a JSON text with a millisecond expiry (`PX`). So are the values the framework puts there itself, such as a rate limiter's counter (a whole number), the marker of `job.once` (`1`) and the scheduler's last tick (`schedule:last-tick` for tasks that run on one server and `schedule:last-tick:` for the others, each the start of the minute in epoch milliseconds). Two nodes of a rolling deploy read each other's entries. A change of one arrives as a new key name, never as a new meaning under the old one. - **Pagination cursors** carry no mark: the values of the last row as JSON, encrypted with `APP_KEY` under a context that names the list's order (and its `name`, when given). A cursor stays valid while the key that made it is `APP_KEY` or in `APP_PREVIOUS_KEYS` and the list's order stays the same; its payload is frozen, and one that no longer decrypts or fits answers 400. - **CSV exports** of a [table](https://marmeon.com/docs/tables.md#exports) are frozen: a byte order mark, every field quoted, lines ended by CRLF. The header row is each column's `label`, or its name, in the order of the definition. A time the database returns as a date is written as ISO 8601 in UTC, and a time stored as text as it is stored; a boolean as `true` or `false`, an object as JSON, and a text that starts like a formula (`=`, `+`, `-`, `@`, a tab, a carriage return or a line feed, also behind spaces or invisible characters, or in full width) gets a `'` in front (a plain decimal such as `-12.50` is no formula). The file is named `-YYYY-MM-DD.csv`, the day being the UTC day. A new form of a cell arrives with a new kind of column, never as a new meaning of an old one; `csv/v1.csv` holds the form. The table's cursor is a pagination cursor under the context `table:`. - **`history.state`** holds the URL, component, a key and the scroll position. An entry that does not match loads from the server. - **The names of keys** in the cache and the lock store (`limiter:…`, `queue:unique:…`, `queue:once-lock:…`, the scheduler's locks) and the names of [encryption contexts](https://marmeon.com/docs/encryption.md#what-the-key-protects) are format: two nodes must agree on them. A release that renames one does so with the same care as a renamed column. Fixtures sit under `__fixtures__/formats/`, one per version: the page and region object, the job record, the Redis member, queued listeners, mails, notifications and chat messages, the session payload, the pagination cursor, the CSV export, the record of migrations, the encrypted value, API tokens, the live stream, its query and the messages between nodes, the manifest of copied files and the `--json` documents. A test reads each directory with the current code. A pull request that changes or deletes a fixture is a `breaking` one. [Changing a stored or wire format](https://marmeon.com/docs/contributing.md#changing-a-stored-or-wire-format) says how a format moves on. From 1.0 on, every change of a format ships so that a rolling deploy works: the release that first writes version N is one whose readers already read N, and a table is not renamed in place but created anew, written twice and dropped over two releases. The upgrade to the first release that marks these formats is the exception, and cannot be rolling: [the upgrade that stops every process](https://marmeon.com/docs/deployment.md#the-upgrade-that-stops-every-process) lists what to do and what it costs. ### Experimental Experimental means: it can change or go away in any minor version, without an entry in the [upgrade guide](https://marmeon.com/docs/upgrading.md). It is still listed in the package's `api.md`, under **Experimental**, so a change shows in the pull request's diff, but the `breaking` label is not required for it. Build on it only when you can follow the releases. Nothing in this release is experimental. ### When a union grows A new member of a union, such as a string value, a field of an event like `via`, or a message of a diagnostics channel, is a minor change. It ships as an ordinary `feature`, and the title of its pull request names the new member (for example "Add 'magic-link' to SignInVia"), so the release notes show it. The exception is the `err` kinds of the [results the framework returns](https://marmeon.com/docs/errors.md#results-the-framework-returns). They are closed: a new kind comes only with a new method, so an exhaustive `switch` with `satisfies never` compiles across minor versions. Everywhere else, handle a value you do not know in a `default` branch. Here `event` is a `SignedIn` event: ```ts switch (event.via) { case 'attempt': return 'password'; case 'passkey': return 'passkey'; case 'remember': return 'cookie'; default: return 'other'; } ``` ### Deprecations What is removed is deprecated first, in a minor version: marked `@deprecated` in its types, with the replacement and a link to the docs, and warned about once per process as soon as it is used, **only** when `NODE_ENV` is `development` or `test`. On the server, the warning is a Node `DeprecationWarning`: `node --no-deprecation` turns it off, and `node --throw-deprecation` turns it into an error; in the browser it goes to the console. It is removed at the earliest in the next breaking release (a major version from 1.0 on, a minor before); its `@deprecated` tag says which one (from 1.0 on, `Removed in 2.0` and the like, never a minor). The removal has an entry in the [upgrade guide](https://marmeon.com/docs/upgrading.md). [Package development](https://marmeon.com/docs/package-publishing.md#deprecating-an-api) shows how a package deprecates an API. ## A broken release A release is never taken back from npm. A broken one is deprecated there, with the version to use instead, and the next patch fixes it. What the release workflow publishes is staged first and goes public only after a maintainer approves it with two-factor authentication, and it carries npm provenance, so you can check where it was built. A package's very first version has to be published by hand, before trusted publishing can be set up for it. The [contribution guide](https://marmeon.com/docs/contributing.md#pull-requests-and-releases) describes the process. ## The first day after a release pnpm 12 holds back any package version younger than its `minimumReleaseAge`, one day by default. This protects you from a package that is pulled again soon after it appears. For a day after a Marmeon release, `pnpm up --latest` and `pnpm create marmeon` install the previous release without a message. A new exact version you wrote into `package.json` yourself installs all the same under the default setting: pnpm prints that it added the package to `minimumReleaseAgeExclude` in `pnpm-workspace.yaml` and writes it there. Only where `minimumReleaseAge` is set explicitly (the app's `pnpm-workspace.yaml`, your global config or a variable) is the install asked in a terminal, and without one the install fails with "within the minimumReleaseAge cutoff". Check the versions in `package.json` (`marmeon` and the `@marmeon/*` packages) after an upgrade; a mix of two releases is what [`marmeon check`](https://marmeon.com/docs/check.md#the-packages-check) reports. Wait a day, or let only the framework through for this one command: ```sh pnpm_config_minimum_release_age_exclude='["@marmeon/*","marmeon","create-marmeon"]' pnpm up --latest "@marmeon/*" marmeon ``` The variable changes nothing else, and only this command sees it. npm has no such delay. [`marmeon upgrade`](https://marmeon.com/docs/releases.md#how-to-upgrade) passes exact versions (`pnpm add --save-exact --save-prod @marmeon/core@1.2.0 …`), so it installs as a version you wrote yourself does, pnpm's note about `minimumReleaseAgeExclude` included. It never sets `minimumReleaseAge`, an exclusion or any flag that changes the release-age delay, and it leaves standard input to pnpm, so a question about an explicit `minimumReleaseAge` reaches you at a terminal. Without a terminal that install fails, and `upgrade` puts `package.json`, the lockfile and `pnpm-workspace.yaml` back. When the install leaves another version than the one asked for, or the packages are not in one version, `upgrade` puts the files back and stops with what it found, before it prints the guide or generates anything. ## How to upgrade 1. Run `pnpm marmeon upgrade` (`npx marmeon upgrade` with npm). It moves every `marmeon` and `@marmeon/*` package your app lists to the `latest` version at once, prints the entries of the [upgrade guide](https://marmeon.com/docs/upgrading.md) between your version and the new one, and runs `route:types` and, when the app has `@marmeon/database`, `db:types` with the new version. Then read those entries: they are sorted by impact, and each says how likely it touches your app. - `--to=` moves to that exact version, `--to=` (such as `next`) to the version a dist-tag names. `--dry-run` prints what it would run and changes nothing. `--json` prints [one document](https://marmeon.com/docs/console.md#machine-readable-output) and never asks a question. Its keys are `format`, `dryRun`, `packageManager`, `from`, `to`, `breaking`, `packages`, `commands`, `guide` (the sections of the guide with their entries), `generated` (the generators that ran, each with its exit code, 0) and `warnings`. `guide` and `generated` are `null` with `--dry-run` and when nothing needs to move; `guide` is also `null` when the guide could not be read, and `warnings` says why. - At a terminal, `upgrade` shows what it will move and asks once before it installs, unless you pass `--json`. A move to another major version (or, below 1.0, another minor) may break your app: without a terminal, and with `--json`, it stops unless you name the exact version with `--to=`. - It saves exact versions, installs through your package manager with the arguments it checked, and never lifts [`minimumReleaseAge`](https://marmeon.com/docs/releases.md#the-first-day-after-a-release). It does not downgrade. Until the installed packages pass its check (they must all be in the version it asked for), a stop (a failed install, a failed check, Ctrl-C) puts `package.json`, the lockfile and `pnpm-workspace.yaml` back as they were, and it tells you to run `pnpm install` (or `npm install`) to make `node_modules` match. After that check the files keep the new version, whatever happens to `route:types` or `db:types`: `upgrade` then names the generator to run again and exits with 1. A Ctrl-C at the terminal reaches pnpm and `upgrade` together. A SIGTERM sent to `upgrade` alone while pnpm asks you a question stops pnpm only, and a lifecycle script it started may outlive it. - It stops before it changes anything when the framework packages are not in one installed version (`--to=` repairs that; a tag does not), when `marmeon` is not listed, when `package.json` pins a framework package above the target, when a framework package is listed only as a peer, with a `workspace:`, `file:`, `link:`, `catalog:` or `npm:` spec or a git URL, or under an override or a patch, when the app is part of a workspace, has no lockfile or two lockfiles of different package managers, or uses yarn, bun or another package manager than pnpm or npm. 2. Run `marmeon doctor`, your tests, and `pnpm marmeon build`. Type errors point to most of what changed. 3. Deploy as usual. An entry says so when a change needs a migration or signs users out. The [deployment](https://marmeon.com/docs/deployment.md) page covers the rest. Where `upgrade` stops, do it by hand: read the section of the new version in the [upgrade guide](https://marmeon.com/docs/upgrading.md), move every framework package to the new version at once ([the first day after a release](https://marmeon.com/docs/releases.md#the-first-day-after-a-release) has a catch), install, and run `marmeon route:types` and `marmeon db:types`. --- # Contributing to Marmeon Thank you for helping. This page covers the rules for a contribution: the sign-off, the checks, pull requests and their labels. It says how a release is made, and what the repository holds that the documentation does not: its layout, its own test suites and benchmarks, and the inside of the framework's client. The principles the framework is built on are in the [README](https://github.com/marmeon/marmeon/blob/main/README.md#principles); the documentation is under `docs/` ([Writing documentation](https://marmeon.com/docs/contributing.md#writing-documentation)). ## Sign your commits off (DCO) Marmeon takes contributions under the [Developer Certificate of Origin 1.1](https://developercertificate.org/) (DCO), as the Linux kernel and Node.js do — no contributor licence agreement. With the sign-off you certify that you wrote the change or have the right to submit it under the project's licence (MIT, `LICENSE`; copyright [BespokeCode](https://bespokecode.de)). Every commit of a pull request carries a `Signed-off-by` line with your real name and the e-mail of the commit: ```text Signed-off-by: Jane Doe ``` `git commit -s` adds it (`git commit --amend -s --no-edit` for the last commit, `git rebase --signoff main` for a whole branch). A check on every pull request (the DCO app) refuses commits without it. The text you certify: ```text By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ``` ## Set up Node 26.10 or newer and pnpm 12 (the version in `packageManager` — `pnpm self-update` or Corepack-free `npm i -g pnpm@12.9.1`). ```sh pnpm install docker compose up -d # Postgres, Redis, S3 and MySQL for test:pgsql, test:redis, test:s3 and test:mysql (this repository's containers only) pnpm dev # the web app (apps/web-app) on http://localhost:3000 — first its .env and database (apps/web-app/README.md) ``` `pnpm-workspace.yaml` holds the install policy: a release younger than three days is not installed, a package whose trust evidence got weaker is refused, and no dependency runs an install script. The compose services listen on `127.0.0.1` only. Optional: [zizmor](https://docs.zizmor.sh) (`brew install zizmor` or `uv tool install zizmor==`), so that `pnpm run ci` can check the workflows ([The workflows: zizmor](https://marmeon.com/docs/contributing.md#the-workflows-zizmor)). ## Before you open a pull request ```sh pnpm run ci # every check CI runs: build, typecheck, lint, the test suites, sizes, types, docs, tarballs, image, release, workflows ``` `pnpm ci` without `run` is pnpm's own clean install — it checks nothing. The run has 18 parts (`pnpm run ci --list`; [The repository](https://marmeon.com/docs/contributing.md#the-repository) names them); some of them: `pnpm run ci --only test,lint`. `pack:smoke` and `image` need the package store, the registry and Docker, `zizmor` needs [zizmor](https://marmeon.com/docs/contributing.md#the-workflows-zizmor) — without them they are reported as skipped, which is not green. - **Tests** come with the change — type guarantees as `@ts-expect-error` tests, behaviour in Vitest, a feature shown in `apps/web-app` (principle 9). - **Bundle sizes are reported, not limited:** the `size` check puts a table of the client bundles, this branch against its base commit, into the job summary and fails only when a build or measurement breaks. A maintainer decides per pull request whether its growth is worth it; say in the description what the bytes buy ([The bundle sizes](https://marmeon.com/docs/contributing.md#the-bundle-sizes)). - **Tests leave nothing behind:** every run gets its own temporary directory (`TMPDIR`), and `pnpm test` fails with a list when a test leaves a `marmeon-*` entry in it. Make temporary directories with `tempDir('marmeon-…')` (`scripts/test/temp-dir.js`): it removes them when the test, or the file, is done. The root of an app whose modules come from the repository's fixtures is made with `workspaceTempDir('marmeon-…')` instead: it lies in `.tmp/` of the checkout (ignored by git), because migrations have to lie in the app or its workspace. - **`pnpm check:source` holds** — the rules over the repository's own files ([next section](https://marmeon.com/docs/contributing.md#rules-over-the-source-pnpm-checksource)). - **A pull request** is one change; its title is its line in the release notes, and a maintainer gives it one release label ([Pull requests and releases](https://marmeon.com/docs/contributing.md#pull-requests-and-releases)). You write no changelog entry. A breaking change gets its entry in [UPGRADING.md](https://marmeon.com/docs/upgrading.md) — impact, before → after, the way back — when the release is prepared; say in the description what an app has to do. - **A change to a public API, an environment default or a command** changes its page under `docs/` in the same commit ([Writing documentation](https://marmeon.com/docs/contributing.md#writing-documentation)). - Code, comments and commit messages are in English; a commit subject says what the change does, in the imperative. ## The repository ```text packages/* the framework's packages, each with a short README for npm apps/web-app the app every feature is shown and tested in apps/blank-app an app without modules: what create-marmeon --minimal writes (pnpm template:sync), and what make:auth is tested against examples/* demos on the starter kit, each an overlay (files, edits, commands) that pack:smoke applies to its kit app and runs apps/website the documentation as a Marmeon app: docs/*.md and the policies at the root (pnpm website:dev; apps/website/Dockerfile, deploy/website) docs the documentation's pages, in the order apps/website/docs.config.ts lists them scripts/ci.ts pnpm run ci — its 18 parts, from the build to the release rules (below) scripts/bench pnpm bench — the start and the request path, measured (never a gate) scripts/test the test suite's temporary directory per run, tempDir() and workspaceTempDir() — the repository's own, not exported by a package (pnpm test fails when a test leaves an entry behind) deploy/website the docs' Compose file and Caddyfile (one server) UPGRADING.md what changes for apps from one version to the next .github workflows/ (ci.yml: pnpm run ci in parallel jobs; release.yml: started by hand, staged publishing; pr-label.yml: the release label check; codeql.yml and codeql/: code scanning; scorecard.yml: the OpenSSF Scorecard), zizmor.yml (the rules of the zizmor job), release.yml (the notes' categories, generated) and release-base (the commit a release was prepared from) ``` ```sh pnpm run ci # everything, as CI runs it (pnpm ci without `run` is pnpm's clean install) pnpm test # the test suite; test:pgsql, test:redis, test:s3, test:mysql against the containers (docker compose up -d) pnpm website:dev # the docs on http://localhost:3970 pnpm website:image # the docs' image (apps/website/Dockerfile): built, run read-only and behind Caddy (deploy/website) — part of `image` pnpm pack:check # the tarballs: clean build, pnpm pack, no tests or leftovers, LICENSE, exact versions, publint, attw pnpm pack:smoke # create-marmeon from the tarballs, outside the repository: the starter kit (pnpm) and a blank app (npm) — install, tests, lint, build, start pnpm api:check # every package's public surface against its api.md (after a build); pnpm api:update rewrites the files pnpm template:sync # apps/blank-app → the template of create-marmeon (a test fails while they differ) pnpm release:prepare # the next version, changelogs and upgrade-guide heading from the merged pull requests (below); pnpm check-release checks the release rules pnpm csp:probe --app apps/web-app --build # a built app in headless Chrome under style-src 'self': 0 CSP violations (never a gate) ``` `pnpm csp:probe` with `--build` builds, then starts the app (or probes `--url`; `--throwaway`: generated keys and a seeded temporary SQLite, for a fresh checkout), signs in over HTTP and visits the guest and signed-in pages, a layer by deep link and by click, and a failing visit — in headless Chrome under a second `style-src 'self'` policy; it needs Chrome (`--chrome ` or `CHROME`). `pnpm run ci` runs 18 parts one after the other, each with its exit code and time, and fails when one is red: `build`, `typecheck`, `lint`, `check:source` ([below](https://marmeon.com/docs/contributing.md#rules-over-the-source-pnpm-checksource)), `test`, then `test:pgsql`, `test:redis`, `test:s3` and `test:mysql` against this repository's containers (`compose.yaml`, started as needed), `size` (the bundle sizes against the base commit — [The bundle sizes](https://marmeon.com/docs/contributing.md#the-bundle-sizes)), `types:check` (the apps' generated route and table types are current), `api:check` (each package's `api.md` matches its built declarations — [The API snapshot](https://marmeon.com/docs/contributing.md#the-api-snapshot)), `website:check`, `pack:check`, `pack:smoke`, `image` (the starter kit's image from `make:docker`, then the docs' image), `check-release` and `zizmor` (the workflows, [below](https://marmeon.com/docs/contributing.md#the-workflows-zizmor)). `pack:smoke` and `image` without a package store, the registry or Docker, and `zizmor` without zizmor, are reported as skipped, never as green. `--only a,b`, `--skip a,b`, `--bail`, `--no-compose` (the databases already run) and `--list` choose; `--shard i/n` runs one n-th of the files of the selected test parts (Vitest's `--shard`; with no test part selected it is an error). `ci.yml` splits the parts into jobs that run side by side (the checks, the tests as three shards `test (1/3)` to `test (3/3)`, the tarballs, the image, Postgres as two shards `test:pgsql (1/2)` and `(2/2)`, Redis, MySQL, S3, zizmor); a shard builds for itself, and a job's name is what a required check of the repository would list. The job `test:pgsql` only waits for both Postgres shards and fails unless they passed, so the name a required check lists stays the same. ### The test suites against real services `pnpm test` runs every package's tests and the web app's on SQLite and in memory. Each run gets a temporary directory of its own (`TMPDIR` points into it) and fails when a test leaves a `marmeon-*` entry behind; the framework's tests make theirs with `tempDir()` of `scripts/test/temp-dir.js`. The cases for other backends run when their variable is set — the services come from `compose.yaml` (`docker compose up -d`, ports of their own): ```sh pnpm test:pgsql # MARMEON_TEST_PGSQL_URL, DB_DRIVER=pgsql and DB_URL → postgres://marmeon:secret@127.0.0.1:55432/marmeon pnpm test:redis # MARMEON_TEST_REDIS_URL=redis://127.0.0.1:56379 pnpm test:s3 # MARMEON_TEST_S3_ENDPOINT=http://127.0.0.1:56333 # (MARMEON_TEST_S3_KEY / MARMEON_TEST_S3_SECRET default to the compose identity) pnpm test:mysql # MARMEON_TEST_MYSQL_URL=mysql://root:secret@127.0.0.1:53306/marmeon (MySQL 8.4) ``` Each of them runs only the test files that use its service, not the whole suite again. `scripts/test/services.ts` derives the selection from the source — nothing is listed or marked by hand — and `vitest.config.ts` makes one Vitest project per set of services (`plain`, `pgsql`, `pgsql+redis`, …; `pnpm test:pgsql` is `pnpm test --project '*pgsql*'`, and a path filter still narrows it). A file is selected for a service by the files it reaches through relative imports (never through a package specifier, so import a `__fixtures__` file relatively; the selection throws on a package specifier that names `__fixtures__`): - **Postgres**: a file reads `MARMEON_TEST_PGSQL_URL`; a test or helper file (anything in `apps/`, `scripts/`, `__fixtures__/`, `test-helpers/`, `*.test-support.ts` or a test) builds a `database: 'refresh'` app; the test lives in an app that depends on `@marmeon/database` (`DB_DRIVER` from the environment wins over the app's `.env`); a test or helper starts a nested Vitest (its refresh tests inherit `DB_DRIVER`). - **Redis**, **S3** and **MySQL**: a file reads `MARMEON_TEST_REDIS_URL`, `MARMEON_TEST_S3_ENDPOINT` or `MARMEON_TEST_MYSQL_URL`. Each project gets tripwire values for the services its files were not selected for: `DB_DRIVER=pgsql` with a Postgres URL, a Redis URL, an S3 endpoint and a MySQL URL on `not-selected-for-test-….invalid` hosts (which never resolve), so a file that reaches a service the rules do not see fails in the plain `pnpm test` instead of silently dropping out of the service runs. An error that names `not-selected-for-test-pgsql.invalid` (or `-redis`, `-s3`, `-mysql`) means exactly that: import the helper relatively, or extend the rule in `scripts/test/services.ts` — do not change the test. Tests that assert something about wall-clock time (a ratio, an upper bound) live in a file `.timing.test.ts`. These files run in the `timing` project on SQLite, after all others and one at a time, so nothing competes with the measurement; they need no service, and `pnpm test:pgsql` and its siblings leave them out. Tests that start processes — a file that, or a relative import it reaches, imports `node:child_process`, starts a nested Vitest, imports `vite` as a value or builds a test app with the `ssr` option — run in their own projects, `-process` (for example `plain-process`, `pgsql-process`; `--project '*pgsql*'` takes both). They run after the other projects with half as many workers as the machine has cores (`MARMEON_TEST_PROCESS_WORKERS` sets the number), a 30 s test timeout and a 60 s hook timeout, so what they take depends on their own work, not on the load next to them. The rule is in `scripts/test/services.ts` (`startsProcesses`); a new file lands in the right project without being marked. With `DB_DRIVER=pgsql` and `DB_URL` in the environment, refreshed test apps of any app use Postgres: the role needs the right to create databases (one per worker, next to the configured one). Run `test:pgsql` for every change to the database, sessions, auth, queues or locks — Postgres finds races SQLite hides. Never run two Postgres, Redis or MySQL suites at once: they share their test databases. A session store of the framework is held to the shared suite in `packages/session/src/stores/stores.test.ts`, the contract's test: compare and write in one atomic step. ### Benchmarks `pnpm bench` keeps the measurements in the repository — none of them is part of `pnpm run ci`, a laptop's noise (±3–5 % between runs) would make a gate flaky: ```sh pnpm bench boot --app apps/web-app # marmeon start → /up 200: median of 7, a breakdown from a CPU profile pnpm bench login --base f785159 --without all # the request path, A/B: this checkout against a commit, each side in a git worktree pnpm bench people # GET /people signed in pnpm bench login --profile --base f785159 # CPU profiles of the measured requests: top lists (self, inclusive) and their diff ``` The request benchmarks boot the web app in-process (SQLite in memory, `SESSION_DRIVER=memory`) and send the requests through the kernel as a browser would — the cookies as the server set them, the body read; none of the test helpers' work per response. Each side runs from a `git worktree` under `$TMPDIR/marmeon-bench/` (this checkout as a snapshot with its uncommitted changes; before a run each one must import what a measured process imports — a missing module reinstalls its `node_modules`), the sides alternate in fresh processes, and the report gives the median, the mean's 95 % confidence interval and Welch's test per pair. `--in-place` measures the checkout itself instead of a snapshot; the repository's own `apps/web-app/.env` (read under `.env.test`) and the location of the worktrees changed results by several per cent, so every side runs from the same place. `--without ` (`session-hash`, `fetch-metadata`, `csp`, `epoch`; `all` for all four) switches one of the request path's security measures off in one variant — counted, and refused when one still runs — so its cost shows on its own. What one request cost the server at `0dd3448`, measured with `pnpm bench login` and `pnpm bench people` (`SESSION_ENCRYPT=false`; median of 6 alternating runs, each the median of 3 × 10 000 requests) on an Apple M1 Pro (16 GB) with Node 26.10: | Request | µs per request | without the four measures | at `f785159` | | --- | --- | --- | --- | | JSON visit of `/login` with a guest session — **the budget** | **≈ 117** | ≈ 115 | ≈ 141 | | JSON visit of `/login` without a cookie (no session) | ≈ 87 | ≈ 85 | ≈ 112 (a session per request) | | the `/login` document (HTML, CSP nonce) | ≈ 120 | ≈ 117 (without the CSP) | — | | JSON visit of `/people` signed in (session, auth, queries, shared props) | ≈ 336 | ≈ 332 | ≈ 362 | The measures cost, each switched off on its own: the session id's hash ≈ 0.3 µs per request with a cookie (`crypto.hash`), the Fetch Metadata stage nothing on a GET (it checks unsafe methods only; ≈ 0.4 µs per POST), the CSP ≈ 1.5 µs per request (its middleware) and ≈ 3 µs per document (the nonce, the header), the tab-sync epoch ≈ 0.9 µs per page (a memoized HMAC). `SESSION_ENCRYPT=true` adds ≈ 9 µs to a request with a session (≈ 18 for `/people`): one decryption, one encryption. What took the time back after `f785159` (CPU profiles, `pnpm bench login --profile --base f785159`): the cookie encryption moved from WebCrypto (≈ 18 µs per call, three calls per page) to `node:crypto`; at most one copy of a response per request (`editableResponse`, instead of four or five); the middleware list sorted once per route instead of per request; fewer allocations in the container's lookups; the cookie headers serialized once; a cheaper request translator. Without the encryption change the rest alone is level with `f785159`, within the noise. ## Rules over the source: `pnpm check:source` A part of `pnpm run ci` (`scripts/check-source.ts`, its tests in `scripts/ci.test.ts`): rules a test of one package cannot see, checked over every file of the repository — tracked, or new and not ignored. Exit 1 lists every hit as `path:line: text`. 1. **The old name is gone**: no file and no path says the framework's name from before 0.1.0, in any letter case. Allowed is the company name and its website's URL only (the `LICENSE` holder — every copy, the policies, the licence rule of `check-release`): nothing was released under the old name, so there is no rename hint. Code that must spell the old name — a test — builds it from parts (`['Bes', 'poke'].join('')`); the rule knows no file exceptions. 2. **No app installs a validation engine**: apps, the starter's template, the `make:auth` stubs, scripts and what the `make:*` generators write validate with `rules` of `@marmeon/validation` — no file outside a package's `src/` imports Valibot (in code or in a generator's template text), and no `package.json` of an app or of the template lists it. Inside `packages//src/` Valibot stays an internal engine. A test that must write the import builds the name from parts as well. 3. **`NODE_ENV` is checked positively**: no `!== 'production'` / `!= 'production'` (any quotes, either side), no `NODE_ENV === 'production'` and no `import.meta.env.DEV` / `!import.meta.env.PROD` (Vite derives them from `NODE_ENV === 'production'`: a build with any other value, or none, is `DEV`) in code people run or copy — a package's code (`packages//src/` and the stubs), the starter's template (`packages/create-marmeon/template/`) and the apps (`apps//`); tests, type tests and fixtures aside — comments count too. Either sends a missing `NODE_ENV`, which is production, down the development branch. Development branches ask `process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'` inline (a client build folds it away), server code `environment.isDevelopment()` / `environment.isProtected()` of `@marmeon/core`. 4. **The old prefix of API tokens is gone**: `AUTH_TOKEN_PREFIX` defaults to `marmeon_`; no file says the two letters and the underscore of before in front of a digit, a `|`, a quote, whitespace or a line's end, anywhere. Tests spell it from parts like the old name. 5. **The docs speak to their readers**: no page under `docs/` carries the placeholder marker as a line of its own ([Writing documentation](https://marmeon.com/docs/contributing.md#writing-documentation)) — every page is written. The pages, the packages' READMEs, the root `README.md`, the three policies the docs show (`UPGRADING.md`, `CONTRIBUTING.md`, `SECURITY.md`), what every new app copies (the starter's template `packages/create-marmeon/template/` and the packages' stubs `packages//stubs/`) and what a reader of one of the apps sees first (its `README.md` and `.env` files), and the website's own pages (`apps/website/modules/site/`) compare Marmeon with no other framework. Each part is an entry of `DOC_TEXT_RULES` with its pattern and the files it reads. 6. **The framework's messages speak to app developers**: no string of a package's code (`packages//src/`, tests and fixtures aside) or of its launchers (`packages//bin/*.js`) names a decision number, a wave or another framework — errors, warnings, solutions, command descriptions and output, the files the `make:*` generators write and the devtools' pages reach every app. Only strings count, read with oxc-parser; comments, names and regular expressions are rule 7's. 7. **No references to the private record**: no tracked file names a decision number (an `E` and two or three digits as a word of its own — a hex value, an exponent, `E2E`, `E.164` or `E164` is none), a wave or a step of the maintainers' plan, a personal date or a path into the maintainers' notes — a comment says what holds and links a page under `docs/` ([Comments](https://marmeon.com/docs/contributing.md#comments)). `pnpm pack:check` holds every file of the packed tarballs to the same patterns. 8. **No mutant is switched off without a reason**: every `disable` comment of the mutation tester in code (`// Stryker disable next-line [, ]: `, also inside `/* */`; comments are read with oxc-parser, in Stryker's own grammar) names its mutators and gives a reason of at least three words after a colon directly behind them — why the mutant changes nothing anyone can observe. A range (`disable` without `next-line`) must be closed by `restore` comments covering every one of its mutators later in the same file and never covers `all`; `disable next-line all: ` needs only its reason. 9. **The internal subpath of a package is not API**: no code file outside `packages//src/` imports `@marmeon//internal` (the framework's own packages mark their routes with it). Apps, stubs, templates and scripts decide access with `everyone` or a check. 10. **Every deprecation shows the way forward**: each `@deprecated` tag in `packages//src/` (tests and fixtures aside) names the replacement (`Use {@link x}` or ``Use `x` ``), links the docs (`docs/.md#`, which the docs link test checks against the real page) and says when it goes (`Removed in x.y`): `@deprecated Use {@link isSensitiveRememberField}. Removed in 0.5; docs/forms.md#remembering-input.` Each `deprecated(id, message, removeIn)` call has three string literals: an id `.` whose package is the file's and that no other call uses, the message, and `removeIn` as `major.minor`. The version must lie after the current one — otherwise it is a typo or overdue. From 1.0 on it is a major version (`Removed in 2.0`). [Package development](https://marmeon.com/docs/package-publishing.md#deprecating-an-api) shows both. 11. **Only `@marmeon/database` imports the query builder**: no code file outside `packages/database/src/` (the other packages and their tests, apps, the template, stubs, scripts, the templates of `make:*`, the edits of an example) names `kysely` as a quoted module specifier — `import`, `import type`, `export … from`, `import()`, `require()`, `import.meta.resolve()`, any subpath such as `kysely/helpers/postgres` — and no code block of a docs page or README of a package, app or example imports it. No manifest but `packages/database/package.json` installs it — the root `package.json` is checked too, `pnpm-workspace.yaml` is not: not as a dependency, an alias (`npm:kysely@…`), a bundled dependency or an override. Packages and apps take the builder, `sql`, `Kysely`, `Transaction` and the types (`Connection`, `SelectQuery`, `ColumnReference` …) from `@marmeon/database`. `UPGRADING.md` may show an old import. 12. **No test is retried**: in every test file and every Vite or Vitest configuration — the framework's tests, the stubs, the template and the examples alike — each property `retry` is refused unless its value is `0` or `{ count: 0 }`, as are `.retry()` on `it`/`test`/`describe` and `--retry` in a `package.json` script. So that nothing hides a retry from the rule, so are an options argument of a test that is not an object literal or that spreads another object, and a name that takes over `it`/`test` (`const t = it`, `t = it`; an alias in an import or a destructuring counts as the export, and the result of a call such as `it.skipIf(x)` or `test.extend({})` is bound the same way without being refused). In a test file, a `retry` in an object passed directly to a call or a `new` outside the test API (`expect(config).toMatchObject({ retry: 3000 })`) is something else and passes; in a configuration nothing does. The rule catches a retry written by accident, it is no barrier against one who sets out to get around it. A test that passes on the second try measures noise: prove the property without a clock (count the work), or move the measurement of time into a `.timing.test.ts`. There is no list of exceptions. 13. **No lint rule is disabled without a reason**: every `eslint-disable` or `oxlint-disable` comment in code (`-next-line`, `-line` or a range, also inside `/* */`; comments are read with oxc-parser) gives its reason after ` -- `, at least three words — why the rule is wrong for this line. `// oxlint-disable-next-line no-control-regex -- control characters are exactly what it removes`. 14. **Real paths come from the system**: no `realpathSync` without `.native` (a call, a value such as `map(realpathSync)`, or an alias), no `fs.realpath(` and no `realpath` imported from `node:fs` in a package's sources or launchers (`packages//src/` and `bin/`; tests, type tests and fixtures aside). The JavaScript implementation joins a link's target with `path.resolve`, so with `d -> ../outside/sub` and `evil -> d/../x` it answers `x` inside the root while the kernel lands in `outside/x`; a containment check built on it passes what escapes. `realpathSync.native` asks the system, and `realpath` of `node:fs/promises` already does. A new rule joins the same script, with its test. ### Environment variables The names of the variables are frozen, and `scripts/env-names.test.ts` holds them to these rules; the list is `docs/configuration.md` › "Every variable", compared with the `Environment` sections of every `api.md`: - A variable starts with the prefix of its area; only `NODE_ENV`, `PORT`, `HOST` and the names of the OpenTelemetry specification have none. - `_DRIVER` picks a driver, `_CONNECTION` names a connection of the database or Redis, never anything else. - A duration ends with its unit (`_MILLISECONDS`, `_SECONDS`, `_MINUTES`, `_HOURS`, `_DAYS`); a name with one of the words `LIFETIME`, `TIMEOUT`, `DELAY`, `EXPIRE`, `EXPIRES`, `EXPIRY`, `EXPIRATION`, `THROTTLE`, `RETRY`, `HEARTBEAT`, `WITHIN`, `AFTER`, `INTERVAL`, `TTL`, `AGE`, `DURATION`, `WINDOW`, `PERIOD`, `GRACE`, `IDLE`, `BACKOFF`, `WAIT` or `STALE` is read as one (whole words: `USER_AGENT` is none). An abbreviated unit (`_MS`, `_SEC`, `_MIN`, `_HRS`) is refused. - A switch is read with `env.boolean()`: no `env.in(['true', 'false'])`, no `true|false` pattern and no compare with `'true'` in a package's source, and no variable that reads `true` and `false` as text. - One variable has one meaning: two configs of a package do not read it differently. - One name has one default: every package that reads a variable gives it the same default, or leaves it optional in all of them. - A retired name is never given out again. A rename is a `breaking` pull request with `.renamed()`; its `UPGRADING.md` entry is written when the release is prepared, and the description says what an app renames. A new variable adds its row to the table. ## Dependencies of drivers A driver of another package, such as a queue driver for SQS, comes through the static record of its provider (`static queueDrivers`), never through a change to the service's own package; see [drivers](https://marmeon.com/docs/drivers.md). Third-party driver libraries follow one rule. Each package README names the part that applies to it, with the exact install command, and the [package development](https://marmeon.com/docs/package-publishing.md#dependencies-of-drivers) page explains it to package authors: 1. A package that wraps exactly **one** third-party driver and is useless without it lists it in **`dependencies`**, at a caret range of the tested major: `@marmeon/redis` → `redis`, `@marmeon/validation` → `valibot` (its engine, never re-exported). The app installs the package, nothing else. 2. A package with **several** selectable drivers (usually with a built-in one) keeps the third-party drivers as **optional peers**, and its error names the **exact** install command with the major — `pnpm add @aws-sdk/client-s3@^3 @aws-sdk/s3-request-presigner@^3` (storage), `pnpm add mjml@^5` (mail), `pnpm add pg@^8` (database). Where the driver is surely used (an S3 default disk, a Redis cache), the start fails with it, not the first request. 3. A library whose instance or types the app must **share** stays a **peer** — the OpenTelemetry API, React, Vite. A dependency would install a second copy, and the app's SDK would register on an API the framework never reads. 4. Decided exception: **`nodemailer` is a dependency of `@marmeon/mail`** — no dependencies of its own, the production path. 5. Decided exception: **`@simplewebauthn/server` is a dependency of `@marmeon/auth`** — passkeys are a required standard and their verification is security-critical, so a proven implementation; loaded only by `@marmeon/auth/passkeys`. 6. Decided exception: **`kysely` is an exact dependency of `@marmeon/database` only** — no caret. The other packages take the builder and its types from there. The builder's shape is public API and the security plugins are tested against exactly this version. A Kysely update is a pull request of its own that changes its manifest. Once a week the workflow `.github/workflows/kysely-canary.yml` installs the newest Kysely under the `next` tag over that pin on its runner (nothing is committed), builds, typechecks and tests `database`, `table` and `queue`, and fails when something breaks or a new builder method or statement is unclassified. It is no required check and opens no issue: a red run is the cue to prepare the update. A version younger than the release-age gate of `pnpm-workspace.yaml`, or a `next` not newer than the pin, is skipped with a note in the run's summary (green). A schedule runs only on the default branch and GitHub disables it after 60 days without activity in the repository, so start the workflow by hand once after it merges. It runs code nobody pinned, so `pnpm check-release` holds it to a schedule and a manual start (never a pull request or a push), the `contents: read` permission and no secret, a checkout without credentials, actions pinned by SHA, and no cache, restored or saved. 7. Decided exception: **`@modelcontextprotocol/server` is an exact dependency of `marmeon`** (the CLI package) — the official SDK of the protocol `marmeon mcp` speaks, loaded only by that command (`import()` after the check for `NODE_ENV=development`, only from `packages/cli/src/mcp/`). The tool schemas and the protocol negotiation are tested against one version. An update is a pull request of its own; `@modelcontextprotocol/client` at the same version is a devDependency of the repository for the tests. 8. Decided exception: **`oxc-transform` is an optional peer of `@marmeon/core`**, at `>=0.157.0 <1.0.0` — it compiles the mail views of an app (`modules/*/mail/**/*.tsx`) in development and in `marmeon build`; a production start runs the build's output and never loads it. An app that has mail views installs it as a devDependency; without it the load hook names the install command. 9. Decided exception: **`@faire/mjml-react` is an exact dependency of `@marmeon/react`**, imported only by `src/mail/implementation.ts`; no name or type of it is public. The components of `@marmeon/react/mail` are Marmeon's own wrappers with their own prop types and run-time checks, so a fork or another library replaces it without an app noticing. An update is a pull request of its own; `packages/react/src/mail/implementation.type-test.ts` and `scripts/mail-implementation.test.ts` hold the version to the props and to the `mjml` range the framework is tested against, and `pnpm api:check` refuses a name of it in a declaration or the snapshot. A driver sub-package (`@marmeon/-`) only when a driver brings its own code and configuration — ask first. Optional peers on other framework packages (`@marmeon/queue` for `mailer.queue()`, `@marmeon/redis` for a Redis cache) are a different thing: the coupling between the framework's packages. `pnpm pack:check` holds every packed manifest to the rule (`DRIVER_RULE` in `scripts/packages.ts` — a new driver gets its line there), and `pnpm pack:smoke` boots the starter kit on the Redis drivers without `redis` in its `package.json`, sends a mail over SMTP from the production install, and starts it with an S3 default disk and no AWS SDK (the exact command, exit 1). ## Pull requests and releases The framework is released in lockstep: every `@marmeon/*` package, the CLI `marmeon` and `create-marmeon` always have the same version. Nobody writes a changelog entry: the release notes are made from the pull requests merged since the last release. ### Pull requests - **One change per pull request.** Its **title is its line in the release notes**: in the imperative, saying what the change does, like a commit subject (`Add a dry-run flag to make:migration`, not `dry-run` or `Fixes #12`). - **Exactly one label**, set by a maintainer at review, sorts it into the notes: `breaking` (an app has to change something), `feature` (something new), `fix` (a bug fixed), `docs` (documentation only) or `internal` (tests, tooling, refactoring — no line in the notes). The `release label` check fails a pull request with none or with two; contributors need not label. A `breaking` pull request says in its description what an app has to do — the release preparation turns that into the upgrade guide's entry. - **Pull requests are squash-merged:** the title and `(#N)` become the commit's subject, and the pull request keeps its individual commits on GitHub. Merge commits and rebase merges are switched off. - **Only release preparation writes the `CHANGELOG.md` files and the package versions;** a pull request that edits them is sent back at review. A breaking change's entry in the upgrade guide is written there too ([The upgrade guide](https://marmeon.com/docs/contributing.md#the-upgrade-guide)). ### The API snapshot Every package with an entry point has a `packages//api.md`: its public surface as the built `.d.ts` files emit it, so a change to what an app can import shows in the pull request's diff. `pnpm api:check` (part of `pnpm run ci`, after the build) fails on any difference; `pnpm api:update` builds and rewrites the files — commit them with the change that caused it. A conflict in an `api.md` is never merged by hand: take either side, run `pnpm api:update`, commit. Per entry point (every subpath of `exports` with `types`, except `./internal`) the file lists each exported declaration without its comments, sorted by name: **Stable**; **Referenced, not exported** — the local helper types and `@internal` exports that a public signature names, because their shape is public too; **Augments** — `declare module` and `declare global` blocks of the files the entry reaches (a file belongs to the first entry that reaches it); **Experimental** — what is experimental (below). Members and declarations tagged `@internal` are left out, a `@deprecated` declaration carries a `// @deprecated` line, and a re-export from another package is the `export … from` statement (its declaration is in that package's snapshot). Below the entry's heading, "Types from other packages" names the libraries whose types the entry's declarations mention. A retired environment variable (`.renamed()`) is listed under Environment as `OLD` → `NEW` (renamed), so a lock stands in the diff like a variable. Experimental has three forms, one source each: a whole entry point or package through `marmeon.experimental` in the `package.json` (`true` for every entry point, variable and command of the package, or a list of subpaths such as `["./preview"]`); one option of an options interface through `@experimental` in the JSDoc of the member, which the snapshot takes out of its declaration and lists as the item `.`; one command through `static experimental = true` on its class (`marmeon list` and `--help` say so). Experimental variables and commands stand in a section `## Experimental` of the package. `pnpm api:check` fails unless `docs/releases.md` › "What is public API" › "Experimental" names every experimental entry point (`@marmeon/x/y`), package and command (`marmeon tinker`) as inline code in a list item, and names nothing else. The helper types an experimental entry names but does not export are listed apart under "Experimental, referenced (not exported)", so a name nobody can import stays visible. `api label` does not enforce Experimental, but moving something from Stable to Experimental removes it from the stable surface: label it `breaking`. A class, function, constant or enum that an entry exports only as a type (`export type { Foo }`) carries a `// type-only` line: an app can no longer `new` it. A public signature must not name a type of another package's `./internal` (no snapshot holds its shape), and an entry cannot export a module of its own package as a namespace; `pnpm api:check` reports both. Stability is transitive: a stable item — a stable declaration without its `@experimental` members, an augmentation or a re-export of a stable entry — must not name a type that only experimental entry points export or that is marked `@experimental`, in its own package or another one (the check walks through a helper type that no entry exports); `pnpm api:check` names the item, the type and the file that declares it — mark the item or member `@experimental`, or name a stable type. A `FOREIGN_TYPES` entry that no entry point of its package uses any more is reported, so it gets deleted with the change that made it unnecessary. One exported name stands for one declaration: when two entry points of the framework (stable or experimental, not `./internal` or `@internal`) export the same name, they must export the same declaration — a re-export, or a helper type with the same text such as `Simplify` — or `pnpm api:check` names both files and asks for a rename. The only exceptions are a typed view of the same value, each with its reason in `SAME_VALUE` of `scripts/api-names.ts`; an entry whose name no longer collides fails the check until its line is deleted. A span of time is a `Duration`, or a number with its unit in its name ([docs/time.md](https://marmeon.com/docs/time.md#spans-of-time)): a member, a parameter or a return value of a stable entry whose name ends in a span word (`timeout`, `ttl`, `delay`, `maxAge`, … — the list is `SPAN_WORDS` in `scripts/api-spans.ts`) and whose type holds a bare `number` fails `pnpm api:check`. A number that is no span for the framework, such as a point in time or a field the WebAuthn JSON defines, or a parameter of a contract an app implements ([docs/time.md](https://marmeon.com/docs/time.md#spans-of-time), rule 4), stands in `SPAN_EXCEPTIONS` with its reason. A listed name that follows the rule fails the check until its line is deleted. The check holds the position too: a positional parameter whose name, without a unit (`Seconds`, `Ms`, `Milliseconds`, `Minutes`, `Hours`, `Days`), is a span name and whose type is a bare `number` fails, because a span in a position of a parameter is a `Duration` or moves into an options object. So does a parameter named only for its unit (`seconds`, `ms`, `minutes`, …) with a bare `number`. What a package keeps behind `./internal` is for other packages: `pnpm api:check` fails for a name of an `./internal` entry that no file outside its package imports (imported by the code or tests of another package), and for a class that a public signature names but no entry point exports (mark the member that names it `@internal`, or export the class). A name that stands on purpose is in `INTERNAL_EXCEPTIONS` of `scripts/api-internal.ts` with its reason. A listed name that follows the rules fails the check until its line is deleted. A public constructor or member of a stable class that nothing outside its package uses is not API either: `pnpm api:check` (the `members:` block) fails for a constructor or member that no docs page, README, app (tests included), starter file or `stubs/` file uses, and for one that only the code of other framework packages uses — those may keep calling it once it is `@internal`, which hides it from the snapshot only. A use is `.member` or `?.member` in the text of such a file (`new Class(` for the constructor), Markdown read whole, so `session.flash()` in prose counts; the tests of a framework package never count. A class that a file of the docs, an app or the kit extends keeps its members, since they are the contract of a base class; a new public method of a class that apps extend needs a `Low` line in the upgrade guide, since a subclass may already have a member of that name. Not checked: `private`, `protected` and `#` members, `@internal` and `@experimental` ones, abstract and error classes, computed keys, `toString`, `toJSON`, `valueOf` and `then`. The match is by name, so a common name (`get`, `size`, `run`) is found somewhere anyway and escapes the check; the review of the snapshot catches the rest. A member that stays public on purpose is in `MEMBER_EXCEPTIONS` of `scripts/api-members.ts` with the reason an app needs it (the key ` .*` covers a class, ` *` an entry point). A line that matches nothing any more fails the check. `pnpm api:usage --members` (after `pnpm build`) shows per constructor and member where it is used. The same goes for a function, a constant and a type: `pnpm api:check` (the `exports:` block) fails for one of a stable entry point that no docs page, README, app (tests included), starter file or `stubs/` file uses (an import, also through an entry point that re-exports the name, or the name as code in a Markdown page), and for one that only the code or a `bin/` launcher of other framework packages uses; mark it `@internal`, stop exporting it, or list it. A type that a public declaration names is not checked (its shape is public anyway), nor are classes (the members rule covers them), re-exports, `@experimental` exports and names ending in `Error`, `Config` or `ServiceProvider`. An export that stays public on purpose is in `EXPORT_EXCEPTIONS` of `scripts/api-exports.ts` with the reason an app needs it (` *` covers an entry point). A line that matches nothing any more fails the check. `pnpm api:usage --files` shows per name where it is used. An entry point may only expose the types of the libraries `FOREIGN_TYPES` in `scripts/api.ts` lists for its package (Node's built-ins, `@marmeon/*` and `marmeon` are free); `pnpm api:check` fails otherwise. Each entry says why it is there — a peer the app installs, or the change that removes it. Add an entry only for a peer, and give a type of your own to anything else. A library a package builds on and never shows stands in `IMPLEMENTATION_ONLY` of `scripts/api-implementation.ts` (`@faire/mjml-react` for `@marmeon/react`): `pnpm api:check` fails when any `.d.ts` under the package's `dist/` names it, also one no entry point reaches, when the `api.md` lists it under "Types from other packages", or when a source file other than the listed adapter imports it. The same file ends with the package's **Environment** and **Commands**, read from the built code of the providers its `package.json` lists under `marmeon.providers` (`static config`, `static commands`) and, for the CLI, its built-in commands. A variable shows its default as JSON, or `required`, or `optional`; a default that only a config's `resolve` sets is not seen. A command shows its usage and its sorted options with their types — never its description, whose wording is no API. A command with `static hidden` is listed apart under **Hidden commands (not API)** and is no API, except those in `HIDDEN_COMMANDS_IN_API` of `scripts/api.ts`, each with its reason; a key that names no hidden command fails `pnpm api:check`. Exit codes cannot be read from the code; tests secure them. A config whose `env` is not made by `env({ … })` fails `pnpm api:check`, because its variables cannot be listed. `pnpm api:usage ` (for example `pnpm api:usage @marmeon/core`) lists, per export of an entry point from its `api.md`, the docs, apps, kit files, neighbour packages and tests that import it outside the package, with a first guess — `keep`, `testing`, `internal` or `drop` — for where the export belongs; `--files` names the importing files, `--json` prints the data. An export that a public declaration of another entry or package names (`namedBy`) is always a `keep`, since an app would otherwise meet it as a type it cannot import. A pull request that changes an `api.md` needs matching labels. The check "api label" (`.github/workflows/api-label.yml`, `scripts/api-label.ts`) compares the merge commit GitHub builds for the pull request with its first parent, `Experimental` and hidden-command items left out — so what merged into the base meanwhile is not counted as its change. A **removed** entry needs `breaking`; a removed `Referenced, not exported` item counts as a change, since an app cannot import it by name. A **changed** entry needs `breaking`, or `api-compatible` when no app breaks — a loosened parameter, or a constructor that is only exported as a type (core's `EnvString` and its kin), which no app can call anyway; `api-compatible` never covers a removal. A **new** entry needs a release label other than `docs` and `internal`. Environment variables and commands are entries like any other; hiding a command moves it out of Commands, so it counts as a removal and needs `breaking`. The check reminds and does not protect — a pull request runs its own copy of the workflow, the review is the protection — and it runs on untrusted code, so it holds no token and installs nothing: `pnpm check-release` keeps that shape, down to the files the script may import. #### Fixtures of stored and wire formats A format that outlives a process — a stored record, a cookie, a message between two nodes — keeps one fixture per supported version in `packages//src/__fixtures__/formats//v[-].`. One test of the package reads every file of that directory and checks that the code still reads it, or refuses it once its version is no longer supported, so a fixture nobody tests cannot sit there. The directory is append-only: a new version adds a fixture and leaves the old ones. Only a version that was once supported gets a fixture; data without the mark is a negative case written inside the test. "api label" asks for `breaking` when a pull request changes, renames or deletes a file under `formats/` (a new file is free), and `api-compatible` does not lift that — an old node or old data would otherwise read something else without anyone noticing before a rolling deploy. The DDL the schema builder writes is held the same way, per dialect, in `packages/database/src/__fixtures__/formats/ddl/{sqlite,pgsql}/` (`schema/ddl.test.ts` compares byte for byte; the Postgres files are written against the Postgres major in `compose.yaml`). `MARMEON_UPDATE_DDL=1 pnpm test:pgsql packages/database/src/schema/ddl.test.ts` writes them again — for a new group or a new file only. A changed v1 file means old migrations build another database, which is `breaking`. ### The upgrade guide `UPGRADING.md` has a section `## Upgrading to from ` for every breaking release. `pnpm check-release` (a part of `pnpm run ci`) refuses a section that is not headed exactly so — level 2, the version as x.y.z, steps as `###` inside it; any other heading that starts with "Upgrading to" or "Upgrading from" is refused. A section's `from` is the line directly below it (for 1.0.0 any 0.y.z), its entries are listed in `UPGRADING_ANCHORS` (`scripts/check-release.ts`) and every listed entry must stand under its release with its impact and its likelihood. A breaking release is a version `0.y.0` (y of 2 or more) or `x.0.0` (x of 1 or more), and `check-release` asks for its section; a patch or a feature release asks for nothing. Prerelease versions are refused. An entry is a `####` heading that starts with its impact (`#### High: …`, `Medium:` or `Low:`) under the section, and a line `*Likelihood of impact: high|medium|low…` in its body. ### Preparing a release Preparation is one command, again as often as needed. It needs a clean working tree, `HEAD` equal to `origin/` (`main` or the maintenance branch) and an authenticated `gh` with write access to the repository (it asks GitHub to generate the notes): ```sh git describe --tags --abbrev=0 --match 'v*' # the last release pnpm release:prepare --dry-run # the version and the notes it would write; nothing written pnpm release:prepare # write them and print the next steps ``` - **The version** comes from the last tag and the labels of the pull requests merged since: below 1.0 a `breaking` pull request makes a minor, anything else a patch; from 1.0 on `breaking` makes a major, `feature` a minor, anything else a patch. On a maintenance branch `breaking` is refused (it would leave the line). It stops while a merged pull request has no label and names it. Every published package gets the version and the same `## ` section on top of its `CHANGELOG.md` — `### Breaking changes`, `### Features`, `### Fixes`, `### Documentation`, new contributors, the full-changelog link. Sections of maintenance releases that `main` does not hold yet are carried over from their tags. - **1.0 and release candidates:** `pnpm release:prepare --major` makes `1.0.0` from a 0.x release whatever the labels ask for (from 1.0 on it is refused: the labels decide); it says whether a merged pull request is `breaking`. `--rc` makes a release candidate `x.y.z-rc.N` of the version the labels (or `--major`) ask for: the first run `-rc.1`, a run after `v-rc.1` is tagged `-rc.2`, and so on, for the same release. When the labels (or `--major`) come to ask for a higher release than the candidates lead to, they replace them: the version starts over (`--rc` at `-rc.1`), the log names the replaced candidates and their changelog sections stay. Candidates are made on `main` only. A run without `--rc` after a candidate makes the release itself. A candidate has its own changelog section, with the notes since the previous candidate; the release's section covers everything since the last release, and the candidates' sections stay below it. Only the release gets the `UPGRADING.md` heading. The deprecation check below sees the version already (`--major --rc` is refused for what `1.0.0` would be refused for). Other prereleases (`beta`, `alpha`) are not supported. - **A breaking release** gets the heading of its `UPGRADING.md` section and a placeholder comment naming the pull requests. Replace it with one entry per breaking pull request (impact, before → after, the way back) and list the anchors in `UPGRADING_ANCHORS` **before** the printed `git add -A` and commit; `check-release` refuses the comment. - **A release is refused while a deprecation is due:** every `@deprecated` tag or `deprecated()` call whose "Removed in x.y" is the release's version or an earlier one is listed with its path and line. Remove the API and its `deprecated()` calls with an entry in `UPGRADING.md`, or move the "Removed in" to the next breaking release. `--dry-run` refuses the same way. - **`.github/release-base`** holds the version and the commit the preparation started from (` `). The release commit has to sit directly on that commit; if another pull request merged in between, the release workflow refuses with "main moved after the release was prepared" — merge nothing else first, or run `pnpm release:prepare` again, which rewrites the section and the base. - Then follow the printed next steps: a branch `release-`, `git add -A`, the commit `Release `, **`pnpm run ci`**, and a pull request titled `Release ` with the label `internal` (it is no line of the notes itself). To update an open release pull request instead, recreate its branch from `main` (`git switch -C release-`), commit, and push with `--force-with-lease`; if the version changed (0.1.3 became 0.2.0 because a `breaking` pull request arrived), close the old one and open a new one. - **A release pull request changes the release files only:** the package versions and changelogs, `UPGRADING.md`, `.github/release-base` and `scripts/check-release.ts` (the anchor list). The release guard refuses a release commit that changes anything else. A failure that `pnpm run ci` finds elsewhere is fixed in its own pull request, merged first; then run `pnpm release:prepare` again. ### Releasing These are the maintainer's gates: 1. Merge the release pull request. 2. Start the *Release* workflow ("Run workflow") on `main`, or on the maintenance branch for a late fix of an older line. 3. Run `pnpm release:verify ` — it rebuilds the release commit and compares its tarballs with the staged ones (below). 4. Approve the staged versions on npmjs.com with two-factor authentication. 5. Publish the draft GitHub Release. 6. From 1.0 on, after a release (not a candidate), pin the release line's docs for the website (below). The run releases the **release commit** — the last commit of the branch that changed a package's `CHANGELOG.md` or `.github/release-base` — not the branch head, so whatever merged after it goes into the next release. The first job (`build`, `contents: read`, **no** OIDC token) runs `scripts/release-guard.ts` before anything is installed: the branch, the release commit (checked out, detached), one `x.y.z` or `x.y.z-rc.N` version, the same changelog section in every package, `v` not yet tagged, the version on no package of npm, the release base, the release commit changing release files only and the dist-tag (a release candidate: `main` only, above npm's `latest`). Then `pnpm run ci --only build,pack:check,check-release`, and `scripts/release-pack.ts` packs every package (`pnpm pack`) and writes `SHA512SUMS`; the tarballs and `SHA512SUMS` leave the job as an artifact (kept for a day), the hash of `SHA512SUMS` as its output. The second job (`stage`, `id-token: write`, the only job in the `npm-release` environment) checks out nothing, installs nothing and runs no script of the repository or of a dependency, so the code that runs in the first job never meets the OIDC token. It downloads the artifact, checks `SHA512SUMS` against the output and every tarball against `SHA512SUMS`. Then it asks npm, for every package whose tarball `SHA512SUMS` names, whether the package trusts this workflow. It makes the token exchange that `npm stage publish` makes, with a fresh ID token per package. It first refuses a tarball whose `publishConfig` holds anything but `access: "public"` and `provenance: true`: npm copies every `publishConfig` key into its options, a registry or a proxy among them. As defence in depth it refuses the tarball shapes it knows to be read differently by `tar` and by npm: entries that are not plain files below `package/`, and more than one `package/package.json`. `npm stage publish` gets the registry (`--scope=@marmeon` also covers the unscoped packages), the proxies, `strict-ssl` and `cafile` as flags, which win over `publishConfig`, so a manifest cannot move where npm sends the token or the tarball. A `ca` from a manifest can only make TLS fail. If one package does not answer with success, the job stops before it stages anything. Only then it stages the tarballs with `npm stage publish` (trusted publishing, OIDC, no token in the repository; provenance) and prints `SHA512SUMS`. The step tries a transient registry error again, skips a version the registry already holds (409) with a warning in a re-run (on the first attempt, a 409 on a tarball's first try stops the job; so does one after an error that left the upload unprocessed, such as a 429, `ENEEDAUTH` or a refused connection), and `pnpm release:verify` must pass before the approval. The hashes show that the staged files are the ones the first job packed, not that the first job packed what the release commit builds — step 3 closes that gap. The third job (`release`, `contents: write`, installs nothing) tags `v` on the release commit (one tag per release, none per package) and drafts the GitHub Release with the version's changelog section as its notes (a prerelease for a release candidate). **Before approving (required):** the builds are reproducible, so a rebuild of the release commit must give the very tarballs npm holds. The run's log has the commit's SHA; with an `npm login` session run `pnpm release:verify `. It rebuilds the commit in a temporary worktree (your checkout stays as it is), downloads every staged tarball with `npm stage download`, compares the SHA-512 of each with the rebuilt tarball of the same name, flags staged packages without a rebuild and rebuilt ones that are not staged, and exits 0 only when all match. That catches tarballs changed in CI (a compromised runner or action, a modified workflow), not a compromised dependency in the lockfile: the rebuild uses the same lockfile. The log's `SHA512SUMS` (printed by the *stage* job) is only a pointer to the right files: the log shows what the job checked, npm holds what will go live. Any difference — or a staged package you cannot account for — means: do not approve. Reject the staged versions (`npm stage reject `; the command prints the ids when the tarballs differ, otherwise `npm stage list` shows them) and look into the build job. By hand: `git switch --detach `, then `pnpm install --frozen-lockfile && pnpm run clean && pnpm build && node scripts/release-pack.ts "$(mktemp -d)/tarballs"`, then `npm stage download ` per package (`npm stage list` shows the ids) and `shasum -a 512` against the rebuilt tarball. Anyone with write access can start the workflow; the guards are conveniences and `check-release`'s check of the workflow files is a review aid, not a barrier. The gate is the maintainer's two-factor approval on npm — nothing is public without it, and the trusted-publisher configuration allows staging only, and only from the `npm-release` environment. npm accepts the OIDC token of a run in that environment only, so a workflow started on another branch cannot stage. Set it up as follows (npm >= 11.15, an `npm login` with 2FA, a maintainer's `gh`): 1. Create the environment (Settings › Environments) with deployment branches "Selected branches and tags": branch rules `main` and `*.x`, no tag rule, no secrets, no required reviewer — npm's 2FA approval is the gate. GitHub creates a referenced environment that does not exist *without* a branch policy, so never let the first run create it. 2. Verify the policy: `gh api repos/marmeon/marmeon/environments/npm-release --jq .deployment_branch_policy` must show `custom_branch_policies: true`, and `gh api repos/marmeon/marmeon/environments/npm-release/deployment-branch-policies --jq '.branch_policies[].name'` must list exactly `main` and `*.x`. 3. The "Protect Main" ruleset that covers `*.x` must include "Restrict creations", so only a maintainer can create a branch the environment admits. 4. Revoke each package's old trust: npm keeps one configuration per package, so `npm trust list ` and `npm trust revoke --id `. 5. Run `bash scripts/npm-trust.sh` (generated; passes `--environment npm-release`). It stops at the first package that still has an old configuration. 6. Verify: `npm trust list ` shows `environment: npm-release` for every package. A package's very first version has to be published by hand, before trusted publishing can be set up for it. The policies stay in place: the `LICENSE` holder, private reporting in `SECURITY.md` and the deprecation policy in the README. ### Pinning the docs of a release line Each release line from 1.0 on (`1.x`, `2.x`) has its docs on the website under `/docs//`, with its own `llms.txt`. A line is pinned to the commit of its release tag, and its docs are checked into `apps/website/content/lines//`; before 1.0 there are no lines, and `/docs` shows `main`. The website's image is built without a network and without `.git`, so it holds only what is checked in. After the draft GitHub Release is published (the tag `v` stands on the release commit, on `main` or on the line's branch): ```sh git fetch --no-tags origin main '+refs/heads/*.x:refs/remotes/origin/*.x' && git fetch origin refs/tags/v:refs/tags/v pnpm website:lines add v ``` The command writes the pin (`apps/website/docs-lines.json`) and the snapshot, and refuses a tag that is not an annotated `v`, that origin has elsewhere, or whose commit is on neither `origin/main` nor `origin/`. Open a pull request against `main` with the label `internal`; its diff is the text agents will read — review the snapshot before merging, since ancestry and the tag are checked only when the line is added. Then deploy the website (`deploy/website/compose.yaml`). Never edit a snapshot by hand: `pnpm website:check` (the `check` job) compares each one, byte for byte, with the tagged commit and the tag on origin with the pin, so a moved tag turns CI red while the website keeps showing the pinned commit. The `image` job builds the website's image, checks that the pins and snapshots are in it and, in a second container, a fixture line (`apps/website/modules/docs/__fixtures__/lines`) mounted in place of the pins, so no real line is needed in the repository for that. A maintainer sets up once, in the repository's settings: a ruleset on the tags `v*` that restricts updates and deletions and blocks force pushes (not creations: the release job creates the tag), and the protection of `*.x` branches — restricted creation and the rules of `main` — so that no branch from an unreviewed commit satisfies the ancestry check of a pin. Check with `gh api repos/marmeon/marmeon/rulesets`. ### A fix that comes late - **The release pull request is still open:** merge the fix, run `pnpm release:prepare` again on `main` and update the release pull request's branch. - **The release pull request is merged, the workflow not started:** run `pnpm release:prepare` again — for the same version it rebuilds the section from the previous tag to `HEAD` — and merge that small release pull request; its merge is the new release commit. - **Staged, not yet approved:** reject the staged versions on npmjs.com and release the next patch (a candidate: the next one, `--rc`). - **Released:** the next patch. A broken version is never unpublished; it is deprecated (`npm deprecate 'marmeon@0.2.1' 'Broken: use 0.2.2'`, for every package of the release). ### When a run fails - **The guard, a check or the packing in the `build` job is red:** nothing was staged. Merge the fix through a pull request, run `pnpm release:prepare` again (any merge moves the release base), merge that release pull request and start the workflow again. - **A hash check of the `stage` job is red** (before its first `npm stage publish`; the log says which line failed): nothing was staged, but the artifact is not what the `build` job hashed — do not re-run, look into the run, and start a new one. - ***"SHA512SUMS has a line that is not a hash and a tarball name"*** or ***"the build job's hash of SHA512SUMS is not a SHA-512 hash"***: nothing was staged. The file matched the `build` job's hash, or the hash itself came out wrong, so the `build` job wrote it that way: do not re-run, look into the `build` job (`scripts/release-pack.ts` and the dependencies it ran), and start a new release after the fix. - **The trust check of the `stage` job is red:** the "stage the tarballs" step is the same step, so read its log first. The step's messages speak for this attempt only. Nothing was staged only when this attempt's log ends with the trust check's `::error::` lines, and neither it nor an earlier attempt of the run (the attempt selector of the run page) shows output of `npm stage publish`: no `+ … (staged with id …)` line, no `npm notice Staging to …` line, no `npm error` line. Anything else falls under the bullet on a partly staged run below. - *"has no working trusted publisher"* (npm answered 401, 403 or 404): run the `npm trust github` line the log prints for each package it names. Revoke the package's old configuration first, as in the trust setup above (`npm trust list`, `npm trust revoke`); `scripts/npm-trust.sh` is no help here, it stops at the first package that already has one. Then use **"Re-run failed jobs"**. - *"could not ask the registry"* (any other answer, or none) or *"the trust check took … seconds"*: use **"Re-run failed jobs"**. - *"is not a tarball of version"*, *"a package name that is not one of ours"*, *"a publishConfig the stage job does not accept"* or *"is not a tarball the stage job accepts"*: the `build` job packed a tarball the stage job does not accept. Do not re-run; look into the run and the package list, merge the fix through a pull request and start a new release. A re-run keeps the `build` job's tarballs and outputs, so the version stays. The artifact is kept for a day: after that, start the workflow again, which costs nothing as long as nothing was staged. - **The "stage the tarballs" step is red once `npm stage publish` has run** (its log shows a `+ … (staged with id …)` line, an `npm notice Staging to …` line or `npm error` lines after the trust check): treat it as possibly partly staged. Read the log's last `::error::`: - *"is not confirmed as staged after 3 attempts"* (the registry answered 429, 500, 502, 503, 504, `ENEEDAUTH` or a connection error or timeout each time), *"ran out of time"*, or the job was cancelled by its time limit (the log ends without an `::error::`): use **"Re-run failed jobs"**, and **do not reject anything before it**. A rejected version answers 409 too, so the re-run would skip it and `pnpm release:verify` would then fail. The re-run stages every tarball again; on a re-run a 409 is skipped (on the first attempt, one on a tarball's first try stops the job, and a 409 after a timeout, a reset connection, `FETCH_ERROR` or a 5xx answer of the same tarball is skipped), so one that an earlier attempt staged prints a `::warning::` ("was staged before", the registry answered 409) and is skipped, and a closing `::notice::` counts them. The job then ends green, so the `release` job tags `v` and drafts the release before you verify: run `pnpm release:verify ` as always. If it reports a rebuilt package that is not staged or a hash that differs, do not approve: reject everything staged, delete the draft and release the next version as under "Staged, not yet approved". `--replace` refuses a tagged version, and plain `pnpm release:prepare` says "Nothing to release" until a pull request labelled `fix`, `feature`, `breaking` or `docs` has merged after the release commit (`internal` ones are not in the notes): merge the fix, or another such pull request, first. Its label decides the next version (a `feature` gives the next minor); a candidate uses `--rc`. The tag `v` and that version's changelog section stay; the tag is protected. - *"is on the registry already"* (a 409 in a first attempt that cannot be this run's own upload), a 401, 403 or 404, an unknown or unreadable code: never re-run it. A version the registry already holds cannot be this run's upload and this run tags nothing, but a re-run would skip the 409 and tag. Reject whatever was staged on npmjs.com, then run `pnpm release:prepare --replace` (a candidate: `--rc --replace`). It takes the untagged version the packages carry as rejected, removes its CHANGELOG sections and prepares the one after it (the next patch, or what the labels ask for if higher; a candidate: the next number) with the notes since the last tag. Merge that release pull request and start the workflow. A rejected breaking release moves its UPGRADING.md heading to the new version; the script says which `UPGRADING_ANCHORS` key in `scripts/check-release.ts` to rename. Later plain runs stay on the replacing version (within its line: a release that labels pushed too high still comes down when the label is fixed). - **The tag step or the draft step failed after staging:** use **"Re-run failed jobs"** on the run. It repeats only the `release` job with the `build` job's outputs; nothing is staged again, a tag that already stands on the release commit is kept, and the draft is created. **Never "Re-run all jobs"**, and never start a new run after one that staged: a staged version is invisible to `npm view`, so the guards cannot see it. - **If the re-run does not help,** or the workflow file itself was wrong (a re-run executes the same file again), approve on npmjs.com first, then tag and draft by hand (the release commit's SHA is in the run's log): ```sh git switch --detach notes=$(mktemp) git ls-remote --tags origin refs/tags/v # prints a line: the tag stands, skip the next two lines git tag -a v -m v git push origin refs/tags/v node scripts/release-notes.ts > "$notes" gh release create v --draft --verify-tag --title v --notes-file "$notes" # plus --latest=false for a maintenance release, --prerelease for a candidate ``` ### Maintenance releases A **line** is `0.` before 1.0 and `` from 1.0 on. Its branch is the line plus `.x` (`0.1.x`, `1.x`), cut from the line's last tag; it releases versions of its line only. Each fix is cherry-picked from `main` as its own pull request into that branch, with the same title and its own label so the notes find it. Then `pnpm release:prepare`, the release pull request and the workflow run on that branch exactly as on `main`. A patch of a pinned line moves that line's pin: after the release, `pnpm website:lines add v` as in "Pinning the docs of a release line" (older versions are refused). The branch needs the same ruleset as `main`: the `release label` check, squash merges only. Delete the branch when the line is done. The dist-tag follows from the version: above npm's `latest` (or none yet) it is `latest`, and the draft is marked latest; below it, `latest-` (`latest-0.1`, `latest-1`) and the draft is not marked latest, so `latest` never moves back. `main` never releases below `latest`, and a version equal to `latest` is refused. An app on an old line installs the exact version, or `pnpm add @marmeon/core@latest-0.1`. The section of a maintenance release reaches `main`'s changelogs with `main`'s next `pnpm release:prepare`. ### Release candidates A release candidate (`x.y.z-rc.N`, prepared with `pnpm release:prepare --rc`) goes through the same workflow, staging and approval, but only from `main` and only under the dist-tag `next`: never `latest`. Its draft GitHub Release is marked a prerelease, not the latest release. `scripts/release-guard.ts` picks the dist-tag and the prerelease flag from the checked version alone (`releaseTarget` in `scripts/release-rules.ts`); the workflow has no input, and `check-release` refuses one. The staging job checks the pair again: a version with `-rc.` is staged as `next` only, any other version never as `next`. A candidate must be above npm's `latest`; the release itself, `x.y.z`, is an ordinary release and takes `latest` from the candidates. To try one: `pnpm add @marmeon/core@next`. The first release of a package is a plain `x.y.z`: on a first publish npm points `latest` at the version whatever the tag, so the guard refuses a candidate while npm has no `latest`. After `x.y.z` ships, `next` still points at the last candidate (below `latest`) until a maintainer moves or removes it (`npm dist-tag add|rm`, with two-factor authentication). Between the first candidate and its release, the project is frozen: only pull requests labelled `fix`, `docs` or `internal` are merged, and `feature` and `breaking` ones wait. A security hardening is the exception ([Releases and Support](https://marmeon.com/docs/releases.md#what-is-public-api)): it may be merged and brings the next candidate; whether the version changes follows from its label, as for any release. ### The tarballs - Packages are packed with **pnpm** only — `npm pack` and `npm publish` of a directory ignore `publishConfig.exports` and would ship the `@marmeon/source` condition, TypeScript sources Node does not strip under `node_modules` (`pnpm pack:check` proves the tarballs). A release stages the finished tarballs as files (`npm stage publish ./.tgz`, from `scripts/release-pack.ts` and its `SHA512SUMS`), never a package directory. - **`pnpm pack:check`** holds each tarball to these rules: no tests, type tests, `__fixtures__`, `test-helpers` or build info (`stubs/` and `template/` ship whole — generators and create-marmeon copy them into apps, tests included); no `dist/` file without its source in `src/` (a leftover of an earlier build) and every source map's sources in the tarball; `LICENSE` byte for byte the root's (`pnpm license:sync`) and a `README.md`; the packed manifest without the `@marmeon/source` condition and `workspace:` ranges, every internal dependency (optional peers too) at the package's own version; every `exports`/`bin` target in the tarball and none of them TypeScript source; MIT, a repository with the package's directory, `engines.node`, public access with provenance; the driver rule (`checkDriverRule` in `scripts/packages.ts`: one wrapped driver is a dependency, one of several an optional peer, a library the app must share one instance of — OpenTelemetry API, React, Vite — a peer); no reference to the private record. Then publint (warnings count) and attw with the `esm-only` profile (the packages are ESM only, so the CommonJS resolutions are not checked). `create-marmeon` has no dependencies at all — it is the first thing a stranger runs — and its template has no `.env` and no `APP_KEY` with a value. The root `tsconfig.json` references every package. - The `marmeon` tarball carries the docs of its version: `pnpm build` copies `docs/*.md`, `UPGRADING.md`, `SECURITY.md` and `CONTRIBUTING.md` into `packages/cli/` (`scripts/docs-ship.ts`, gitignored, never checked in) and writes `docs/index.json` and `docs/llms.txt`. `pnpm pack:check` demands every copy byte for byte and nothing else under `docs/`. - `pnpm pack:smoke` makes a starter-kit app (pnpm) and a minimal one (npm) from the tarballs outside the repository and runs install, tests, lint, `marmeon doctor --json` (every check must pass, on both apps), build without `.env`, and `marmeon start` as exactly one Node process, loading neither oxc-parser nor pino-pretty; the Redis step needs the Redis of `compose.yaml`. The apps live under `$TMPDIR`, with no `node_modules/@marmeon` or `pnpm-workspace.yaml` above them. On the starter kit it then applies the notes demo (`examples/notes`: `commands.json`, `files/`, `edits.json` — each `find` of an edit occurs exactly once, and only `marmeon ` lines run) and runs that app's tests, type check, lint, build and start; `--keep` leaves the app with a confirmed test user and a few notes to look at. - A broken version is never unpublished; it is deprecated (`npm deprecate 'marmeon@0.2.1' 'Broken: use 0.2.2'`, for every package of the release) and fixed by the next patch. - `scripts/npm-trust.sh` is generated (`node scripts/npm-trust.ts`) — the `npm trust github` call for every package, run once by a maintainer after the first publish. ## Inside the framework What a contributor to the framework needs and an app never does. The exported functions and classes document themselves in their sources; these are the rules that span several files. ### The request context The context a handler and a middleware receive holds the keys of `RESERVED_CONTEXT_KEYS` (`@marmeon/router`) — everything of `RequestContext` plus `body` and `pageQuery` — and nothing in it may be replaced: `next(extension)` throws for a reserved key and for any key the context has already, and the router hands every context on frozen (nothing in the framework assigns to `ctx`; add a key with `next()`). A middleware that adds keys declares them in `static adds`, so that two on one route stop the start. A type test keeps the list equal to `keyof RequestContext | 'body' | 'pageQuery'`, so a key added to the context is added to the list in the same commit. After 1.0 the framework adds no new key to `ctx`; new request-scoped state goes into a container token, because an app's middleware may already use the name. ### The entry points of `@marmeon/core` Besides its main entry and the documented `@marmeon/core/diagnostics`, `@marmeon/core/dev` and `@marmeon/core/deprecation` (`deprecated()` without the rest of the core, for client code) and `@marmeon/core/testing` (`TestClock` and `EventFake`, for a test that builds its own container — the fakes of any package go to the `./testing` of their package, never to its main entry), the core has three entry points that only the framework imports: | Import | What | | --- | --- | | `@marmeon/core/internal` | what the framework's packages share and an app has no use for: injection analysis and embedding, the manifest, the file guard, the transaction frames, the request/job/task context, `messageBase`/`trace`/`publishEnded` of the diagnostics, `marmeonInjection()` (part of `marmeon()` in `@marmeon/vite`) and `CSP_NONCE_PLACEHOLDER`. Not API, outside semver; a name only a neighbour imports goes here, one nobody imports has no export | | `@marmeon/core/environment` | `environment` and `resolveEnvironment` alone, without dependencies — what `marmeon` loads before anything else | | `@marmeon/core/register` | the Node loader hook that writes the injection lists of app code. `marmeon` registers it in its own process (`module.registerHooks`) before a command loads; in a protected environment it takes `marmeon build`'s precomputed lists | `pnpm api:usage @marmeon/core` shows who imports each export and suggests where it belongs. ### The helpers of `Controller` `Controller` has six helpers (`view`, `island`, `json`, `redirect`, `back`, `closeLayer`) and gets no more: a new `protected` name would collide with a method of the same name in an app's controller. A new helper is a free function exported from `@marmeon/http`; a test in `controller.test.ts` holds the list. ### The source condition and the manifests The `@marmeon/source` condition is public: an app uses it for a package of its own workspace, and its name and meaning are API ([what is public API](https://marmeon.com/docs/releases.md#what-is-public-api)). The app sets `NODE_OPTIONS=--conditions=@marmeon/source` itself ([a package in your app's workspace](https://marmeon.com/docs/package-workspace.md#a-package-in-your-apps-workspace)); the installed CLI never does that for an app. Inside this repository the packages resolve to their TypeScript sources through the same condition, and the launcher adds it from its own location. A published package does not carry it (`publishConfig.exports`). `marmeon` runs a command in its own process and starts Node a second time only for what a running process cannot switch on: `node --watch` for `marmeon dev`, and the source condition when the CLI runs inside this repository — a `pnpm-workspace.yaml` above it lists its directory among `packages`. Never for `marmeon start`, which serves the packages' `dist/` here too. A copy of the CLI under `node_modules` (what `pnpm deploy` leaves) runs its `dist/` like a published package. Discovery writes one manifest per set of resolution conditions: `.marmeon/manifest.json` for the published packages and `.marmeon/manifest.source.json` inside this repository, so switching between `marmeon dev` and `marmeon start` here rewrites neither. Any other set gets its own file — Vitest adds `development`: `manifest.development+source.json`. ### The package protocol What a community package may rely on is the tables of [`docs/package-development.md`](https://marmeon.com/docs/package-development.md#the-package-protocol): the keys of the `"marmeon"` field, the statics of a provider and of the classes a package brings. A new static or key is additive and comes into its table in the same change (`scripts/package-protocol.test.ts` fails for a provider static that the table lacks); a new key of the field is also added to `MARMEON_KEYS` in `packages/core/src/discovery/discover.ts`, which refuses every other. ### The starter's template `packages/create-marmeon/template/base` is `apps/blank-app`: change the blank app, then run `pnpm template:sync` — a test fails while the two differ (`node scripts/sync-template.ts --check` names every file). The template stores `.gitignore` and `package.json` as `_gitignore` and `_package.json` (npm turns a `.gitignore` into `.npmignore` when it packs, and a nested `package.json` in a tarball confuses publint and bundlers; the scaffolder renames them back), makes `tsconfig.json` standalone, empties every `APP_KEY=` and leaves `README.md` out — the scaffolder writes each app its own README and keys. `template/kit` holds what the starter kit adds: the home module, the app's dialog, the look (`styles/app.css`) and, through `KIT_DEV_DEPENDENCIES` in `src/template.ts`, the font it imports as a dev dependency (kept equal to the website's). `MARMEON_CREATE_TARBALLS=` makes `create-marmeon` take the framework from the tarballs of `pnpm pack` in that directory instead of the registry. They are copied into the app's `vendor/marmeon/`, and every `@marmeon/*` dependency and `marmeon` point there (`file:`), the packages' dependencies on each other too — through `overrides` in `pnpm-workspace.yaml` for pnpm, with nothing hoisted and only for what gets installed (pnpm installs an overridden optional peer as if the app had asked for it), and in `package.json` for npm, the optional peers nobody installs by absolute path (npm resolves a relative override from the dependent's directory). A package the app adds later comes from its tarball: `pnpm add ./vendor/marmeon/marmeon-redis-.tgz`. That is how `pnpm pack:smoke` and `pnpm image:smoke` make their apps before anything is published. It is not for apps: the variable never reaches the install and the generators. The tests next to the kit's stubs (`packages/auth/stubs/react/modules/*/`) do not run where they lie: they import the app's paths, and the root `include` of Vitest takes no package's `stubs/`. They run once in `pnpm test`, in an app that `make:auth` writes: the starter kit in `packages/create-marmeon/src/kit.test.ts` ("the starter kit works"), on SQLite and, under `pnpm test:pgsql`, on Postgres. That one run also generates the routes, migrates, type-checks, lints (module boundaries on `modules/auth` and `modules/system`) and builds the kit. `pnpm pack:smoke` runs the tests again from the tarballs. `kit.test.ts` counts the passing tests of each `describe`, so a test added to one changes its count there. To run them alone: `pnpm test packages/create-marmeon/src/kit.test.ts`. Redis is covered by the copies of the modules in `apps/web-app`, so a change to a stub test belongs in its copy too. The stub tests of `@marmeon/oauth` (`packages/oauth/stubs/react/modules/oauth/`) run the same way in `packages/create-marmeon/src/kit-oauth.test.ts`, in a kit app that also ran `make:oauth` and `make:social-accounts-table`, with the same per-`describe` counts; `pnpm pack:smoke` does not run them. ### The client core and its adapters A UI adapter — `@marmeon/react` is the one there is — is a rendering layer. Everything else lives in the UI-free client core, `@marmeon/http/client`: the protocol, the history, the in-memory page cache, background requests and every security invariant. What an adapter builds on is `@marmeon/http/client/adapter` (stable, like every entry point); `@marmeon/http/client` keeps what an app uses — the `hooks` and `tabSync` handles for `useFeature()` (typed `FeatureHandle`), `xsrfToken` and the types an adapter re-exports. Adapter code and the browser parts of other packages import the core from these two entries only, never from `@marmeon/http/internal`; a name an adapter lacks goes into `/client/adapter`. A new required member of an interface an adapter implements is a `breaking` change; a new capability comes as an optional member or as a feature of the core (`defineFeature` is the framework's own route and `@internal`). `packages/http/src/client/adapter.test.ts` is the proof, written against the two entries: a complete adapter in plain DOM visits, goes back and forward, loads deferred props, reloads partially, follows a 409, and drives islands, layers, actions with their optimistic patches, flash messages, the navigation guard, live validation, instant visits, remembered state and tab sync between two tabs — with no UI framework anywhere. New protocol, visit, region or cache logic goes into the core first, with its case in that test, then into the React hook, then into the default component. An adapter provides: 1. **Rendering a page object.** `new Navigator({ initialPage, render, confirm, revalidateOnBack })`, then `navigator.start()`. `render(page, { preserveState, owner, layers, placeholder, transition })` shows the page and resolves once it is on screen — the navigator restores the scroll position after that; a rejection makes the browser load the URL itself. Islands render from `navigator.use(islands).region(url, { owner })` and their snapshots, layers in a modal frame with a page context of their own; render `layer.view` and a region's `snapshot.region`, which carry the optimistic patches. Flash messages come from `navigator.on('flash')`, never from props. 2. **Persistent layouts**, with error boundaries inside them. 3. **Head management** through a `TitleRegistry`; on the server the head is recorded for the SSR entry. 4. **The SSR renderer** (`SsrRender` of `@marmeon/http/page`): it resolves with the shell — the whole page with `complete` — and rejects when the shell cannot render. Each eager island and each streamed deferred group renders behind a boundary of its own, with its result in an inert JSON data block (`scriptJson`); groups inside a host element, returned as `streamedProps`. 5. **The hydration entry:** `readInitialPage()`, the component and the messages resolved before hydrating, `hasServerMarkup(root)` to hydrate or render. Without the Navigation API, `loadHistoryFallback()` in the same round trip, passed in `features` before the navigator writes its first entry. 6. **Hooks and components** over the navigator. Form state — values, errors, `processing` — stays per adapter; the core gives it the requests, the validation, the guard and the memory. 7. **Its route sinks:** every place where app code hands the adapter a route name is a row in `ROUTE_SINKS` of `@marmeon/vite`, so the client build ships only the names written out there. `@marmeon/react` has no provider: `"marmeon": { "browser": ["src/**"] }` marks every source as browser code, so discovery registers nothing for it and `marmeon package:build` embeds no injection lists. A test bundles it for the browser and fails on any module outside its own sources, the client core and its adapter entry, `@marmeon/http/page`, `@marmeon/http/protocol` and `@marmeon/router/url`, and on any npm package but React. ### Client features The navigator alone is the fixed core. Everything optional is a feature, and `NavigatorOptions.features` is empty by default. A feature is attached where it is used (`navigator.use(feature)`), loaded on first use as a chunk of its own (`navigator.load(loader)`), loaded beside the first page by default (tab sync, the History fallback), or loaded by the core when an answer of the server needs it (the layers, live props). A new feature: - is `defineFeature(name, setup, order?)`: `setup(host)` runs once per navigator, hooks into the pipeline with `host.on(…)` and returns what adapters use of it; - keeps what came from the server or the user **only in slots** — `host.entry(slot, key)` per history entry, `host.document(slot)` per document. The core empties an entry's slots when memory lets go of it and every slot when the document is left (every 409), so nothing of a signed-in user outlives a sign-out; - writes a history entry's state only through `host.history`, which takes positions and the fields registered with `host.history.field(name, check, value?)`. Anything else throws in development and is left out in production: no props in `history.state` or browser storage; - joins `ALL_FEATURES` in `packages/http/src/client/security-matrix.test.ts` (every feature × every event that must forget) and gets markers in the leak test of `packages/react/src/bundle-size.test.ts`, so it is in a bundle only with its own import. What any answer may need stays in the core, and so does every security invariant: the visit pipeline, Back and Forward, scroll restoration, the page cache and the history writer; the 409 that leaves the document, empties every slot and aborts every request; once, flash, deferred, merged and streamed props; a visit's own `confirm` and its optimistic patches; the `RegionOwner` of each entry on screen. The devtools' hook (`globalThis.__MARMEON_DEVTOOLS_HOOK__`) is called only under an inline positive `NODE_ENV` check, so a production build drops the calls. ### The bundle sizes `pnpm size` reports each scenario in KB gzip of the initial download, measured in Vite's app mode against `dist/` — minified, with production defines, without React, i18n and Vite's preload helper: | Scenario | What | | --- | --- | | `core` | the client core as an adapter uses it: the navigator, the document, links, forms, routes, titles, messages | | `emptyApp` | `createMarmeonApp` alone — an app without a page | | `minimalApp` | `createMarmeonApp`, `Link`, `useForm`, `usePage`, `Head` | | `everything` | all of `@marmeon/react`'s main entry | | `table` | `createMarmeonApp` and `useTable` | | `blank-app`, `web-app`, `website` | the real apps' client builds: the marginal cost of core and adapter in their initial load (React and the app's code do not move it) | - `pnpm size` prints the table; the `size` check measures this commit and the pull request's base commit (a worktree of it, installed from the lockfile and built) and writes base, this commit and the delta into the job summary. There is no limit: it fails when a build or a measurement breaks, never for a size. `pnpm size --base ` does the same locally (an install and a build of that ref). - `bundle-size.test.ts` is also the **leak test**: every feature has markers (its modules) and must be in a bundle only with its own import — a lazy one only in a lazy chunk. - `pnpm size web-app` (or a scenario name) attributes every byte to its module (source maps) and gives the marginal cost of core and adapter. - `marmeon()` splits an app's first download into a `vendor` and an `index` chunk (`CLIENT_CHUNKS` of `@marmeon/vite`), initial modules only; the scenarios are built the same way. ### Changing a stored or wire format A format is anything that outlives a process or crosses between two: a record, a cookie, a header, a message between nodes, a table the framework creates, a file it generates. [The public list](https://marmeon.com/docs/releases.md#stored-and-wire-formats) shows each with its mark. Seven rules: 1. **One mark per format, in a fixed place, with a frozen meaning**: a header value (`x-marmeon: 1`), a field (`v` in a job record, `_v` in a session), a version byte, a prefix, the columns of a table (`migrations`), a first line (`// @marmeon-format 1`). The envelope fields never change name or meaning. 2. **Additive changes need no new version, only when a reader that ignores the addition permits nothing more and misreads nothing.** A field that is ignored may cost comfort, never protection. Every change that restricts is a new version. 3. **A reader knows a set of versions**, one table `readers[version]` per format, and a test registers a synthetic next version to show that it reads the versions it should and refuses the one after. A newer version than the set is refused and left untouched, since a newer process may be running. An older version, or none, is carried over by a migration, or counts as missing: never interpreted, never defaulted. 4. **A writer writes version N only once every reader of the release before reads N**: expand in one release, contract in the next. Without that step, a change of format belongs to a major release with an upgrade guide. 5. **A fixture per version**, under `__fixtures__/formats/`, append-only, read by a test over the whole directory ([fixtures](https://marmeon.com/docs/contributing.md#fixtures-of-stored-and-wire-formats)). A format that a pull request changes needs `breaking`. 6. **Tables the framework creates have plain names** (`jobs`, `sessions`, …; only `migrations` and `migration_lock` are the migrator's), and the migrations a package ships (the files under a package's `stubs/`, the kit's among them) are append-only: once a file is on `main` it never changes, moves or goes, and a change is a new file that sorts after every file in its directory and does not repeat the name of one in its directory. A package ships its migrations from one directory, `stubs/migrations` (the kit's directory aside), and never moves them or adds a second. The "api label" check refuses a pull request that breaks this, whatever its labels. It judges each pull request against its own base: two pull requests that each add a file to the same directory are green apart and can sort wrongly once both are merged. An updated database is identical to a new one: tables, columns, and the names of indexes and constraints. Readiness is red while a required column does not fit the code. 7. **From 1.0 on, a change of format and a rename of a shared table is rolling**: rules 3 and 4, and for a table create anew, write twice, drop over two releases. In a release whose upgrade stops every process, nothing exists only so that an old process can run beside a new one: data of the old release is carried over by a migration or refused. A change of format also changes its row in the [public list](https://marmeon.com/docs/releases.md#stored-and-wire-formats) and, where it helps a mixed fleet, [the deployment page](https://marmeon.com/docs/deployment.md#what-else-a-mixed-fleet-does). ### Lint The repository lints itself with `pnpm lint` (`oxlint --deny-warnings`, part of `pnpm run ci`): the root `.oxlintrc.json` has oxlint's correctness rules as errors, plus `no-import-type-side-effects`, and turns a few off with a reason — unused private brands such as `readonly #event = true`, deliberate copies before deleting while iterating, `this` aliases that walk a parent chain. The apps carry the preset of `marmeon make:lint-config` — `apps/web-app` with `--boundaries`, `apps/blank-app` without — which oxlint takes for their files instead: nested configs replace, they do not merge. Two rules of `eslint-plugin-regexp` (loaded as an oxlint JS plugin) refuse regular expressions that run in super-linear time: `no-super-linear-backtracking` and `no-super-linear-move`, the latter catching trims such as `/^[. ]+|[. ]+$/g`, which restart at every character of a long run. They apply to `packages/*/{src,bin,stubs}` only — code an app runs, where text from a request or a user must not tie up the event loop — not to tests, fixtures, `scripts/` or the apps. Rewrite before allowing: `(?] ` on the same line (a comment above does not count), never by line number in `zizmor.yml`. `pnpm check-release` holds `ci.yml` to the shape the job relies on. ## Comments A comment earns its place by saying what the code cannot. Try a better name or a smaller function first; what is left to say follows these rules. No check reads a comment's quality — the review does. What stays: - **JSDoc on exported API** — the hover an app developer reads: one or two sentences on what it does, plus only what is not obvious (the default, when it throws, a security note). For more, link the docs page instead of retelling it. ```ts // Good /** Signs `url` for `hasValidSignature()`, valid until `expires`. See docs/urls.md#signed-urls. */ // Bad: the page retold, line by line /** Signs the URL. The signature is an HMAC over the path and the query, the key is APP_KEY, the expiry … */ ``` - **The why**, where the code would otherwise look wrong: a security invariant, a race, a browser or driver quirk, a deliberate deviation — one to three lines. ```ts // Good // Compare in constant time: an early exit would tell how much of the token matched. // Bad // Compare the tokens. ``` - **A file header** only when the file's role is not clear from its name and exports — a few lines. Good: "Vitest global setup: a temporary directory per run, and a red run when a test leaves an entry in it." Bad: a header that lists the exports. What goes: - **History and derivation** — "used to", "after the review", "we decided", "since", who wanted what when. Git keeps the history. Bad: `// Not cached any more since the logout bug.` Good: `// Not cached: a cached copy would outlive a sign-out.` - **Narration of the next line.** Bad: `// Increment the counter` above `count++`. Good: no comment — or the reason, if there is one: `// Counted before the await, so a second request sees it.` - **References to decisions, plans, findings and people** — `pnpm check:source` refuses them (rule 7). Bad: `// Changed as the review asked.` Good: `// Claimed in one statement, so two workers never take the same job.` - **Essays about behaviour.** What an app developer needs to know belongs on the docs page — move the sentence there, in the same commit; the rest goes. Bad: twenty lines on every option in a config file. Good: one line and `docs/queues.md#connections-and-drivers`. - **Duplicate JSDoc** on an interface and its implementation, or the same text on every overload. Document it once, where the reader hovers. Bad: the same paragraph above `interface Mailer` and `class SmtpMailer`. Good: the interface's only. - **Comments in tests that repeat the test's name.** The name says what is checked; a comment explains only setup that is not obvious. Bad: `// it logs out` inside `it('logs out')`. Good: `// Two processes on one database file: the lock must hold across them.` **Security invariants stay.** A comment that says what must never happen, or in which order something must run, may be shortened, never deleted. ## Writing documentation The docs under `docs/` are the framework's documentation: one page per topic, in the order `apps/website/docs.config.ts` lists them. They are the only source, written in English for people who build apps. **A change to a public API, an environment default or a command changes its docs page in the same commit.** No check compiles the examples, except those of the recipes, of "Your First App" and of the section "A package in your app's workspace" of `docs/package-workspace.md`, which `pnpm test` and `pnpm pack:smoke` check against an app; for every other page that commit is where they stay true. That section's heading, the titles of its code blocks and its `sh` block are tied to `scripts/workspace-package-smoke.ts`: the smoke writes the files from the blocks and runs the commands, so a rename there fails the smoke and `scripts/workspace-package-smoke.test.ts`. Comments in the code follow [Comments](https://marmeon.com/docs/contributing.md#comments). `pnpm website:dev` shows the pages on http://localhost:3970. `docs/installation.md` and `docs/routing.md` are the model for every other page. - **Structure.** `# Title`, then `## Introduction`: what the feature is, what it is for, and a first example, in one to three paragraphs. Then the sections, from the common to the rare. A short `## Testing` section at the end only where it helps — it links to the Fakes page instead of repeating it. - **One example per section** — a file and what goes with it, such as a route and its controller. Derive examples from real code: `apps/web-app`, the starter's template and the `make:auth` stubs. Compile a complex example once in a temporary file in `apps/web-app`, and delete the file again. - **Titles and imports.** A code block with a title names its file — the fence reads ```` ```ts title="modules/notes/routes.ts" ```` — and is complete enough to copy, imports included. A block without a title may continue an example of the same page, and leaves out the imports the page has already shown. - **Tone.** Address the reader as "you", in the present tense and the active voice. One idea per sentence. No chains of parentheses, no strings of abbreviations, no marketing adjectives. No decision numbers and no wave numbers, and no comparisons with other frameworks: a page stands on its own. - **Callouts, sparingly** — at most about one per section: `> [!NOTE]` for extra knowledge, `> [!WARNING]` for security and data loss, `> [!TIP]` for a shortcut. - **Security defaults** get two to four sentences: what the default does, why, and how to change it on purpose. - **Configuration** is a table with the columns Variable, Default and Effect. The default is the one in the code's schema. - **Links** are relative links to other docs pages: `[route model binding](routing.md#route-model-binding)`. Link to an anchor only on a page that is written; a page still marked pending gets a link without one. Never link to a package README or a source file — a reader of the website cannot follow it. - **Placeholders.** Every page is written: `pnpm check:source` refuses a page that carries `` as a line of its own. While you write a new page, the marker on line 2 marks it "draft" in the navigation of `pnpm website:dev` (the website removes the line); delete it before you commit. - **Code that names a page** — a solution's `docs`, an error message, a comment — names its repository path with the anchor: `docs/migrations.md#running-migrations`. A test of the website (`apps/website/modules/docs/links.test.ts`) follows every such path in the packages' code, the stubs, the starter's template, the apps, the package READMEs and the root README to its page and anchor, refuses a path to a package README, and refuses a page without its anchor outside the READMEs (which list pages). - **Recipes** are flat pages, `docs/recipe-.md`, in the navigation section "Recipes". A recipe walks through one task with the generators: `# Task`, `## Introduction` (the task, what it writes, the threat it guards against), `## Generate` (the `make:*` commands in order, in one `sh` block), `## What it writes` (a table of file and purpose), `## The code`, `## The test`, `## Check` and `## Where to go next`. A recipe shows only what exists: where there is no generator, it writes the file as the topic's page shows it and does not say a generator exists. Its code is checked like "Your First App": the directory `examples/recipes/` holds an overlay in the format of `examples/notes` (`files/` optional, `edits.json`, `commands.json`) and a `recipe.json` with the `page` and, for what a generator writes, a `reference` directory such as `apps/web-app`. `pnpm test` (`scripts/recipes.test.ts`) requires every `ts`, `tsx` and `json` block to carry a `title`, every titled block to be part of an overlay file, an edit or the reference file of that path, and every command of `commands.json` to stand in the `sh` blocks in order. `pnpm pack:smoke` lays all overlays on the starter kit after the notes demo and requires each titled block to stand word for word in the app's file, the tests, the type check and the lint to pass, `marmeon check` to pass without a finding in `raw-sql`, `inner-html` or `throttle`, and `marmeon docs` to list every recipe. A recipe has a module of its own and changes no file of the kit that another overlay changes. - **Length:** as long as the topic needs. A page past about 600 lines probably wants splitting — propose it rather than splitting on your own. - **Package READMEs are cards for npm**, not documentation: one sentence on what the package is, how to install it (or that a new app has it), one short example taken from its docs page, the page's links and the licence line. npm shows a README without the repository, so a card links with absolute website URLs (`https://marmeon.com/docs/#`) — the website's links test checks each page and anchor. A package that needs a third-party driver names the exact install command. Everything else belongs on a docs page. When the code and a README disagree, the code is right: describe what it does, and report the difference (or the bug) rather than writing around it. ## Reporting a vulnerability Never in a public issue — see [SECURITY.md](https://marmeon.com/docs/security-policy.md). --- # Security policy ## Reporting a vulnerability Please do not report a vulnerability in a public issue, a pull request or a discussion. Use GitHub's **private vulnerability reporting**: the repository's *Security* tab → *Report a vulnerability* (). Only the maintainers see the report. Without a GitHub account, or when GitHub is not an option, write to **** — only the maintainers read it, too. The steps below are the same either way. Please include what you can of: - the package and version (or commit), Node's version, the driver or configuration involved; - what an attacker can do, and what they need for it (an account, a position on the network, a setting); - the steps to reproduce it, ideally as a failing test or a small app. What happens then: - You hear back within **five working days** — that the report arrived and whether we can reproduce it. - We work on the fix in a private fork of the advisory and keep you informed; you are welcome to review the fix. - A fix is released for the supported versions (below), and the advisory is published with it — with credit to you, unless you ask us not to. A CVE is requested through GitHub where it applies. - Please give us 90 days before you disclose anything yourself, or less once a fixed release is out. ## Supported versions Security fixes are released for the **latest minor version of the current major version** (1.x). The previous major version receives them for 12 months after the next major is released, as patches on its last minor version under the npm dist-tag `latest-`. 0.x receives none — upgrade along [Upgrading to 1.0.0 from 0.4.0](https://marmeon.com/docs/upgrading.md#upgrading-to-100-from-040) ([which versions get fixes](https://marmeon.com/docs/releases.md#which-versions-get-fixes)). | Version | Security fixes | |---|---| | 1.x, latest minor | yes | | 1.x, older minors | no — upgrade to the latest minor | | 0.x | no — upgrade to 1.0 | ## What is in scope The packages of this repository (`@marmeon/*`, `marmeon`, `create-marmeon`) and what they generate (`marmeon make:*`, the starter kit). The demo apps under `apps/` are examples, not products — a flaw there is welcome as a normal issue unless it lies in framework code they show. What an app protects by itself and what it leaves to you is summed up in [Security](https://marmeon.com/docs/security.md); the details are on their pages — [sessions](https://marmeon.com/docs/session.md), [CSRF protection](https://marmeon.com/docs/csrf.md), the [Content-Security-Policy](https://marmeon.com/docs/csp.md), [authentication](https://marmeon.com/docs/authentication.md) and the production setup in [deployment](https://marmeon.com/docs/deployment.md). --- # Packages ## Introduction Marmeon is a set of packages that are released together. A new app depends on most of them already, and you add the others when you need what they bring. Each installed package registers itself through [discovery](https://marmeon.com/docs/modules.md#discovery), so adding one is a single command, in the version your app already has: ```sh pnpm marmeon add redis ``` Without `marmeon add` (yarn, bun, a workspace), install it yourself: `pnpm add -E @marmeon/redis@`. Every package has the same version as every other: upgrade them together. Each pins the others exactly, so one in another version (`pnpm add @marmeon/redis` takes `latest`, which an app on a release candidate is not) brings a second copy of `@marmeon/core`, and the package manager's only sign is a warning about peers. `-E` saves the version exactly. A new app saves exactly by itself (`saveExact: true` in `pnpm-workspace.yaml`, `save-exact=true` in `.npmrc` for npm); an app that is older can set it too. [`marmeon check`](https://marmeon.com/docs/check.md#the-packages-check) finds a package in another version, and `marmeon dev` warns about it at the start. The [release policy](https://marmeon.com/docs/releases.md) explains why. ## What a new app has `pnpm create marmeon` installs these packages: | Package | What it brings | Read more | | --- | --- | --- | | `@marmeon/core` | The application, modules, service providers, the container, configuration, events and the clock. | [Modules](https://marmeon.com/docs/modules.md), [container](https://marmeon.com/docs/container.md), [providers](https://marmeon.com/docs/providers.md), [configuration](https://marmeon.com/docs/configuration.md), [events](https://marmeon.com/docs/events.md) | | `marmeon` | The command: `dev`, `build`, `start`, the generators and `tinker`. | [Console](https://marmeon.com/docs/console.md), [deployment](https://marmeon.com/docs/deployment.md) | | `@marmeon/router` | Routes, invokable controllers, requests with schemas, route model binding and middleware. | [Routing](https://marmeon.com/docs/routing.md), [controllers](https://marmeon.com/docs/controllers.md), [requests](https://marmeon.com/docs/requests.md), [middleware](https://marmeon.com/docs/middleware.md) | | `@marmeon/http` | Controllers, pages and their props, redirects, signed URLs, cookies, and the browser's side of every visit. | [Responses](https://marmeon.com/docs/responses.md), [pages](https://marmeon.com/docs/pages.md), [URL generation](https://marmeon.com/docs/urls.md) | | `@marmeon/server` | The HTTP server, server rendering, health checks and the graceful stop. | [Request lifecycle](https://marmeon.com/docs/lifecycle.md), [health checks](https://marmeon.com/docs/health.md) | | `@marmeon/session` | Sessions with their drivers, flash data and CSRF protection. | [Session](https://marmeon.com/docs/session.md), [CSRF protection](https://marmeon.com/docs/csrf.md) | | `@marmeon/encryption` | Encryption with `APP_KEY` and key rotation, behind every cookie and session. | [Encryption](https://marmeon.com/docs/encryption.md) | | `@marmeon/validation` | The validation rules, with messages in the request's language. | [Validation](https://marmeon.com/docs/validation.md) | | `@marmeon/i18n` | Translations, the request's language and formatting. | [Localization](https://marmeon.com/docs/localization.md) | | `@marmeon/database` | Connections, migrations, table types, repositories, factories, transactions and pagination. | [Database](https://marmeon.com/docs/database.md), [repositories](https://marmeon.com/docs/queries.md), [migrations](https://marmeon.com/docs/migrations.md) | | `@marmeon/cache` | The cache, atomic locks and rate limits. | [Cache](https://marmeon.com/docs/cache.md), [rate limiting](https://marmeon.com/docs/rate-limiting.md) | | `@marmeon/auth` | Sign-in, password hashing and reset, the confirmation of an address, API tokens, policies and `make:auth`. | [Authentication](https://marmeon.com/docs/authentication.md), [authorization](https://marmeon.com/docs/authorization.md), [starter kit](https://marmeon.com/docs/starter-kit.md) | | `@marmeon/mail` | Mails as classes, queued sending and previews. | [Mail](https://marmeon.com/docs/mail.md) | | `@marmeon/queue` | Jobs, workers, retries and failed jobs. | [Queues](https://marmeon.com/docs/queues.md) | | `@marmeon/scheduler` | Scheduled tasks. | [Task scheduling](https://marmeon.com/docs/scheduling.md) | | `@marmeon/storage` | Disks on the local file system or S3, signed URLs and uploads. | [File storage](https://marmeon.com/docs/storage.md) | | `@marmeon/live` | Live updates: pages reload their data when the server hints a change. | [Real-time updates](https://marmeon.com/docs/realtime.md) | | `@marmeon/notifications` | Notifications over mail, the database and live updates. | [Notifications](https://marmeon.com/docs/notifications.md) | | `@marmeon/fetch` | Outgoing HTTP requests that refuse addresses that are not public, with a fake for tests. | [HTTP client](https://marmeon.com/docs/http-client.md) | | `@marmeon/log` | The logger: readable in development, JSON in production. | [Logging](https://marmeon.com/docs/logging.md) | | `@marmeon/react` | The React side: pages, layouts, ``, forms, islands and dialogs. | [Pages](https://marmeon.com/docs/pages.md), [navigation](https://marmeon.com/docs/navigation.md), [forms](https://marmeon.com/docs/forms.md) | As dev dependencies, a new app has three more: | Package | What it brings | Read more | | --- | --- | --- | | `@marmeon/vite` | The Vite plugin: the entries, the injection lists and the check that keeps server code out of the browser. | [Asset bundling](https://marmeon.com/docs/vite.md) | | `@marmeon/testing` | `createTestApp()`, requests and assertions, the database refresh and the fakes. | [Testing](https://marmeon.com/docs/testing.md), [fakes](https://marmeon.com/docs/fakes.md) | | `@marmeon/devtools` | What the app did while you develop: requests, queries, jobs and mails. Development only. | [Devtools](https://marmeon.com/docs/devtools.md) | ## Packages you add | Package | What it brings | Read more | | --- | --- | --- | | `@marmeon/redis` | Redis connections for the cache, sessions, the queue and live updates. | [Redis](https://marmeon.com/docs/redis.md) | | `@marmeon/table` | Data tables driven by the server: columns, sorting, filters, actions and CSV export. | [Data tables](https://marmeon.com/docs/tables.md) | | `@marmeon/chat-notifications` | Chat messages to Slack, Discord and Teams through incoming webhooks, now or queued, with a fake for tests. | [Chat notifications](https://marmeon.com/docs/chat-notifications.md) | | `@marmeon/oauth` | Social login: OAuth 2.0 and OpenID Connect providers you register by name, linked accounts and `make:oauth`. | [Social login](https://marmeon.com/docs/oauth.md) | | `@marmeon/otel` | OpenTelemetry traces of requests, queries, jobs and mails. | [Observability](https://marmeon.com/docs/observability.md) | Add one with `marmeon add`, which installs it at the version of your app: ```sh pnpm marmeon add redis ``` The command takes the short name (`redis`) or the full one (`@marmeon/redis`), and no version. It does four things: 1. It installs the package with your package manager (pnpm or npm, by your lockfile) at exactly the version of your app, as a development dependency for `devtools`, `testing` and `vite`. 2. It runs `marmeon discover`, so the app finds the package's provider. 3. It copies the migrations of a package that ships some (`auth`, `cache`, `live`, `notifications`, `oauth`, `queue`, `session`, `storage`) with `marmeon publish`. That boots the app, so it needs a `.env` the app boots with. 4. It prints the next step: `marmeon migrate` after a publish, and the `marmeon docs` page of each package. `marmeon add redis --dry-run` prints the commands and changes nothing. If the install fails or you press Ctrl-C, `package.json` and the lockfile are put back as they were; run `pnpm install` to bring `node_modules` back. A pnpm that stops because a dependency's build script is not approved (`ERR_PNPM_IGNORED_BUILDS`) needs `pnpm approve-builds` first. Once the install has finished, its files stay as it left them, even when a later step fails: when the package manager installed another version than your app's (a release the package manager holds back for its first day, for example), or when `discover` or `publish` fails. The command then says what to run. `marmeon add` refuses when it cannot be sure of the result: your framework packages are not all in one version, one comes from a workspace, a path or a patch rather than the registry, the package is listed only under `peerDependencies`, the app is part of a workspace or holds one, it has no lockfile or one of another package manager, `package.json` cannot be read, or anything else the command names. It then says what to change. With yarn or bun, or in a workspace, install the package yourself at the version of your app (`pnpm add -E @marmeon/redis@`) and run `marmeon discover`, and `marmeon publish ` for a package with migrations. A package that needs a library of its own names the exact install command when the library is missing. The [deployment](https://marmeon.com/docs/deployment.md#drivers-what-an-app-installs) page lists them. ## The creator `create-marmeon` is the package behind `pnpm create marmeon`. It writes a new app and is not a dependency of it. The [installation](https://marmeon.com/docs/installation.md) page covers its questions and options. --- # Installation ## Introduction Marmeon is a full-stack framework for TypeScript. One command creates a new app: a server that renders React pages, a database, sessions, mail, a queue, a scheduler, file storage, live updates and notifications, already wired together. You run it with one more command and register your first account a few seconds later. ```sh pnpm create marmeon my-app cd my-app pnpm dev ``` This page walks through those three commands: what you need first, how you call the creator, what it writes, and what runs when you start the app. ## Requirements You need **Node.js 26.10** or newer. Marmeon runs your TypeScript directly on Node, without a compile step, and relies on what recent Node versions provide for that. An older Node stops the creator before it writes a single file. [Supported platforms](https://marmeon.com/docs/releases.md#supported-platforms) says which Node, TypeScript and library versions Marmeon supports and how that changes. You also need a package manager. Marmeon is built and tested with **pnpm 12**, and a new app pins the exact version in its `package.json` (`"packageManager": "pnpm@12.9.1"`). npm works as well, with `--npm`. Marmeon runs on Linux and macOS; on Windows, use WSL 2 ([operating systems](https://marmeon.com/docs/releases.md#operating-systems)). Nothing else is required. The app uses SQLite in a file by default, so you need no database server to get started. ## Creating an app Run the creator with the directory of the new app: ```sh pnpm create marmeon my-app ``` With npm, the creator's own flags follow a `--`: ```sh npm create marmeon@latest my-app -- --npm ``` The directory must not exist yet, or it must be empty. Its name becomes the package name, and a readable form of it becomes the app's name: `my-app` is the package `my-app` and the app "My App". ### Options | Option | Effect | | --- | --- | | `` | The directory of the new app. On a terminal it is asked for when you leave it out. | | `-y`, `--yes` | Takes the defaults and asks nothing: the starter kit, pnpm, the install and a first commit. | | `--minimal` | A blank app instead of the starter kit: no sign-in, no home page. | | `--docker` | Adds a `Dockerfile`, a `.dockerignore` and a `compose.production.yaml`. | | `--agents`, `--no-agents` | Installs the framework's skills for coding agents and registers `marmeon mcp` in `.mcp.json`, as `marmeon agents:install` does; the block of `AGENTS.md` then names the skills and the tools. Off unless you choose it; on a terminal the creator asks. | | `--npm`, `--pnpm` | Chooses the package manager. pnpm is the default. | | `--no-install` | Writes the files only. The output lists the commands to run next. | | `--no-git` | Creates no git repository. | | `-h`, `--help` | Shows the help. | | `-v`, `--version` | Shows the version. Every framework package of the new app has this same version. | These flags and the [exit codes](https://marmeon.com/docs/installation.md#without-a-terminal) are [API](https://marmeon.com/docs/releases.md#what-is-public-api). ### Without a terminal In a script or in CI, the creator never waits for an answer. The flags and the defaults decide everything. A missing directory ends the run with exit code 2: ```text create-marmeon needs a directory: create-marmeon [--yes] ``` Every wrong call ends with exit code 2: an unknown flag, two directories, or `--npm` together with `--pnpm`. A directory that is not empty and a Node older than 26.10 end with exit code 1, before anything is written. So does a missing pnpm when the creator is about to install. When a later step fails, for example the install, the run ends with exit code 1 and shows that step's output; only `marmeon agents:install` just warns and the run ends with exit code 0. The directory stays as it was at that moment, so you can fix the cause and run the step yourself. Ctrl+C at a question ends the run with exit code 130. Unless you say yes to the question or pass `--agents`, nothing is installed for agents beyond `AGENTS.md` and `CLAUDE.md`. ## What you get The creator copies the app's template, writes its `package.json` and `.env`, installs the dependencies and runs the app's own generators. It then creates a git repository with one commit, unless the directory is already inside a repository. The creator also writes `marmeon-stubs.json`, which records the version and the hash of every file it copied unchanged. Files it fills in for your app or that commands rewrite, namely `package.json`, `.env.example`, `.env.test`, `README.md`, `index.html`, `bootstrap/app.ts`, `bootstrap/client.tsx`, `bootstrap/head.ts` and the generated types `bootstrap/routes.ts` and `bootstrap/database.d.ts`, and the migrations are not in it. [The starter kit](https://marmeon.com/docs/starter-kit.md#what-the-auth-module-holds) says what the file is for. The creator writes the setting that saves a package you add exactly, not as a range: `saveExact: true` in `pnpm-workspace.yaml` for pnpm, `save-exact=true` in `.npmrc` with `--npm`. Every `@marmeon/*` package must have the app's version, and a range would let `pnpm add @marmeon/redis` pick another. `marmeon add redis` installs the version of the app (see [packages](https://marmeon.com/docs/packages.md)). The creator also runs `marmeon agents:sync`, so an installed app has an `AGENTS.md` and a `CLAUDE.md` for coding agents, both in the first commit. With `--no-install` the command is one of the next steps. They are not in `marmeon-stubs.json`: the block in `AGENTS.md` changes with every release and the rest is yours. With `--agents` it also runs `marmeon agents:install`, the last step before git, so the skills and `.mcp.json` are in the first commit too. When that step fails, the creator only warns, names the command among the next steps and ends with exit code 0: the app is complete. See [coding agents](https://marmeon.com/docs/agents.md). ### The starter kit By default you get the starter kit. It is a complete app with accounts: - **An auth module** in `modules/auth/`: sign-in, registration with a confirmation mail, password reset, a security page with "sign out other devices", and API tokens. The `marmeon make:auth` generator writes it into your app, so the code is yours to read and change. - **A home page** in `modules/home/` and a **dashboard** for signed-in users, framed by the auth module's layout. - **Tests** for all of the above. The starter kit's registration is private: it never tells anyone whether an address already has an account. The [starter kit](https://marmeon.com/docs/starter-kit.md#private-registration) page explains what that means and how to turn it off. ### A blank app `--minimal` creates a blank app. It has one module, `system`, that holds the tables of the framework's queue, notifications and live updates. You add your own modules from there. Both kinds of app share the rest: `bootstrap/`, the configuration, the security headers, the devtools that record what the app does while you develop, Vitest and oxlint with the app's own preset. ### The environment file The creator writes `.env` from `.env.example` and puts a fresh application key into it: ```sh title=".env" NODE_ENV=development APP_NAME="My App" APP_URL=http://localhost:3000 APP_KEY=base64:… PORT=3000 ``` `APP_KEY` encrypts the session cookie and everything else the app encrypts or signs. The file is readable by its owner only, and git ignores it, like every `.env*` file except `.env.example` and `.env.test`. `.env.example` lists the common settings with a comment and carries no key. `.env.test` is what the tests run with, and it has a test key of its own. `NODE_ENV=development` in `.env` makes every `marmeon` command on this machine run in development: the server, `migrate`, the queue worker. The [configuration](https://marmeon.com/docs/configuration.md#the-environment-node_env) page explains how `NODE_ENV` and the other variables are resolved. > [!WARNING] > `.env` belongs to this machine. Never deploy it. On a server, set `NODE_ENV=production`, `APP_KEY`, `APP_URL` and the rest in > the real environment, which always wins over `.env`. The [deployment](https://marmeon.com/docs/deployment.md) page lists what a server needs. ### The database The app starts on SQLite, in the file `storage/database.sqlite`. The creator runs `marmeon migrate`, so the tables exist when you first start the app. In development, `migrate` also writes the table types to `bootstrap/database.d.ts`, which the type checker uses for every query. You switch to PostgreSQL in four steps: 1. Install the driver: `pnpm add pg@^8`. 2. Set `DB_DRIVER=pgsql` and the server's `DB_HOST`, `DB_PORT`, `DB_DATABASE`, `DB_USERNAME` and `DB_PASSWORD` in `.env`, or its whole address in `DB_URL`. The database's name is required, there is no default. 3. Set `DB_DATABASE` in `.env.test` to the test database's name. It says `:memory:`, which is SQLite's, and the start refuses `DB_DRIVER=pgsql` with it unless `DB_URL` names the database. 4. Create the app's database on the server. The test database need not exist: the tests create their workers' databases next to it, through the server's `postgres` database when the test database is missing, so the role in `.env.test` needs the right to create and drop databases. [Database testing](https://marmeon.com/docs/database-testing.md) shows how the tests run on Postgres. ### Security from the start A new app answers with security headers and a strict Content-Security-Policy with a fresh nonce on every page. Guests get no session cookie until something needs one. The stylesheet of the framework's components is imported in the client entry, so no component writes a `style` attribute that the policy would have to allow. ## Running the app Start the development server from the app's directory: ```sh pnpm dev ``` `pnpm dev` runs `marmeon dev`. It serves the app on http://localhost:3000 and starts what the app needs next to it: - **The server**, with Vite in front of it. Changes to a page appear in the browser at once. Changes to server code restart the server. - **A queue worker**, which runs the queued jobs. The starter kit sends its mails through the queue. - **The scheduler**, when a module has scheduled tasks. The starter kit's auth module prunes expired tokens at night. `marmeon dev` runs in development unless your shell or the app's `.env` sets another `NODE_ENV`. Then it says so and serves the build instead, without Vite, the devtools, the worker and the scheduler. In development, a failing page shows the development error page: the code that threw, the request's queries and suggested solutions. The devtools record requests, queries, jobs and mails at http://localhost:3000/_marmeon/devtools, and a small panel at the bottom right of every page links to them. The [devtools](https://marmeon.com/docs/devtools.md) page covers both. ### Your first account Open http://localhost:3000 and register. The confirmation mail does not leave your machine: in development the mailer writes every mail to the log. The queue worker sends it a moment after you register, and it appears in the terminal where `pnpm dev` runs. Copy the confirmation link from it and open it. The app asks you to sign in first, confirms the address and takes you to the dashboard. > [!NOTE] > In development and tests the log mailer writes links and tokens in plain text. Outside development and tests it logs only recipients > and subjects, sends nothing, and the app warns at every start while `MAIL_DRIVER` is still `log`. Set up a real mailer before anyone else uses the app. ### Tests and lint The app's tests and lint run with two more scripts: ```sh pnpm test pnpm lint ``` `pnpm test` runs Vitest over `modules/**/*.test.ts`, on an in-memory SQLite database with the settings of `.env.test`. `pnpm lint` runs oxlint with the app's preset. The preset keeps views from importing server code by value, which would bundle it into the browser. The [testing](https://marmeon.com/docs/testing.md#creating-the-test-app) page explains how a test boots the app. With npm, the scripts are `npm run dev`, `npm test` and `npm run lint`. The `marmeon` command itself runs as `pnpm marmeon ` or `npx marmeon `. ## The documentation of your version `marmeon` ships the documentation of its own version: every page of this site, the [upgrade guide](https://marmeon.com/docs/upgrading.md), the [security policy](https://marmeon.com/docs/security-policy.md) and the [contribution guide](https://marmeon.com/docs/contributing.md) as Markdown files under `node_modules/marmeon/docs/` (the three policies sit one level up, so a link such as `../UPGRADING.md` works there too). A person or a coding agent reads what matches the installed version, offline, without guessing which release a web page describes. - `docs/.md` is the page `/docs/` of this site, for example `docs/routing.md`. - `docs/index.json` lists the sections and pages in reading order, `docs/llms.txt` does the same as links for a reader without a parser. - `marmeon docs` lists the pages and prints one, see [reading the documentation](https://marmeon.com/docs/console.md#reading-the-documentation). - A `docs/.md` named in the output of a `marmeon` command is a file in that directory. Under pnpm the path is stable, because `marmeon` is a direct dependency of the app. The files take about 1.6 MB on disk (0.5 MB to download), once per app. ## The first day after a release pnpm installs no package version younger than its `minimumReleaseAge`, one day by default. This protects you from a package that is pulled again soon after it appears. For a day after a Marmeon release, `pnpm create marmeon` therefore does not stop: it takes the previous release of the creator, and the install succeeds without a message. The creator writes its own version, exactly, for every `@marmeon/*` package and `marmeon`, so the new app is on the previous release. `marmeon` and the `@marmeon/*` entries in its `package.json` show which one. `pnpm create marmeon@next` falls back to an older version the same way. Wait a day, or let only the framework through for this one command: ```sh pnpm_config_minimum_release_age_exclude='["@marmeon/*","marmeon","create-marmeon"]' pnpm create marmeon@ my-app ``` Name the version of the release (for a candidate its own version, `x.y.z-rc.N`) in the command. pnpm keeps the creator it fetched for a spec as written, so after a `pnpm create marmeon` earlier that day, a plain `pnpm create marmeon` serves the old creator again. The variable reaches the install the creator runs and changes nothing else. The creator never changes your pnpm settings. npm has no such delay. ## Next steps - [Your First App](https://marmeon.com/docs/first-app.md) builds a small notes app on the starter kit, step by step. - [Directory Structure](https://marmeon.com/docs/structure.md) shows where everything in the new app lives, and walks you through your first module. - [Configuration](https://marmeon.com/docs/configuration.md) explains `.env`, `NODE_ENV` and each package's settings. - [Routing](https://marmeon.com/docs/routing.md) is where every feature starts: a URL, a controller and a page. - [Deployment](https://marmeon.com/docs/deployment.md) takes the app to a server: `marmeon build`, `marmeon start`, the worker and the scheduler. --- # Configuration ## Introduction A Marmeon app reads its settings from environment variables. The app, each of its modules and each installed package declare the variables they need as a config definition: a schema that checks the variables, and a function that turns them into a typed value. The app checks every definition when it starts, so a missing or wrong variable stops the start before anything runs. ```ts title="config/app.ts" import { defineConfig, env, type ConfigOf } from '@marmeon/core'; export const AppConfig = defineConfig('app', { env: env({ APP_NAME: env.string(), APP_URL: env.url(), }), resolve: (e) => ({ name: e.APP_NAME, url: e.APP_URL }), }); export type AppConfig = ConfigOf; ``` A definition is also a service. A class that asks for `AppConfig` in its constructor gets the resolved value, `{ name, url }`. ## The environment files The variables come from three places, and a later one wins over an earlier one: 1. `.env` in the app's root. 2. `.env.{NODE_ENV}` on top of it, for example `.env.test` while the tests run. 3. The real environment of the process: the shell, the container, the service manager. An empty value counts as unset, also in a later place: `AUTH_REVOKE_TOKENS_ON_PASSWORD_CHANGE=` in the process or in `.env.test` gives the variable's default, not the value an earlier file sets. Only `NODE_ENV` has its own rule, in [where `NODE_ENV` comes from](https://marmeon.com/docs/configuration.md#where-node_env-comes-from). A new app has three such files: | File | In git | What it holds | | --- | --- | --- | | `.env` | no | The settings of this machine, with its application key. Readable by its owner only. | | `.env.example` | yes | The common settings with a comment each, and no key. A colleague copies it to start. | | `.env.test` | yes | What the tests run with: a test key, sessions and cache in memory, a database in memory. | `.env.test` is committed, so put no real credentials in it. A new app's `.gitignore` lists `.env*`, then `!.env.example` and `!.env.test`, so every other file, such as `.env.production` or `.env.local`, stays out of git. Keep it that way: those files hold secrets. `marmeon key:generate` writes a fresh `APP_KEY` into `.env`. When there is no `.env` yet, it copies `.env.example` first and creates the file readable by its owner only. A `.env` that others could read is tightened to the same, and the command says so. `marmeon make:docker` warns when a `.env.production` exists and git does not ignore it. The app parses the files when it starts and leaves `process.env` as it is. The one exception is `NODE_ENV`, described below. So read a setting through a config definition, not through `process.env`: only the definition sees the values from `.env`. ## The environment: `NODE_ENV` Two variables describe where the app runs. `NODE_ENV` decides what the framework does, and it has exactly three values. `APP_ENV` is the name you give the environment: it is shown, and it selects the scheduled tasks that run. The app reads both through `EnvironmentConfig` of `@marmeon/core`, which every app has. `APP_ENV` is not part of your app's `config/app.ts`: the framework's own parts, such as the start line and the logs, read it too. `NODE_ENV` decides two things: whether the development tools run, and whether the protections apply. The two rules are not mirror images of each other: | `NODE_ENV` | Development tools | Protections | | --- | --- | --- | | `development` | on | off | | `test` | off | off | | `production`, or none | off | on | Any other value stops the start, before anything of the app runs: ```text ✗ [marmeon:K6] Invalid environment — the application cannot start: • NODE_ENV=staging is not an environment Node knows — set NODE_ENV=production and APP_ENV=staging. NODE_ENV is development, test or production; APP_ENV names the environment (docs/configuration.md#the-environment-node_env). ``` The development tools are Vite's dev server, the error page with the code that threw, the devtools, the `Server-Timing` header, the mail previews, readable logs and the table types that `migrate` writes. The protections are JSON logs, `migrate` asking for `--force` and the warnings at start-up. In addition, a write in a request that may only read is dropped and logged instead of thrown. The protections fail closed. A server where nobody set `NODE_ENV` is protected like production, because a forgotten variable must never show your source code to a visitor. There is no switch to turn this off: set `NODE_ENV=development` on your own machine, and nowhere else. ### `APP_ENV`: the environment's name `APP_ENV` names the environment: `local`, `staging`, `production` or a name of your own. Without it, the name follows `NODE_ENV`: | `NODE_ENV` | `APP_ENV` when it is not set | | --- | --- | | `development` | `local` | | `test` | `testing` | | `production`, or none | `production` | The name appears in the start line, as the `appEnv` field of every JSON log entry, as `deployment.environment.name` on every span the framework records, and in the header of the devtools. It also selects which scheduled tasks run: a task with `.environments('staging')` runs where `APP_ENV=staging`, and one with `.environments('production')` does not run there, as the [scheduling](https://marmeon.com/docs/scheduling.md#conditions) page shows. That is all it does. `APP_ENV` never weakens a protection and never enables a development tool: `APP_ENV=local` on a server with `NODE_ENV=production` is protected, and its development routes answer 404. ### Where `NODE_ENV` comes from The `marmeon` command decides `NODE_ENV` once, before it loads anything of the app: 1. The process's own `NODE_ENV` wins. 2. Otherwise the one in `.env`. A new app's `.env` says `development`, so the commands on your machine run in development — except `marmeon start`, which refuses a `development` or `test` that comes from `.env` alone. 3. Otherwise the command's own default: `marmeon start` and `marmeon build` use `production`, `marmeon dev` uses `development`. Every other command runs without one, which is production. Only the base `.env` can set it. A `.env.production` is chosen by `NODE_ENV=production`, so it cannot choose it: a `NODE_ENV` line in it is ignored, with a warning. The value is written into `process.env.NODE_ENV`, so every part of the app reads the same one. `APP_ENV` is read the same way as any other variable: the real environment, then `.env.{NODE_ENV}`, then `.env`. `marmeon build` builds the browser code for production unless the environment itself says `NODE_ENV=development`. A `development` from `.env` belongs to the commands of your machine, so the build sets it aside and says so; `test` builds for production as well. The start line says where the value came from, for example `development (APP_ENV=local, NODE_ENV from .env)`. A `.env` copied to a server would turn the development tools on there, so `marmeon start` refuses it: with `NODE_ENV=development` or `NODE_ENV=test` from `.env` alone it prints `marmeon start runs in production`, loads nothing of the app and exits with 1. Run `marmeon dev`, set `NODE_ENV=production` to try the build, or set `NODE_ENV=development` in the real environment to start the development stack on purpose. `queue:work` and `schedule:work` still run in that case, but each logs a loud warning that begins with `NODE_ENV=development comes from .env, not from the environment`. On a server, set `NODE_ENV` in the real environment. ### Staging A staging server runs as production and says so in its name: ```sh NODE_ENV=production APP_ENV=staging marmeon start ``` It gets every protection and the production builds of the framework and of React, so a server error reaches the visitor as a plain error page, never with its message or stack. The start line reads `production (APP_ENV=staging)`, and its logs and traces carry the name. The [deployment](https://marmeon.com/docs/deployment.md#staging) page shows the image and the variables. ### Asking for the environment in code `environment` from `@marmeon/core` answers the questions of the tables above. Ask `isProtected()` where your code protects something, and `isDevelopment()` where it offers a development tool. Never compare `NODE_ENV` with `'production'`: that would treat a missing value as development. Never ask `APP_ENV` whether to protect something either: it is a name, not a switch. ```ts title="config/demo.ts" import { defineConfig, env, environment, type ConfigOf } from '@marmeon/core'; export const DemoConfig = defineConfig('demo', { env: env({ NODE_ENV: env.string().optional(), DEMO_DELAY_MS: env.integer().min(0).max(10_000).default(0), }), // A delay to watch a slow page load — never where the app is protected. resolve: (e) => ({ delayMs: environment.isProtected(e) ? 0 : e.DEMO_DELAY_MS }), }); export type DemoConfig = ConfigOf; ``` Inside `resolve`, pass its argument on: it is the environment the definition was checked against, which a test may set itself. Outside a definition, the functions read `process.env`. `environment.isTest()`, `environment.name()`, `environment.app()` and `environment.describe()` complete the set. `describe()` returns what the start line shows, such as `production (APP_ENV=staging)`. To show the environment's name, ask for `EnvironmentConfig`. Every app has it, and it reads `NODE_ENV` and `APP_ENV` like any other variable, so an `APP_ENV` in `.env` counts too: ```ts title="modules/system/controllers/ShowStatusController.ts" import { EnvironmentConfig } from '@marmeon/core'; export class ShowStatusController { readonly #environment: EnvironmentConfig; constructor(environment: EnvironmentConfig) { this.#environment = environment; } handle() { // { node: 'production', app: 'staging' } on a staging server return { environment: this.#environment.app }; } } ``` Code that also runs in the browser cannot import `environment`. It checks the value inline, and positively: `process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'`. The client build replaces the expression with the value `marmeon build` ran under, and server rendering reads it when it runs. ## Defining configuration ### Reading variables `env({ … })` from `@marmeon/core` is the schema of a definition. Its keys are the variables, and each one gets a building block that reads the variable's text: `env.integer()` makes `'25'` the number 25, `env.boolean()` makes `'true'` the value `true`. A default goes into the block, and `resolve` turns the values into the shape your code wants: ```ts title="modules/notes/config.ts" import { defineConfig, env, type ConfigOf } from '@marmeon/core'; export const NotesConfig = defineConfig('notes', { env: env({ NOTES_PER_PAGE: env.integer().min(5).max(100).default(25), NOTES_SHARING: env.boolean().default(false), NOTES_EDITORS: env.list(env.email()).default([]), NOTES_EXPORT_URL: env.url({ protocols: ['https'] }).optional(), }), resolve: (e) => ({ perPage: e.NOTES_PER_PAGE, sharing: e.NOTES_SHARING, editors: e.NOTES_EDITORS, exportUrl: e.NOTES_EXPORT_URL }), }); export type NotesConfig = ConfigOf; ``` `NOTES_EDITORS=ada@example.com, alan@example.com` becomes a list of two addresses, and each one is checked. `ConfigOf` is the type that `resolve` returns, and `resolve` sees each variable with its type: `NOTES_PER_PAGE` is a `number`, `NOTES_EXPORT_URL` a `string | undefined`. These are the building blocks: | Block | Reads | Narrowed by | | --- | --- | --- | | `env.string()` | Any text. | `.min(n)` and `.max(n)` characters, `.regex(pattern, message?)` | | `env.integer()` | A whole number, written in decimal: `25`, `-1`. | `.min(n)`, `.max(n)` | | `env.number()` | A number, decimals too: `0.5`. | `.min(n)`, `.max(n)` | | `env.boolean()` | `true` or `false`, `1` or `0`, in any case. Any other text is an error, not `false`. | | | `env.in(['sqlite', 'pgsql'])` | One of the values, case-sensitive. Its type is their union, `'sqlite' \| 'pgsql'`. | | | `env.url()` | An absolute URL with `//`: `http://` or `https://`. `env.url({ protocols: ['redis', 'rediss'] })` takes others. | | | `env.port()` | A port from 1 to 65535. | | | `env.email()` | An e-mail address. | | | `env.list(block)` | A list split at commas, each entry trimmed and read by `block`. Empty entries are dropped. `env.list(block, { separator: ';' })` splits at another character. | | Every block ends in one of three ways, which decide what a missing variable means: | Ending | A missing variable | | --- | --- | | none | Stops the start: `NOTES_TOKEN is required.` | | `.default(value)` | Is `value`. The default has the block's type: `env.integer().default(25)`, not `'25'`. | | `.optional()` | Is `undefined`. | An empty variable, such as `NOTES_PER_PAGE=`, counts as missing, for every block: a `.env` file has no other way to say "not set". So `NOTES_PER_PAGE=` gives the default 25, and an empty required variable stops the start like a missing one. `.default()` and `.optional()` come last. `env.integer().default(25).min(5)` is a compile error, and so is a default of the wrong type, a `.min()` on a boolean, and a variable that `resolve` reads but `env({ … })` does not declare. ### Messages of your own A block's own message names the variable and what it expects, such as `NOTES_PER_PAGE must be at least 5.` It never repeats the value, because a variable may hold a secret. Each block and each narrowing takes a message of its own as its last argument, and `.check()` adds a rule of your own. `.required(message)` says what to do about a missing variable: ```ts title="modules/billing/config.ts" import { defineConfig, env, type ConfigOf } from '@marmeon/core'; const isTaxRate = (rate: number) => [0, 7, 19].includes(rate); export const BillingConfig = defineConfig('billing', { env: env({ BILLING_API_KEY: env.string().required('Missing — create a key in the billing dashboard'), BILLING_TAX_RATE: env.integer().check(isTaxRate, 'Expected 0, 7 or 19').default(19), BILLING_COUNTRIES: env.list(env.string().regex(/^[A-Z]{2}$/, 'Expected country codes like DE,AT')).default(['DE']), BILLING_DEFAULT_COUNTRY: env.string().default('DE'), }).check((e) => e.BILLING_COUNTRIES.includes(e.BILLING_DEFAULT_COUNTRY), 'BILLING_DEFAULT_COUNTRY must be one of BILLING_COUNTRIES', 'BILLING_DEFAULT_COUNTRY'), resolve: (e) => ({ apiKey: e.BILLING_API_KEY, taxRate: e.BILLING_TAX_RATE, countries: e.BILLING_COUNTRIES, defaultCountry: e.BILLING_DEFAULT_COUNTRY }), }); export type BillingConfig = ConfigOf; ``` `.check()` on `env({ … })` relates variables to each other. It runs once every variable was read without a problem, and its message belongs to the variable its third argument names. The schema can also come from any library that implements Standard Schema, such as Zod or Valibot. Then the library decides how an empty variable is read. ### Renamed variables When a variable gets a new name, an app that still sets the old one would silently run on the default of the new one: a page size, a session lifetime or a list of trusted proxies that is suddenly not what the deployment says. `.renamed(from, to)` retires the old name instead. A start with the old name set (and not empty) stops with a problem that names the new one, in every environment and even when the new name is set as well. The old value is never read: ```ts title="modules/notes/config.ts" export const NotesConfig = defineConfig('notes', { env: env({ NOTES_PER_PAGE: env.integer().min(5).default(20), }).renamed('NOTES_PAGE_SIZE', 'NOTES_PER_PAGE'), resolve: (e) => ({ perPage: e.NOTES_PER_PAGE }), }); ``` `renamed()` throws when a name is not in upper case, when both names are the same, when the new name is not a variable of the schema, when the old one is, and when the old one is retired already. The option `{ conversion }` replaces the "same value" advice in the problem, for a rename that changes the unit; it cannot be empty. Reading both names would leave it open which one wins when a deployment sets both, so the old one only stops the start. Leave the `.renamed()` call in place: without it, the old name falls back to the default again, silently. The "How to fix it" hint of the start ("Set … in .env") lists only the variables that are missing or invalid; a retired name is never in it, and when the problem is only a retired name there is no such hint, because the problem already says what to rename. ### Where a definition is listed A definition counts once it is listed, and it is checked once, however often it is listed: | Where | For | | --- | --- | | `defineApplication({ config: [AppConfig] })` in `bootstrap/app.ts` | The app's own settings. | | `defineModule({ config: [NotesConfig] })` in a module's `index.ts` | A module's settings. See [modules](https://marmeon.com/docs/modules.md#defining-a-module). | | `static config = [LogConfig]` on a service provider | A package's settings. See [service providers](https://marmeon.com/docs/providers.md#what-a-provider-brings-besides-code). | A definition is listed, not found by scanning `config/`, for these reasons: - **The definition is already imported.** It is the type and the token the container resolves (`defineConfig()` makes a unique key for it), so any code that reads the configuration imports it anyway. Listing it is one more entry in an array. - **Not every file in `config/` is a definition.** A file there may be loaded only in some environments, such as the devtools' settings, which must never load in production. A scan would load it. - **A module brings its own.** Its definitions sit in the module's folder, and the module lists them, so removing the module removes its settings too. ### Using configuration Ask for the definition in a constructor, like any other service: ```ts title="modules/notes/controllers/ListNotesController.ts" import { Controller } from '@marmeon/http'; import { NotesConfig } from '../config.ts'; export class ListNotesController extends Controller { readonly #config: NotesConfig; constructor(config: NotesConfig) { super(); this.#config = config; } handle() { return this.view('notes/Index', { perPage: this.#config.perPage }); } } ``` Import the definition as a value, not with `import type`. Its name is both the type and the token the container resolves, and a type-only import does not exist when the app runs. The [service container](https://marmeon.com/docs/container.md#constructor-injection) page explains why. ## Values for the browser A page reaches configuration through the server. Read the value from a definition in a controller and pass it as a page prop, or share it with every page through [`SharedData`](https://marmeon.com/docs/responses.md#shared-props): ```ts title="middleware/ShareAppProps.ts" declare module '@marmeon/http/page' { interface SharedProps { app?: { name: string; mapsKey: string }; } } // In handle(), with a config definition injected next to SharedData: this.#shared.share('app', { name: this.#config.name, mapsKey: this.#config.mapsKey }); ``` A component reads it with `usePage().props`, typed by `interface SharedProps`. Only a value that is safe to publish belongs there, such as the app's name or a public key. A secret stays out, because everything shared is sent to the browser. Values take this route for two reasons. The server reads the configuration when it starts, so one build runs unchanged in every environment, and `marmeon build` needs no `.env`. And nothing reaches the browser unless code hands it over, so a variable is never published by being in the environment. The [Vite page](https://marmeon.com/docs/vite.md#server-code-in-the-browser) explains the same rule for imports. Vite's own `VITE_*` variables are switched off: `marmeon()` reads no `.env` file and publishes no variable through `import.meta.env`, so an environment variable never reaches the bundle by its name. A value fixed at build time would differ between the dev server and the build, and would bypass the validation of a definition. An app that needs them anyway sets `marmeon({ viteEnv: true })`; see [Environment variables](https://marmeon.com/docs/vite.md#environment-variables). ## When a value is wrong The app checks every definition before any provider registers, and collects every problem before it stops. One start shows everything to fix: ```text [marmeon:K6] Invalid configuration — the application cannot start: • notes: NOTES_PER_PAGE — NOTES_PER_PAGE must be at most 100. • notes: NOTES_EDITORS — NOTES_EDITORS entry 2 must be an e-mail address. • encryption: APP_KEY — Missing — run "marmeon key:generate" Set or rename these variables in the environment or in .env (see .env.example). ``` Each line names the definition, the variable as it is written, and the problem. A variable has one line, however much is wrong with it. The `marmeon` command prints how to fix it below the error, such as the command that generates a key. ## Configuration and the build `marmeon build` needs no `.env` and no key. It loads the app to write the route types, registers every service provider and boots none of them. A definition that does not validate without `.env`, such as the one that needs `APP_KEY`, is left out instead of failing the build. So no secret can end up in what the build writes. Reading such a definition while the build runs throws an error that names its variables. Read configuration in a provider's `boot()`, in a request, a job or a command, never in a provider's `register()`. The [service providers](https://marmeon.com/docs/providers.md#register-and-boot) page explains the two phases. Nothing of the configuration is cached. Every start reads the environment and `.env` again, so a changed variable needs a restart, not a new build. ## The variables of a new app These are the settings a new app starts with. Each feature's page lists its own variables. | Variable | Default | Effect | | --- | --- | --- | | `NODE_ENV` | the command's | `development`, `test` or `production`; any other value stops the start. `development` turns the development tools on; `production` and none are protected. | | `APP_ENV` | `local`, `testing` or `production`, by `NODE_ENV` | The environment's name in the start line, the logs and the traces, and what `.environments()` of a scheduled task compares against. It never weakens a protection or enables a development tool. | | `APP_NAME` | none, required | The app's name. The starter kit shows it on its pages and in its mails. | | `APP_URL` | none, required | The app's address. `https://` makes the cookies `Secure`, unless `SESSION_SECURE_COOKIE` says otherwise. | | `APP_KEY` | none, required | The key that encrypts cookies and signs URLs: `base64:` and 32 random bytes. | | `APP_PREVIOUS_KEYS` | empty | Former keys, comma-separated. What they encrypted or signed stays valid. | | `APP_SHUTDOWN_TIMEOUT_SECONDS` | `10` | Seconds each provider's `shutdown()` may take before the app logs a warning about it and goes on with the next provider. | | `PORT` | `3000` | The port the server listens on. `0` takes a free one. | | `HOST` | `127.0.0.1` | The interface the server listens on. `0.0.0.0` for other machines. | | `LOG_LEVEL` | `info` | The lowest level that is logged, or `silent`. | | `DB_DRIVER` | `sqlite` | `sqlite` or `pgsql`. | | `DB_DATABASE` | `storage/database.sqlite` | The SQLite file, or the name of the Postgres database, which has no default: set it or `DB_URL`, or the start fails. | | `DB_HOST` | `127.0.0.1` | Postgres: the server. | | `DB_PORT` | `5432` | Postgres: its port. | | `DB_USERNAME` | `postgres` | Postgres: the user. | | `DB_PASSWORD` | empty | Postgres: the password. | | `DB_URL` | none | Postgres: the whole address instead. When it is set, `DB_HOST`, `DB_PORT`, `DB_DATABASE`, `DB_USERNAME` and `DB_PASSWORD` are not read. | | `SESSION_DRIVER` | `file` | Where sessions live: `file`, `database`, `redis` or `memory`. | | `CACHE_DRIVER` | `file` | Where the cache lives: `file`, `database`, `redis`, `memory` or a driver a package brings. | | `QUEUE_DRIVER` | `database` | Where queued jobs wait: `database`, `redis`, `sync` or a driver a package brings. | | `LIVE_DRIVER` | `memory`; `database` in a new app's `.env.example` | How live hints travel: `memory` within one process, `database` through the `live_hints` table (every process of a machine, or of a shared Postgres), `redis` to every process. | | `MAIL_DRIVER` | `log` | Where mails go: `log` writes every mail to the log, `smtp` sends it, `array` keeps it in memory, or a transport a package brings. | ## Every variable Every variable the framework's packages read, from the `Environment` sections of their API snapshots. The list is frozen: a variable is renamed with `.renamed()` ([Renamed variables](https://marmeon.com/docs/configuration.md#renamed-variables)) and never given a retired name again, and a test holds this table to the code. A feature's page explains its variables; the last column links it. The names follow a few rules: - A variable starts with the prefix of its area (`APP_`, `AUTH_`, `HASH_`, `CACHE_`, `CHAT_`, `CSRF_`, `DB_`, `DEVTOOLS_`, `FETCH_`, `LIVE_`, `LOG_`, `MAIL_`, `NOTIFICATIONS_`, `OAUTH_`, `QUEUE_`, `REDIS_`, `SCHEDULE_`, `SERVER_`, `SESSION_`, `UPLOADS_`, `MARMEON_OTEL_`). Only `NODE_ENV`, `PORT` and `HOST` have none, because platforms set them, and the names of the OpenTelemetry specification stay as it writes them. - `_DRIVER` picks the driver. `_CONNECTION` names a connection of the database or of Redis, and nothing else. - A duration says its unit: `_MILLISECONDS`, `_SECONDS`, `_MINUTES`, `_HOURS` or `_DAYS`. A rate ends in `_PER_MINUTE` or `_PER_DAY`. - A size is a whole number and says its unit: `_KB` or `_MB` (1,024-based). `_SIZE`, `_MEMORY` and `_BYTES` are not units. - A switch is read as a boolean: `true`, `false`, `1` or `0`, in any case, and anything else stops the start. `OTEL_SDK_DISABLED` is the one exception: it follows the OpenTelemetry specification, where only `true`, in any case, disables the SDK. Any other value, `1` included, leaves spans on and logs a warning ([Observability](https://marmeon.com/docs/observability.md#configuration)). - A rename keeps the unit, the default and the limits, so an app renames a key and never converts a value. The one exception: when the old name had no unit, the new name's unit may differ, and the stop message for the old name says the conversion. The Kind column says which rule a variable falls under: `driver`, `connection`, `switch`, `duration`, `size` or `value` for the rest. | Variable | Package | Kind | Default | Page | | --- | --- | --- | --- | --- | | `APP_ENV` | core, devtools, log, scheduler | value | optional | [Configuration](https://marmeon.com/docs/configuration.md#the-environment-node_env) | | `APP_FALLBACK_LOCALE` | i18n | value | `"en"` | [Localization](https://marmeon.com/docs/localization.md#configuration) | | `APP_KEY` | encryption | value | required | [Encryption](https://marmeon.com/docs/encryption.md#the-application-key) | | `APP_LOCALE` | i18n | value | `"en"` | [Localization](https://marmeon.com/docs/localization.md#configuration) | | `APP_LOCALES` | i18n | value | `[]` | [Localization](https://marmeon.com/docs/localization.md#configuration) | | `APP_LOCALE_PREFIX` | i18n | switch | `true` | [Localization](https://marmeon.com/docs/localization.md#configuration) | | `APP_NAME` | auth, redis | value | optional | [Configuration](https://marmeon.com/docs/configuration.md#the-variables-of-a-new-app) | | `APP_PREVIOUS_KEYS` | encryption | value | `[]` | [Encryption](https://marmeon.com/docs/encryption.md#the-application-key) | | `APP_SHUTDOWN_TIMEOUT_SECONDS` | core | duration | `10` | [Providers](https://marmeon.com/docs/providers.md#shutting-down) | | `APP_TIMEZONE` | i18n | value | optional | [Localization](https://marmeon.com/docs/localization.md#configuration) | | `APP_URL` | auth, devtools, mail, oauth, server, session | value | optional | [Configuration](https://marmeon.com/docs/configuration.md#the-variables-of-a-new-app) | | `AUTH_ACCOUNT_SIGN_INS_PER_DAY` | auth | value | `100` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_DEVICE_COOKIE_DAYS` | auth | duration | `90` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_EMAIL_CHANGE_MINUTES` | auth | duration | `60` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_EMAIL_CHANGE_THROTTLE_SECONDS` | auth | duration | `60` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_LOGIN_ATTEMPTS_PER_MINUTE` | auth | value | `5` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_PASSKEY_ORIGINS` | auth | value | optional | [Passkeys](https://marmeon.com/docs/passkeys.md#requirements) | | `AUTH_PASSKEY_RP_ID` | auth | value | optional | [Passkeys](https://marmeon.com/docs/passkeys.md#requirements) | | `AUTH_PASSWORD_TIMEOUT_SECONDS` | auth | duration | `900` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_PRIVATE_REGISTRATION` | auth | switch | `true` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_REMEMBER_COOKIE` | auth | value | `"marmeon_remember"` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_REMEMBER_DAYS` | auth | duration | `30` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_RESET_MINUTES` | auth | duration | `60` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_RESET_THROTTLE_SECONDS` | auth | duration | `60` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_REVOKE_TOKENS_ON_PASSWORD_CHANGE` | auth | switch | `false` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_SESSION_MAX_HOURS` | auth | duration | `24` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `AUTH_TOKEN_PREFIX` | auth | value | `"marmeon_"` | [API Tokens](https://marmeon.com/docs/api-tokens.md#the-token-format) | | `AUTH_UNVERIFIED_DAYS` | auth | duration | `7` | [Authentication](https://marmeon.com/docs/authentication.md#configuration) | | `CACHE_CONNECTION` | cache | connection | `"default"` | [Cache](https://marmeon.com/docs/cache.md#configuration) | | `CACHE_DRIVER` | cache | driver | `"file"` | [Cache](https://marmeon.com/docs/cache.md#configuration) | | `CACHE_PATH` | cache | value | `"storage/framework/cache"` | [Cache](https://marmeon.com/docs/cache.md#configuration) | | `CACHE_PREFIX` | cache | value | `""` | [Cache](https://marmeon.com/docs/cache.md#configuration) | | `CHAT_DRIVER` | chat-notifications | driver | `"log"` | [Chat Notifications](https://marmeon.com/docs/chat-notifications.md#configuration) | | `CHAT_WEBHOOKS` | chat-notifications | value | `""` | [Chat Notifications](https://marmeon.com/docs/chat-notifications.md#configuration) | | `CSRF_TRUSTED_ORIGINS` | session | value | `[]` | [CSRF Protection](https://marmeon.com/docs/csrf.md#configuration) | | `DB_DATABASE` | database | value | optional | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DB_DRIVER` | database | driver | `"sqlite"` | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DB_HOST` | database | value | `"127.0.0.1"` | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DB_INFRA_POOL_MAX` | database | value | `4` | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DB_MANAGED` | database | switch | `true` | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DB_PASSWORD` | database | value | `""` | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DB_POOL_MAX` | database | value | `10` | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DB_PORT` | database | value | `5432` | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DB_URL` | database | value | optional | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DB_USERNAME` | database | value | `"postgres"` | [Database: Getting Started](https://marmeon.com/docs/database.md#configuration) | | `DEVTOOLS_ENABLED` | devtools | switch | optional | [Devtools](https://marmeon.com/docs/devtools.md#only-in-development) | | `FETCH_ALLOWED_ADDRESSES` | fetch | value | `""` | [HTTP Client](https://marmeon.com/docs/http-client.md#configuration) | | `FETCH_DRIVER` | fetch | driver | `"direct"` | [HTTP Client](https://marmeon.com/docs/http-client.md#configuration) | | `HASH_ARGON_MEMORY_KB` | auth | size | `19456` | [Hashing](https://marmeon.com/docs/hashing.md#configuration) | | `HASH_ARGON_PARALLELISM` | auth | value | `1` | [Hashing](https://marmeon.com/docs/hashing.md#configuration) | | `HASH_ARGON_TIME` | auth | value | `2` | [Hashing](https://marmeon.com/docs/hashing.md#configuration) | | `HASH_DRIVER` | auth | driver | `"argon2id"` | [Hashing](https://marmeon.com/docs/hashing.md#configuration) | | `HASH_SCRYPT_BLOCK_SIZE` | auth | value | `8` | [Hashing](https://marmeon.com/docs/hashing.md#configuration) | | `HASH_SCRYPT_COST` | auth | value | `17` | [Hashing](https://marmeon.com/docs/hashing.md#configuration) | | `HASH_SCRYPT_PARALLELISM` | auth | value | `1` | [Hashing](https://marmeon.com/docs/hashing.md#configuration) | | `HOST` | server | value | `"127.0.0.1"` | [Configuration](https://marmeon.com/docs/configuration.md#the-variables-of-a-new-app) | | `LIVE_CONNECTION` | live | connection | `"default"` | [Real-time Updates](https://marmeon.com/docs/realtime.md#configuration) | | `LIVE_DRIVER` | live | driver | `"memory"` | [Real-time Updates](https://marmeon.com/docs/realtime.md#configuration) | | `LIVE_HEARTBEAT_SECONDS` | live | duration | `20` | [Real-time Updates](https://marmeon.com/docs/realtime.md#configuration) | | `LIVE_MAX_CHANNELS` | live | value | `20` | [Real-time Updates](https://marmeon.com/docs/realtime.md#configuration) | | `LIVE_MAX_STREAMS` | live | value | `1000` | [Real-time Updates](https://marmeon.com/docs/realtime.md#configuration) | | `LIVE_MAX_STREAMS_PER_SESSION` | live | value | `16` | [Real-time Updates](https://marmeon.com/docs/realtime.md#configuration) | | `LIVE_MAX_STREAM_SECONDS` | live | duration | `900` | [Real-time Updates](https://marmeon.com/docs/realtime.md#configuration) | | `LIVE_POLL_MILLISECONDS` | live | duration | `500` | [Real-time Updates](https://marmeon.com/docs/realtime.md#configuration) | | `LIVE_RETRY_MILLISECONDS` | live | duration | `3000` | [Real-time Updates](https://marmeon.com/docs/realtime.md#configuration) | | `LOG_FORMAT` | log | value | optional | [Logging](https://marmeon.com/docs/logging.md#configuration) | | `LOG_LEVEL` | log | value | `"info"` | [Logging](https://marmeon.com/docs/logging.md#configuration) | | `MAIL_DRIVER` | mail | driver | `"log"` | [Mail](https://marmeon.com/docs/mail.md#configuration) | | `MAIL_FROM_ADDRESS` | mail | value | optional | [Mail](https://marmeon.com/docs/mail.md#configuration) | | `MAIL_FROM_NAME` | mail | value | `""` | [Mail](https://marmeon.com/docs/mail.md#configuration) | | `MAIL_HOST` | mail | value | `"127.0.0.1"` | [Mail](https://marmeon.com/docs/mail.md#configuration) | | `MAIL_PASSWORD` | mail | value | `""` | [Mail](https://marmeon.com/docs/mail.md#configuration) | | `MAIL_PORT` | mail | value | `587` | [Mail](https://marmeon.com/docs/mail.md#configuration) | | `MAIL_REQUIRE_TLS` | mail | switch | `true` | [Mail](https://marmeon.com/docs/mail.md#configuration) | | `MAIL_SECURE` | mail | switch | `false` | [Mail](https://marmeon.com/docs/mail.md#configuration) | | `MAIL_USERNAME` | mail | value | `""` | [Mail](https://marmeon.com/docs/mail.md#configuration) | | `MARMEON_OTEL_RECORD_QUERY_VALUES` | otel | switch | `false` | [Observability](https://marmeon.com/docs/observability.md#configuration) | | `MARMEON_OTEL_TRUST_TRACEPARENT` | otel | switch | `false` | [Observability](https://marmeon.com/docs/observability.md#configuration) | | `NODE_ENV` | chat-notifications, core, devtools, encryption, log, mail, scheduler, server, session | value | optional | [Configuration](https://marmeon.com/docs/configuration.md#the-environment-node_env) | | `NOTIFICATIONS_CONNECTION` | notifications | connection | `"default"` | [Notifications](https://marmeon.com/docs/notifications.md#the-notifications-table) | | `OAUTH_DISCORD_CLIENT_ID` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_DISCORD_CLIENT_SECRET` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_DISCORD_REDIRECT_URL` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_DISCORD_SCOPES` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GITHUB_CLIENT_ID` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GITHUB_CLIENT_SECRET` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GITHUB_REDIRECT_URL` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GITHUB_SCOPES` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GITLAB_CLIENT_ID` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GITLAB_CLIENT_SECRET` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GITLAB_ISSUER` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GITLAB_REDIRECT_URL` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GITLAB_SCOPES` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GOOGLE_CLIENT_ID` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GOOGLE_CLIENT_SECRET` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GOOGLE_REDIRECT_URL` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_GOOGLE_SCOPES` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_MICROSOFT_CLIENT_ID` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_MICROSOFT_CLIENT_SECRET` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_MICROSOFT_REDIRECT_URL` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_MICROSOFT_SCOPES` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_MICROSOFT_TENANT` | oauth | value | optional | [Social login](https://marmeon.com/docs/oauth.md#configuring-a-provider) | | `OAUTH_REGISTRATION` | oauth | switch | `true` | [Social login](https://marmeon.com/docs/oauth.md#signing-users-in) | | `OAUTH_STORE_TOKENS` | oauth | switch | `false` | [Social login](https://marmeon.com/docs/oauth.md#storing-tokens) | | `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST` | otel | value | `[]` | [Observability](https://marmeon.com/docs/observability.md#redaction) | | `OTEL_SDK_DISABLED` | otel | switch | `"false"` | [Observability](https://marmeon.com/docs/observability.md#configuration) | | `PORT` | server | value | `3000` | [Configuration](https://marmeon.com/docs/configuration.md#the-variables-of-a-new-app) | | `QUEUE_DATABASE_CONNECTION` | queue | connection | `"default"` | [Queues](https://marmeon.com/docs/queues.md#configuration) | | `QUEUE_DATABASE_QUEUE` | queue | value | `"default"` | [Queues](https://marmeon.com/docs/queues.md#configuration) | | `QUEUE_DATABASE_RETRY_AFTER_SECONDS` | queue | duration | `90` | [Queues](https://marmeon.com/docs/queues.md#configuration) | | `QUEUE_DRIVER` | queue | driver | `"database"` | [Queues](https://marmeon.com/docs/queues.md#configuration) | | `QUEUE_FAILED_CONNECTION` | queue | connection | optional | [Queues](https://marmeon.com/docs/queues.md#configuration) | | `QUEUE_FAILED_DRIVER` | queue | driver | `"database"` | [Queues](https://marmeon.com/docs/queues.md#configuration) | | `QUEUE_REDIS_CONNECTION` | queue | connection | `"default"` | [Queues](https://marmeon.com/docs/queues.md#configuration) | | `QUEUE_REDIS_QUEUE` | queue | value | `"default"` | [Queues](https://marmeon.com/docs/queues.md#configuration) | | `QUEUE_REDIS_RETRY_AFTER_SECONDS` | queue | duration | `90` | [Queues](https://marmeon.com/docs/queues.md#configuration) | | `REDIS_PREFIX` | redis | value | optional | [Redis](https://marmeon.com/docs/redis.md#configuration) | | `REDIS_URL` | redis | value | `"redis://127.0.0.1:6379"` | [Redis](https://marmeon.com/docs/redis.md#configuration) | | `SCHEDULE_TIMEZONE` | scheduler | value | `"UTC"` | [Task Scheduling](https://marmeon.com/docs/scheduling.md#configuration) | | `SERVER_ASSET_VERSION` | server | value | optional | [Deployment](https://marmeon.com/docs/deployment.md#configuration) | | `SERVER_HEALTH_PATH` | server | value | `"/up"` | [Deployment](https://marmeon.com/docs/deployment.md#health-checks) | | `SERVER_KEEP_ALIVE_TIMEOUT_SECONDS` | server | duration | `65` | [Deployment](https://marmeon.com/docs/deployment.md#configuration) | | `SERVER_MAX_BODY_MB` | server | size | `8` | [Requests](https://marmeon.com/docs/requests.md#configuration) | | `SERVER_SHUTDOWN_DELAY_SECONDS` | server | duration | `0` | [Deployment](https://marmeon.com/docs/deployment.md#configuration) | | `SERVER_SSR_ENABLED` | server | switch | `true` | [Pages & Layouts](https://marmeon.com/docs/pages.md#server-rendering) | | `SERVER_TRUSTED_PROXIES` | server | value | `[]` | [Deployment](https://marmeon.com/docs/deployment.md#configuration) | | `SESSION_CONNECTION` | session | connection | `"default"` | [Session](https://marmeon.com/docs/session.md#configuration) | | `SESSION_COOKIE` | session | value | `"marmeon_session"` | [Session](https://marmeon.com/docs/session.md#configuration) | | `SESSION_DRIVER` | session | driver | `"file"` | [Session](https://marmeon.com/docs/session.md#configuration) | | `SESSION_ENCRYPT` | session | switch | `false` | [Session](https://marmeon.com/docs/session.md#configuration) | | `SESSION_FILES` | session | value | `"storage/framework/sessions"` | [Session](https://marmeon.com/docs/session.md#configuration) | | `SESSION_LIFETIME_MINUTES` | session | duration | `120` | [Session](https://marmeon.com/docs/session.md#configuration) | | `SESSION_LOTTERY` | session | value | `"2/100"` | [Session](https://marmeon.com/docs/session.md#configuration) | | `SESSION_SAME_SITE` | session | value | `"lax"` | [Session](https://marmeon.com/docs/session.md#configuration) | | `SESSION_SECURE_COOKIE` | session | switch | optional | [Session](https://marmeon.com/docs/session.md#configuration) | | `UPLOADS_CONNECTION` | storage | connection | `"default"` | [File Storage](https://marmeon.com/docs/storage.md#configuration) | | `UPLOADS_DISK` | storage | value | `"uploads"` | [File Storage](https://marmeon.com/docs/storage.md#configuration) | | `UPLOADS_LIFETIME_MINUTES` | storage | duration | `120` | [File Storage](https://marmeon.com/docs/storage.md#configuration) | | `UPLOADS_MAX_OPEN` | storage | value | `20` | [File Storage](https://marmeon.com/docs/storage.md#configuration) | | `UPLOADS_MAX_OPEN_MB` | storage | size | `1024` | [File Storage](https://marmeon.com/docs/storage.md#configuration) | | `UPLOADS_MAX_OPEN_TOTAL_MB` | storage | size | `10240` | [File Storage](https://marmeon.com/docs/storage.md#configuration) | | `UPLOADS_SEND_WITHIN_MINUTES` | storage | duration | `15` | [File Storage](https://marmeon.com/docs/storage.md#configuration) | ## Testing Under Vitest, `NODE_ENV` is `test`, so `.env.test` applies on top of `.env`. A test changes single variables for its own app instance: ```ts title="modules/notes/notes.test.ts" import { createTestApp } from '@marmeon/testing'; import { expect, it } from 'vitest'; import application from '../../bootstrap/app.ts'; import { NotesConfig } from './config.ts'; it('reads NOTES_SHARING', async () => { await using app = await createTestApp(application, { env: { NOTES_SHARING: 'true' } }); expect(app.container.make(NotesConfig).sharing).toBe(true); }); ``` The [testing](https://marmeon.com/docs/testing.md#creating-the-test-app) page explains how a test boots the app. --- # Directory Structure ## Introduction A Marmeon app is a set of modules. Each feature lives in one folder under `modules/`, with its routes, controllers, pages, migrations and tests side by side. Around the modules sit a few folders that hold the app together. This is a new app with the starter kit, as `pnpm create marmeon my-app` writes it: ```text my-app/ ├── bootstrap/ the app's definition, its browser and server entries, generated types ├── config/ the app's own settings ├── lang/ texts the whole app shares ├── layouts/ the app's own components, such as its confirm dialog ├── modules/ │ ├── auth/ sign-in, registration, password reset, API tokens │ ├── home/ the home page │ └── system/ the tables of the queue, notifications, live updates ├── storage/ what the app writes while it runs ├── index.html the document every page renders into ├── .env this machine's settings, never committed ├── .env.example ├── .env.test ├── AGENTS.md the guide for coding agents; CLAUDE.md imports it ├── package.json ├── tsconfig.json ├── vite.config.ts ├── vitest.config.ts └── .oxlintrc.json ``` A blank app from `pnpm create marmeon my-app --minimal` has the same skeleton without `lang/`, `layouts/`, `modules/auth/` and `modules/home/`. This page walks through each part, then through your first module. ## The root directory ### `bootstrap/` `bootstrap/` connects the parts. You edit the first file often, the others rarely: | File | What it does | | --- | --- | | `app.ts` | Describes the app: its modules, its configuration and its global middleware. Every command and every test loads it. | | `client.tsx` | The browser's entry. It reads the page from the document and hydrates it. | | `ssr.tsx` | The server's entry for rendering pages. | | `pages.ts` | Finds the page components under `modules/*/views/`, one code-split chunk per page. | | `head.ts` | The document title, shared by both entries. | | `i18n.ts` | Loads the language files for the page's locale, in the browser and on the server. | | `routes.ts` | Generated: every named route and every view, for the type checker. Commit it. | | `database.d.ts` | Generated: the types of the database tables. Commit it. | `bootstrap/app.ts` only describes the app. It boots nothing itself. The `marmeon` command boots it for a command or the server, and each test boots a fresh instance: ```ts title="bootstrap/app.ts" import { join } from 'node:path'; import { defineApplication } from '@marmeon/core'; import { contentSecurityPolicy, securityHeaders } from '@marmeon/http'; import auth from '#modules/auth'; import home from '#modules/home'; import system from '#modules/system'; import { AppConfig } from '../config/app.ts'; export default defineApplication({ root: join(import.meta.dirname, '..'), config: [AppConfig], modules: [auth, home, system], middleware: { global: [securityHeaders(), contentSecurityPolicy()], }, }); ``` The [modules](https://marmeon.com/docs/modules.md#the-application) page lists every option of `defineApplication()`. ### `config/` `config/app.ts` holds the app's own settings: `APP_NAME` and `APP_URL`. Settings that belong to a feature live in its module instead, and each installed package brings its own. The [configuration](https://marmeon.com/docs/configuration.md#defining-configuration) page explains config definitions. ### `lang/` The texts the whole app shares, such as the questions of `layouts/Confirm.tsx`, one file per language: `lang/en.ts`, `lang/de.ts`. A module keeps its own texts in its `lang/` folder. The [localization](https://marmeon.com/docs/localization.md) page covers both. ### `layouts/` Components the whole app shares, unlike a module's `layouts/`, which wraps that module's pages. The starter kit has `Confirm.tsx`, the dialog the app asks its questions with, such as the one before unsaved changes are left; `bootstrap/client.tsx` passes it to `createMarmeonApp`. The [dialogs](https://marmeon.com/docs/dialogs.md#asking-the-user) page shows it. Starter kit only. ### `middleware/` Middleware that belongs to no feature. A new app does not have the folder yet: `securityHeaders()` from `@marmeon/http` already adds `nosniff`, a referrer policy and `X-Frame-Options` to every response. The [middleware](https://marmeon.com/docs/middleware.md) page shows how to write your own. ### `modules/` The features of the app. Each module is a folder with an `index.ts` that exports its definition: | Module | What it holds | | --- | --- | | `auth/` | Sign-in, registration, password reset, the e-mail check, the security page and API tokens. Written by `marmeon make:auth`, and yours to change. The [starter kit](https://marmeon.com/docs/starter-kit.md) page describes it. | | `home/` | The home page at `/`. Starter kit only. | | `system/` | The migrations of the tables the framework's drivers need, such as the queue's `jobs` table, the `notifications` table and the `live_hints` table. | ### `storage/` What the app writes while it runs. Git keeps the folders and ignores their contents. On a server, `storage/` is a volume of its own: | Path | What it holds | | --- | --- | | `storage/database.sqlite` | The SQLite database. | | `storage/app/private/`, `storage/app/public/` | The local disks of [file storage](https://marmeon.com/docs/storage.md). | | `storage/framework/sessions/` | Sessions of the `file` driver. | | `storage/framework/cache/` | The cache of the `file` driver. | | `storage/framework/devtools/` | What the [devtools](https://marmeon.com/docs/devtools.md) recorded. Development only. | | `storage/framework/compile-cache/` | Node's compile cache, which makes `marmeon start` faster. | | `storage/framework/testing/` | The SQLite databases of [refreshed test apps](https://marmeon.com/docs/database-testing.md), one per test worker, and what a test of a [generated migration](https://marmeon.com/docs/database-testing.md#testing-a-generated-migration) writes: its module and a database of its own. | ### The files in the root | File | What it does | | --- | --- | | `index.html` | The document template. The server renders each page into it. | | `.env`, `.env.example`, `.env.test` | The settings of this machine, a template for them, and the settings of the tests. See [configuration](https://marmeon.com/docs/configuration.md#the-environment-files). | | `package.json` | The dependencies and scripts. Its `imports` field maps `#modules/` to `./modules//index.ts`. | | `tsconfig.json` | Strict TypeScript that Node runs without a compile step. `erasableSyntaxOnly` refuses what Node cannot strip, such as enums and parameter properties. | | `vite.config.ts` | Vite with the `marmeon()` plugin and the React plugin. | | `vitest.config.ts` | The tests: `modules/**/*.test.ts`. | | `.oxlintrc.json` | The lint preset. It keeps views from importing server code by value. | | `AGENTS.md`, `CLAUDE.md` | The guide a coding agent reads at the start of a session. `marmeon agents:sync` keeps a block of `AGENTS.md` current; the rest is yours. `CLAUDE.md` imports `AGENTS.md`. See [coding agents](https://marmeon.com/docs/agents.md). | | `marmeon-stubs.json` | Where the files that `create-marmeon`, `marmeon make:auth` and `marmeon publish` copied came from: the package, its version and a hash per file. `publish` records the migrations of a package in it, so a later release that changes one is noticed. Written by the framework, committed with the app. See [the auth module](https://marmeon.com/docs/starter-kit.md#what-the-auth-module-holds). | ### Generated folders Three folders appear once you run the app or build it. Git ignores them: | Folder | Written by | What it holds | | --- | --- | --- | | `node_modules/` | the package manager | The dependencies. | | `.marmeon/` | `marmeon` itself | The list of installed packages and their providers, the routes the browser may learn, the schema the migrations describe, and after a build the precomputed injection lists. | | `dist/` | `marmeon build` | The browser's files in `dist/client/` and the server rendering in `dist/server/`. | `marmeon` does not use `.marmeon/` when it is a link that leads out of the app (a cloned repository can bring one): it neither writes nor reads there, and says so with `.marmeon leads out of the app … Nothing was written.` or `… was not read.` `marmeon discover`, `marmeon build`, `marmeon schema:project`, `marmeon route:types`, the Vite plugin and a start stop, even when the file behind the link is current. Where the schema the migrations describe is asked for directly (the migrator, for example), it is a cache: it is computed in memory, with a warning. The [last error](https://marmeon.com/docs/errors.md#the-development-error-page) is not written while `.marmeon` is a link of any kind. Remove the link, or point it at a directory inside the app. ## Inside a module A module grows the folders it needs. The auth module of the starter kit uses most of them: ```text modules/auth/ ├── index.ts the definition, and what other modules may import ├── routes.ts the routes of the web group ├── api-routes.ts the routes of the api group, under /api ├── AuthServiceProvider.ts bindings and start-up code ├── controllers/ the classes behind the routes ├── views/ the pages ├── layouts/ the layouts around the pages ├── lang/ the module's texts ├── middleware/ ├── mail/ mails ├── jobs/ queued jobs ├── listeners/ event listeners ├── commands/ console commands ├── migrations/ ├── factories/ ├── seeders/ ├── schedule.ts when the scheduled work runs └── auth.test.ts tests, next to the code ``` Only `index.ts` is required, and two folder names matter: the pages are found under `views/`, and the module's texts under `lang/`. The `system` module's `views/errors/` and `views/layers/` hold the framework's pages your app replaces (error pages, the layer backdrop). Routes, providers, jobs, listeners, commands, migrations and the schedule count once the module's definition lists them. Controllers and other classes need no list: the container builds them when a route or a constructor asks for them. `index.ts` is also the module's public face. Other modules import from `#modules/notes`, never from a file inside it, so whatever `index.ts` exports is what the rest of the app may use. In this example the module also has a repository, which the walk-through below does not create: ```ts title="modules/notes/index.ts" import { defineModule } from '@marmeon/core'; import routes from './routes.ts'; // What other modules may use: export { NoteRepository } from './NoteRepository.ts'; export default defineModule({ name: 'notes', routes, }); ``` The [modules](https://marmeon.com/docs/modules.md) page shows every key a module definition can have, and how to enforce the boundaries with the lint preset. ### Components several modules share A module's `index.ts` is loaded as server code, so it cannot export a `.tsx` component: Node refuses the file ("Unknown file extension"). Views read a module's entry with `import type` only (the lint preset says so). Components that several modules use get an import of their own, next to `#modules/*`: ```json title="package.json" { "imports": { "#modules/*": "./modules/*/index.ts", "#ui": "./modules/ui/components/index.ts" } } ``` Views import from `#ui` directly. The target is a file you write: `modules/ui/components/index.ts` re-exports the shared components (`export { Button } from './Button.tsx';`), and the `ui` module's own `index.ts` stays free of components. ### Folders by feature Apart from `index.ts`, `views/` and `lang/`, the framework finds nothing by the folder names above. A module can just as well group its files by feature: ```text modules/billing/ ├── index.ts ├── routes.ts loads the route files of the features ├── invoices/ │ ├── routes.ts │ ├── ShowInvoiceController.ts │ ├── InvoiceRepository.ts │ └── SendInvoiceJob.ts ├── subscriptions/ ├── views/ │ ├── invoices/Show.tsx │ └── subscriptions/Index.tsx ├── lang/ └── migrations/ ``` The folder names still say one thing: `controllers/`, `jobs/`, `listeners/` and the other folders of their kind hold [server code](https://marmeon.com/docs/vite.md#server-code-in-the-browser), and the build refuses a page that imports a file from them as a value. A feature folder is not one of them. Name the feature folders as server code, so a page that imports `ShowInvoiceController.ts` as a value stops the build instead of shipping the controller to the browser: ```json title="package.json" { "marmeon": { "serverModules": ["modules/billing/invoices/**", "modules/billing/subscriptions/**"] } } ``` The build, the tests and the lint preset read this one list (the preset once `marmeon make:lint-config --force` has written it anew). See [Server folders of your own](https://marmeon.com/docs/vite.md#server-folders-of-your-own). A few things stay where they are, because the framework finds them by their path: - Pages are the `.tsx` files under the module's own `views/`, at any depth. A page in `invoices/` is not found. Group the pages by feature inside `views/` instead: the page name follows the path, so `modules/billing/views/invoices/Show.tsx` is `billing/invoices/Show`. - Texts are the files directly in `lang/`. - Migrations are the files directly in the one folder the definition names. Folders inside it may hold helpers a migration imports. - A module lists one route file per group, and that file loads the features' route files: ```ts title="modules/billing/routes.ts" import { defineRoutes } from '@marmeon/http'; import invoices from './invoices/routes.ts'; import subscriptions from './subscriptions/routes.ts'; export default defineRoutes((Route) => { invoices.register(Route); subscriptions.register(Route); }); ``` Jobs, listeners and commands are listed in `index.ts` wherever they live. The boundary rule, which `marmeon make:lint-config --boundaries` adds to the lint preset, covers files up to seven folders below a module, more if a module is deeper when the preset is written. A feature that brings its own tables, routes and pages often makes a module of its own: then it has its own migrations and its own `views/`, and other modules reach it only through its `index.ts` and the tables it [exposes](https://marmeon.com/docs/queries.md#module-boundaries). ### Where tests live The app's `vitest.config.ts` decides which files are tests. A new app collects `modules/**/*.test.ts`, so a test next to the code and one in a module's `tests/` folder both run. For a `tests/` folder in the app's root, add it to the list: ```ts title="vitest.config.ts" import { marmeon } from '@marmeon/vite'; import { defineConfig } from 'vitest/config'; export default defineConfig({ plugins: [marmeon({ test: true })], test: { include: ['modules/**/*.test.ts', 'tests/**/*.test.ts'] }, }); ``` With the boundary rule, the lint preset lets a test import from inside any module, wherever the test lives. ## Your first module A new feature starts as a module. This walk-through adds a page at `/notes` for signed-in users. ### Create the module `make:module` writes `index.ts` and an empty `routes.ts` (`--no-routes` leaves `routes.ts` out, for a module without pages or endpoints), and `make:controller` writes a controller and its page: ```sh pnpm marmeon make:module notes pnpm marmeon make:controller ListNotes --module=notes --view ``` With npm, run the commands as `npx marmeon …`. `pnpm marmeon list` shows every command the app has. ### Register it The app loads a module only when `bootstrap/app.ts` lists it. `make:module` adds the module last in `modules` (routes match in module order), which gives: ```ts title="bootstrap/app.ts" import { join } from 'node:path'; import { defineApplication } from '@marmeon/core'; import { contentSecurityPolicy, securityHeaders } from '@marmeon/http'; import auth from '#modules/auth'; import home from '#modules/home'; import system from '#modules/system'; import { AppConfig } from '../config/app.ts'; import notes from '#modules/notes'; export default defineApplication({ root: join(import.meta.dirname, '..'), config: [AppConfig], modules: [auth, home, system, notes], middleware: { global: [securityHeaders(), contentSecurityPolicy()], }, }); ``` ### Add the route, the controller and the page The route points to the controller and gives it a name. `authenticate()` sends guests to the sign-in page, and `verified()` sends an account whose address is not confirmed yet to the auth module's notice: ```ts title="modules/notes/routes.ts" import { authenticate, verified } from '@marmeon/auth'; import { defineRoutes, everyone } from '@marmeon/http'; import { ListNotesController } from './controllers/ListNotesController.ts'; export default defineRoutes((Route) => { Route.middleware(authenticate()).middleware(verified()).authorize(everyone).get('/notes', ListNotesController).name('notes.index'); }); ``` `authenticate()` alone would let in an account registered with somebody else's address. The auth module's own pages check the address themselves, and a route of yours needs `verified()` for that. The [starter kit](https://marmeon.com/docs/starter-kit.md#your-own-pages) page explains why. The controller answers with the page `notes/ListNotes`, which is `modules/notes/views/ListNotes.tsx`, and hands it its props: ```ts title="modules/notes/controllers/ListNotesController.ts" import type { Authenticated } from '@marmeon/auth'; import { Controller, type HttpContext } from '@marmeon/http'; export class ListNotesController extends Controller { handle(ctx: HttpContext) { return this.view('notes/ListNotes', { author: ctx.user.name }); } } ``` The page takes its props from the controller's type, so a prop the controller does not send is a compile error: ```tsx title="modules/notes/views/ListNotes.tsx" import type { PageProps } from '@marmeon/http'; import { Head, Link } from '@marmeon/react'; import type { ListNotesController } from '../controllers/ListNotesController.ts'; export default function ListNotes({ author }: PageProps) { return (

Notes of {author}

Back to the dashboard
); } ``` The view imports the controller with `import type`. A value import would bundle server code into the browser, and the lint preset and the build both refuse it. ### See it `pnpm dev` keeps `bootstrap/routes.ts` up to date, so `notes.index` is a known route name at once. Open http://localhost:3000/notes and sign in with a confirmed account, and the page is there. The [installation](https://marmeon.com/docs/installation.md#your-first-account) page shows how to register the first account. `pnpm marmeon route:list` shows the route with every middleware it passes. ### A table for the notes `make:migration` writes a migration into the module: ```sh pnpm marmeon make:migration create_notes_table --module=notes ``` The first migration of a module also needs its folder in the module's definition: the command adds `migrations: new URL('./migrations/', import.meta.url)` and prints the line only when the file has another shape or you pass `--no-register`. `pnpm marmeon migrate` then creates the table and, in development, writes its types into `bootstrap/database.d.ts`. The [migrations](https://marmeon.com/docs/migrations.md) and [repositories](https://marmeon.com/docs/queries.md) pages go on from there. [Your First App](https://marmeon.com/docs/first-app.md) takes this module on to a complete notes app with a policy, forms and tests. --- # Starter Kit ## Introduction The starter kit is what `pnpm create marmeon` gives you by default: a blank app plus two modules. The `auth` module handles accounts: sign-in, registration, password reset, the confirmation of an address, a security page, two-factor authentication, passkeys and API tokens. The `home` module is the page at `/`. Both are ordinary modules in your app, written as source code, so you read them, change them and delete what you do not need. [Your First App](https://marmeon.com/docs/first-app.md) adds a notes module of your own on top of the kit. ```sh pnpm create marmeon my-app # the starter kit pnpm create marmeon my-app --minimal # a blank app, without both modules ``` Either way, the app also has an `AGENTS.md` and a `CLAUDE.md` ([coding agents](https://marmeon.com/docs/agents.md)). The auth module comes from the generator `marmeon make:auth`. It writes the module once, and from then on it belongs to your app. The mechanics behind it, such as hashing, sessions, tokens and policies, stay in the `@marmeon/auth` package, and updates of the framework bring them. ## What the auth module holds | Part | What it is | | --- | --- | | `index.ts` | The module's definition: its provider, the listeners that send the confirmation mail and the notes about the second factor and about passkeys, the queued jobs, the migrations, the seeder, the routes, the schedule and the command `auth:prune-unverified` (`auth:end-sessions` and `auth:reset-two-factor` come with `@marmeon/auth`). | | `AuthServiceProvider.ts` | Finds users through the `UserRepository`, binds the authenticator app and passkeys as the sources of second factors, and shares `auth` with every page. The rate limits of its forms are those of `@marmeon/auth` ([the limits of the auth routes](https://marmeon.com/docs/authentication.md#the-limits-of-the-auth-routes)). | | `users.ts`, `UserRepository.ts` | The `User` type and the only code that reads a password hash or a session key. It is the app's `UserProvider`: the statements that write a hash or a session key are `credentialWriter()` of `@marmeon/auth`, so a fix to them reaches you with a package update. The `session_key` column lets `auth.updateSessionKey()` end an account's other sessions with every session driver. | | `routes.ts`, `api-routes.ts` | The pages and forms, and `GET /api/user` for API tokens. | | `home.ts` | `HOME`, the name of the route people land on after they sign in, register or confirm their address: `dashboard`. Change the name there and every sign-in, the guest pages (`guest({ homeRoute: HOME })`) and the layout follow. It names a route without path parameters. | | `controllers/` | The controllers of the pages and forms in `routes.ts`. A form's controller validates it with a request schema. | | `views/`, `layouts/` | The React pages and the app's layout, `AppLayout`, with a settings layout inside it. | | `mail/` | Ten mails: the confirmation of an address, the reset link, the notes about a change of address and about a known address, the notes about the second factor and about passkeys, the note about a copied "keep me signed in" cookie, and the note that an account stopped taking passwords. A mail greets the account by name only at an address it has confirmed: the confirmation link, the link to a new address and every mail to an address not yet confirmed say "Hello,", since the name is the registrant's own text (`mail/greeting.ts`). Each mail is a class (`*Mail.ts`) with a React view next to it (`*View.tsx`) inside the shared frame `mail/Layout.tsx`; the views are written with [`@marmeon/react/mail`](https://marmeon.com/docs/mail.md#mail-views-in-react), so the app needs `oxc-transform` as a development dependency (`pnpm add -D oxc-transform`; `create-marmeon` adds it to a new app). | | `jobs/`, `listeners/`, `commands/` | The work that runs on the queue, the listeners that react to events, and the command `auth:prune-unverified`. | | `middleware/` | `ShareAuthProps` and `ConfirmedAddress`. | | `migrations/` | The tables `users`, `password_reset_tokens`, `personal_access_tokens`, `two_factor_authentications` with `two_factor_recovery_codes`, `passkeys`, `sign_ins`, which also holds the remember-me tokens, and `email_changes`, where a change of address waits for its link. | | `factories/`, `seeders/` | `UserFactory` for tests, and `UserSeeder` with `test@example.com` and the password `password`. The seeder runs only with `marmeon db:seed` or `migrate:fresh --seed`, and refuses outside development and tests: never seed a server with it. | | `schedule.ts` | The nightly clean-up of expired tokens and changes of address. | | `*.test.ts` | The module's own tests, next to the code. | `marmeon make:auth` also writes `marmeon-stubs.json` into the root of the app: for every file it copied, except the migrations, the template it came from in `@marmeon/auth`, the version of the package and the hash of what it wrote (line endings do not count). Commit it with the module. The file belongs to the framework, so do not edit it by hand; without it, where a file came from is unknown. `make:auth --force` also uses its hashes to tell a file of an earlier kit you left unchanged from one you changed. `make:auth` and `create-marmeon` leave the migrations out: they belong to your app, and `make:auth --force` keeps the ones the app has and adds only those it lacks. [`marmeon publish`](https://marmeon.com/docs/migrations.md#publishing-the-migrations-of-a-package) records the migrations of the packages it copies in the same file. They are append-only: a file the framework shipped never changes, so a later change of a kit table comes as a new migration. After a merge conflict in `marmeon-stubs.json`, take one side: the hashes then match that side. A file from a newer Marmeon makes `make:auth` and `publish` stop before they write anything. `create-marmeon` writes the file first, with the sets `create-marmeon:base` (and `create-marmeon:kit` for the starter kit); `make:auth` adds its own set to it. The module is wiring and pages: the repository, the routes, the controllers, the views, the mails and the migrations. About sign-ins, passwords, factors and sessions it decides nothing: the limits, the checks, the single-use links and the ending of sessions are services of `@marmeon/auth`, which the controllers call; [what the package decides](https://marmeon.com/docs/authentication.md#what-the-package-decides) lists them, and a package update brings their fixes. The stores come with the package too, so the module has no store of its own to keep up to date. What you could implement yourself, and which members are required, is listed under [what your app implements](https://marmeon.com/docs/authentication.md#what-your-app-implements). The module does decide a few things of its own, described under [private registration](https://marmeon.com/docs/starter-kit.md#private-registration): that registration answers alike, in the same time and with a hash, for a new and a taken address; how many mails go to one address and the lock per recipient in `SendAccountExistsMailJob` and `SendEmailChangeMailJob`; `ConfirmedAddress`; and `auth:prune-unverified`. The module's routes each say who may call them, as the app's do. Its groups decide with `everyone`: the sign-in and registration pages are open to guests, and every action behind `authenticate()` concerns only the signed-in user's own account. A route you add to the module needs a decision of its own. The [authorization](https://marmeon.com/docs/authorization.md#every-route-decides) page has the rule. To add a language, put a file next to every `en.ts` of the app — a locale with any language file is supported (see [Localization](https://marmeon.com/docs/localization.md), `APP_LOCALES`). `apps/web-app` in the framework's repository shows such a module grown further, with a welcome mail. ## The pages | Path | Name | Who | | --- | --- | --- | | `/login` | `auth.login` | guests | | `/register` | `auth.register` | guests | | `/register/sent` | `auth.register.sent` | guests, after they register | | `/two-factor-challenge` | `auth.two-factor.challenge` | guests whose password was right and who have a second factor | | `/forgot-password`, `/reset-password` | `auth.password.request`, `auth.password.reset` | guests | | `/dashboard` | `dashboard` | signed in, with a confirmed address | | `/confirm-password` | `auth.password.confirm` | signed in, with a confirmed address; asks for the password, and offers "Use a passkey instead" to an account with a usable passkey | | `/confirm-password/passkey/options`, `/confirm-password/passkey` | `auth.password.confirm.passkey.options`, `auth.password.confirm.passkey` | the same; `POST`, the options limited to ten a minute per user | | `/settings/security` | `auth.security` | the same, and a recent confirmation (password or passkey) within 15 minutes by default | | `/settings/sign-ins/:signIn/end` | `auth.sign-ins.destroy` | the same as the security page; `POST`, ends one other sign-in | | `/settings/two-factor` | `auth.two-factor` | the same | | `/settings/two-factor/verify` | `auth.two-factor.verify` | signed in, with a confirmed address; for `twoFactor()` | | `/settings/passkeys` | `auth.passkeys` | the same as the security page | | `/settings/tokens` | `auth.tokens` | the same | | `/email/verify` | `auth.verification.notice` | signed in | A signed-in user who opens a guest page goes to `HOME` of `modules/auth/home.ts`, `/dashboard` as the module ships. A sign-in (password, second factor, passkey) goes to the page that asked for it, or to `HOME` when none did; `HOME` is a route name, so moving it is one edit. A view cannot import it into ``, since the build reads route names written out, so the layout takes the URL from the page's `home` prop. The security page changes the password and the e-mail address, signs out the other devices, and lists the browsers the account is signed in on, each with a button to end it ([sign-ins](https://marmeon.com/docs/authentication.md#sign-ins)). The two-factor page sets up an authenticator app and shows the recovery codes once; the challenge page asks for the code, a passkey or a recovery code after the password. The passkeys page adds, renames and removes passkeys, and the login page offers "Sign in with a passkey". The tokens page creates and revokes API tokens. A passkey alone can confirm sudo mode, so the forms that change the e-mail address, create an API token, turn on an authenticator app and make new recovery codes ask for the current password too, as the passkeys and password forms do ([sudo mode](https://marmeon.com/docs/authentication.md#sudo-mode)). `/` belongs to the home module, so the auth module leaves it free. The routes are an ordinary route file, so you change a path, add a page or remove one in `modules/auth/routes.ts`. The [routing](https://marmeon.com/docs/routing.md#route-files) page explains route files. ## Pages of your own in the kit's layout `modules/auth/layouts/AppLayout.tsx` is the app's layout: the header with the app's name and the account links, and the messages that pop up. The pages of the kit set it with `Login.layout = AppLayout`, and a page of your own does the same ([Your First App](https://marmeon.com/docs/first-app.md) shows it): ```tsx title="modules/notes/views/ListNotes.tsx" import { AppLayout } from '../../auth/layouts/AppLayout.tsx'; ListNotes.layout = AppLayout; ``` The file is yours: put the links of your app into its `