rossa 0.0.6 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,50 @@
1
+ # Changelog
2
+
3
+ Notable changes to this project are documented here. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [0.1.2] - 2026-11-23
8
+
9
+ ### ⚠️ Behavior change
10
+
11
+ - `sendError` no longer adds `Access-Control-Allow-Origin: *` to error responses,
12
+ so guard rejections are no longer readable by every origin in the browser.
13
+ Apps that relied on the wildcard must set the header explicitly — through the
14
+ `cors()` guard or through a guard's error config, e.g.
15
+ `{ headers: { "Access-Control-Allow-Origin": "..." } }`.
16
+
17
+ ### Fixed
18
+
19
+ - `serve()` hands the actually bound port to the ready callback and logs the
20
+ bound URL, so `port: 0` reports the OS-assigned port (and `https` with TLS)
21
+ instead of the configured value.
22
+ - `multipart()` preserves the MIME type declared on uploaded parts, so `File.type`
23
+ keeps its value instead of being empty.
24
+ - `validateUrl` also rejects path-traversal markers in the query string rather
25
+ than checking the path alone.
26
+ - `createGuard` honours a per-call `overrideConfig.code` over the guard default.
27
+ - Session and cookie lifetimes accept fractional days with millisecond
28
+ precision instead of truncating to whole days.
29
+ - A `MAX_COOKIE_SIZE` overflow no longer leaves an orphaned session record or
30
+ surfaces as an empty 500 response.
31
+ - Routes that combine `jwtAuth` and `jwtRefresh` no longer overwrite
32
+ `ctx.jwtData`, and a rejected refresh no longer consumes the refresh token.
33
+
34
+ ### Added
35
+
36
+ - `urlencoded({ strict: true })` opt-in strict parsing mode.
37
+ - `json()` also populates `ctx.body` (alongside the existing `ctx.req._json`).
38
+ - `session({ auth, readonly })` mounts, `ctx.session.rotate()`, and a typed
39
+ `SessionContext<T>`.
40
+ - `jwtRotate` guard: verifies the access token and rotates the refresh token in
41
+ one step.
42
+ - Machine-readable refresh rejection reasons in `error_code`
43
+ (`invalid` | `expired` | `reused`).
44
+ - `WWW-Authenticate: Bearer` on JWT 401 responses.
45
+ - Per-call JWT lifetimes with `sign(payload, lifetimeSeconds?)`.
46
+ - Optional `deleteExpired(before)` hook on refresh-token stores for cleanup of
47
+ expired rows.
48
+ - Documented claim-once semantics for refresh-token stores (deleting the row or
49
+ marking it consumed are both valid).
50
+ - Guard rejection shapes documented in `doc/` and pinned by smoke tests.
package/README.md CHANGED
@@ -1,12 +1,11 @@
1
1
  # Rossa
2
2
 
3
3
  Rossa is a Bun HTTP server with decorator-based routing, request guards, a
4
- response/context API, and optional WebSocket routes.
4
+ response/context API, SSE, WebSocket routes, authentication building blocks,
5
+ and a small SQL repository layer. This README is the quick start; see
6
+ [`doc/features.md`](doc/features.md) for the complete feature reference.
5
7
 
6
- For browser-side data storage, see the standalone [IndexedDB helper](indexeddb/README.md)
7
- outside `src`, with schema/column builders and typed CRUD operations.
8
-
9
- ## Install and build
8
+ ## Install
10
9
 
11
10
  Rossa requires Bun. In an application, install the published package and import
12
11
  its public API from `rossa`:
@@ -15,9 +14,10 @@ its public API from `rossa`:
15
14
  bun add rossa
16
15
  ```
17
16
 
18
- The package build bundles the runtime entry point for Bun and emits TypeScript
19
- declarations under `dist/`. Run `bun run build` before packing or publishing;
20
- `bun pm pack --dry-run` previews the files included in the package.
17
+ The published package ships bundled JavaScript and TypeScript declarations under
18
+ `dist/`. From a source checkout, run `bun run builder.ts` before packing;
19
+ `bun pm pack --dry-run` previews the files included. The project intentionally
20
+ has no `build` npm script.
21
21
 
22
22
  ## Create a server
23
23
 
@@ -42,50 +42,32 @@ app.register(Users);
42
42
  app.serve({ port: 3000, hostname: "localhost" });
43
43
  ```
44
44
 
45
- Call `app.getPaths()` after registering controllers to get an array of HTTP
46
- route paths, including any `basePath`. Parameter names have their colons removed:
47
-
48
- ```ts
49
- app.getPaths(); // ["/users/id"]
50
- ```
45
+ Call `app.getPaths()` after registering controllers to list HTTP paths, including
46
+ any `basePath`, with parameter colons removed (for example `["/users/id"]`).
51
47
 
52
48
  `Rossa` accepts these options:
53
49
 
54
50
  | Option | Default | Purpose |
55
51
  | ---------------- | ------------ | --------------------------------------------------------------------------------------------------------- |
56
52
  | `basePath` | `""` | Prefix added to registered HTTP and WebSocket routes. |
57
- | `clientPath` | `"./public"` | Directory used by `res.fileServer()`. |
53
+ | `clientPath` | `"./public"` | Directory used by `res.fileServer()`. A relative path is resolved from the parent of `dirPath`. |
58
54
  | `dirPath` | `"./src"` | Anchor used to resolve a relative `clientPath`. |
59
55
  | `fileExtensions` | `[]` | Additional extensions to recognize, with or without a leading dot. Built-in extensions remain recognized. |
60
56
  | `logError` | `false` | Log errors caught by the router pipeline. |
61
57
  | `Encoding` | `"br"` | Response encoding; supports the `ContentEncodingType` values. |
62
58
 
63
59
  `app.serve(serverOptions, websocketOptions)` starts Bun's server. The first
64
- argument accepts Bun serve options plus an optional `fn(port)` callback. The
65
- second argument accepts Bun WebSocket options. If no port is provided, Rossa
60
+ argument accepts Bun serve options plus an optional `fn(port, server)` ready
61
+ callback. It runs after Bun binds the socket, so `port` is the actual bound port
62
+ (including an OS-assigned ephemeral port when `port: 0`); the second argument is
63
+ the bound `Bun.Server`. Without `fn`, the startup log prints the bound URL,
64
+ including `https` when `tls` is set. The second argument accepts Bun WebSocket
65
+ options plus Rossa's optional `messageRateLimit`. If no port is provided, Rossa
66
66
  uses `3000`.
67
67
 
68
- ## Static files
69
-
70
- Rossa recognizes common web, image, font, text, and JSON extensions by
71
- default. Add extensions such as PDF or WebAssembly when creating the app:
72
-
73
- ```ts
74
- const app = new Rossa({ fileExtensions: [".pdf", "wasm"] });
75
- ```
76
-
77
- The `req.isFile` check recognizes these extensions. A catch-all route can then
78
- call `res.fileServer()` to serve from `clientPath`:
79
-
80
- ```ts
81
- @route("/:file")
82
- class PublicFiles extends Methods {
83
- get({ req, res }: ctx): Promise<Response> | Response {
84
- if (req.isFile) return res.fileServer();
85
- return res.null(404);
86
- }
87
- }
88
- ```
68
+ `app.test(request, encoding?)` runs a `Request` through the same pipeline
69
+ without binding a socket. `app.registerWSS(...)` registers WebSocket
70
+ controllers, described below.
89
71
 
90
72
  ## Routes and request context
91
73
 
@@ -104,9 +86,20 @@ class Notes extends Methods {
104
86
  }
105
87
  ```
106
88
 
89
+ Rossa supplies an inherited `options` handler for each declared path. It
90
+ returns `204` with an `Allow` header built from the methods registered for that
91
+ path, including `OPTIONS`. OPTIONS on an undeclared path returns `404`, and a
92
+ `HEAD` request without an implemented `head` handler also returns `404` — there
93
+ is no automatic GET fallback.
94
+
107
95
  Useful response methods include `text`, `html`, `json`, `success`, `error`,
108
- `redirect`, `null`, and `fileServer`. Route parameters are exposed as strings
109
- on `ctx.params`; query parameters are available from `ctx.req.query`.
96
+ `redirect`, `null`, `file`, and `fileServer`. Route parameters are exposed as
97
+ strings on `ctx.params`; query parameters are available from `ctx.req.query`.
98
+ Guards may place validated values on `ctx.query`, `ctx.body`, or `ctx.form`.
99
+
100
+ For SSE, a GET request whose `Accept` header allows `text/event-stream` routes
101
+ to `event`. Return `res.event.asyncStream(...)`, `res.event.eStream(...)`, or
102
+ `res.event.readableStream(...)`; these require a live Bun server.
110
103
 
111
104
  ## Guards
112
105
 
@@ -129,20 +122,72 @@ class Api extends Methods {
129
122
  }
130
123
  ```
131
124
 
132
- The public entry point exports guard factories for authentication, caching,
133
- compression, content type, cookies, CORS, CSRF, errors, forms, headers, IP
134
- filtering, JSON, JWT, logging, multipart, query validation, rate limiting,
135
- sanitization, security headers, sessions, static files, timeouts, and URL
136
- validation. See [`doc/guards.md`](doc/guards.md) for guard behavior and
137
- examples.
125
+ `app.use` prepends guards, so a guard registered later runs earlier. Place
126
+ wrapper guards such as `errorHandler` and `security` before the work whose
127
+ response they should wrap.
128
+
129
+ The public entry point exports guard factories for authentication
130
+ (`authBearer`, `apiKey`, `auth`, `authorize`), caching (`smartCache`), content
131
+ type, cookies, CORS, CSRF, error boundaries (`errorHandler`), headers, IP
132
+ filtering, JSON body validation, required JSON keys (`keys`), JWT (`jwtAuth`,
133
+ `jwtRefresh`, `jwtRotate`), logging (`logger`, `loggerFN`), multipart and
134
+ URL-encoded forms, query and form validation, rate limiting, sanitization,
135
+ security headers, sessions, static files, timeouts, and URL validation. Define
136
+ reusable custom guards with `createGuard`. See [`doc/guards.md`](doc/guards.md)
137
+ for guard behavior and examples.
138
+
139
+ Sessions accept the service or `{ auth, readonly }`, can be typed with
140
+ `session<TData>()` plus `SessionContext<TData>`, and expose
141
+ `ctx.session.rotate()` after login. JWT guards expose refresh claims in
142
+ `ctx.data.jwtRefreshData`, reject refresh failures with `error_code`
143
+ (`invalid`, `expired`, `reused`) and `WWW-Authenticate: Bearer`, and require
144
+ `jwtAuth` before `jwtRefresh` on combined routes.
145
+
146
+ ### Rejection and response defaults
147
+
148
+ - `security()` adds `Referrer-Policy: strict-origin-when-cross-origin`,
149
+ `X-Content-Type-Options: nosniff`, and `X-Frame-Options: DENY`. CSP, HSTS, and
150
+ the other policies are opt-in.
151
+ - `sendError()` returns JSON `{ success: false, error }` and only the headers
152
+ you pass. **Behavior change:** it no longer adds
153
+ `Access-Control-Allow-Origin: *`; the `cors` guard owns CORS.
154
+ - The `errorHandler()` guard returns a plain-text `500`
155
+ `Internal Server Error`, not JSON.
156
+ - A per-call guard `code` overrides the factory default
157
+ (`createGuard(..., { code: 403 })(options, { code: 451 })` answers `451`).
158
+
159
+ ## Static files
160
+
161
+ Rossa recognizes common web, image, font, text, and JSON extensions by default.
162
+ Add extensions such as PDF or WebAssembly when creating the app:
163
+
164
+ ```ts
165
+ const app = new Rossa({ fileExtensions: [".pdf", "wasm"] });
166
+ ```
167
+
168
+ The `req.isFile` check recognizes these extensions. A catch-all route can then
169
+ call `res.fileServer()` to serve from `clientPath`:
170
+
171
+ ```ts
172
+ @route("/:file")
173
+ class PublicFiles extends Methods {
174
+ get({ req, res }: ctx): Promise<Response> | Response {
175
+ if (req.isFile) return res.fileServer();
176
+ return res.null(404);
177
+ }
178
+ }
179
+ ```
180
+
181
+ The static server checks resolved paths against the configured root (including
182
+ symlink resolution), caches small files, and supports ETags.
138
183
 
139
184
  ## WebSockets
140
185
 
141
186
  Decorate a `Websocket` subclass with `@wss(path)` and register it with
142
- `app.registerWSS`. Its `open`, `message`, and `close` methods handle the
143
- connection lifecycle. Guards on the WebSocket route can place verified
144
- identity in `ctx.data`; Rossa copies that data to `this.contextData` before
145
- calling `open`.
187
+ `app.registerWSS`. Its `open`, `message`, `close`, and `drain` methods handle the
188
+ connection lifecycle. Guards on the WebSocket route can place verified identity
189
+ in `ctx.data`; Rossa copies that data to `this.contextData` before calling
190
+ `open`.
146
191
 
147
192
  ```ts
148
193
  import { Rossa, Websocket, wss } from "rossa";
@@ -174,19 +219,64 @@ app.serve(
174
219
  `messageRateLimit` is optional and counts inbound messages independently for
175
220
  each socket using a fixed time window. When a socket exceeds its limit, Rossa
176
221
  closes it with code `1008`. `maxPayloadLength`, `backpressureLimit`, and
177
- `closeOnBackpressureLimit` are Bun WebSocket options. A controller may implement
178
- `drain()` to resume work after Bun drains buffered outbound data. Topic
179
- `manager.broadcast(...)` returns per-topic statuses (`sent`, `backpressured`,
180
- `dropped`, or `oversize`) so handlers can observe publish outcomes.
222
+ `closeOnBackpressureLimit` are Bun options. `drain()` runs after Bun drains
223
+ buffered outbound data.
224
+
225
+ `this.manager` is a per-connection `subManager` backed by the process-wide
226
+ `WSSMAN` singleton. Use it to subscribe to topics, broadcast, inspect members,
227
+ set admin flags, and configure room capacity or payload limits. Broadcast
228
+ results report each topic as `sent`, `backpressured`, `dropped`, or `oversize`.
181
229
 
182
230
  For the handshake, frame parsing, lifecycle, and sample chat message contract,
183
231
  see [`doc/websockets.md`](doc/websockets.md).
184
232
 
233
+ ## MCP (Model Context Protocol)
234
+
235
+ Rossa can expose an MCP server over Streamable HTTP. Extend `McpController`,
236
+ declare tools, resources, and prompts in `build`, then register the decorated
237
+ class:
238
+
239
+ ```ts
240
+ import { McpController, McpServer, Rossa, mcp } from "rossa";
241
+
242
+ const app = new Rossa();
243
+
244
+ @mcp("/mcp", { origin: "https://app.example.com" })
245
+ class Assistant extends McpController {
246
+ build(server: McpServer) {
247
+ server.registerTool(
248
+ "echo",
249
+ { description: "Echo a fixed value" },
250
+ async () => ({ content: [{ type: "text", text: "ok" }] }),
251
+ );
252
+ }
253
+ }
254
+
255
+ app.registerMCP(Assistant);
256
+ ```
257
+
258
+ For an explicit path without a controller class, pass a per-request factory:
259
+ `app.registerMCP("/mcp", (context) => new McpServer({ name: "raw", version: "1.0.0" }))`.
260
+
261
+ `origin` accepts full origins, bare hostnames, or `scheme://*`; requests without
262
+ an `Origin` header always pass. POST is served, GET and DELETE return `405`, and
263
+ OPTIONS/HEAD return `404`. Global `app.use(...)` guards run before the endpoint
264
+ and can block it, but header-only guards such as `cors()` do not decorate the
265
+ SDK's response; use `origin` or handle MCP CORS at a proxy.
266
+
267
+ See the [MCP chapter](doc/features.md#mcp-model-context-protocol) and the
268
+ [official TypeScript SDK docs](https://ts.sdk.modelcontextprotocol.io/v2/).
269
+
270
+ For a runnable notes server backed by Rossa's SQLite repository, run
271
+ `bun run examples/mcp/server.ts`. It exposes `add-note`, `list-notes`, and
272
+ `search-notes`; see [`examples/mcp/README.md`](examples/mcp/README.md) for setup,
273
+ Inspector, and curl examples.
274
+
185
275
  ## Test requests without starting a server
186
276
 
187
277
  `app.test(request)` runs a `Request` through the same router pipeline and
188
- returns a `Response`. The runnable example in [`test.ts`](test.ts) shows HTTP,
189
- guards, WebSockets, and this in-process request method.
278
+ returns a `Response`. The runnable [`test.ts`](test.ts) shows HTTP, guards,
279
+ WebSockets, and this method.
190
280
 
191
281
  ```ts
192
282
  const response = await app.test(
@@ -197,30 +287,38 @@ console.log(response.status, await response.text());
197
287
 
198
288
  ## Public exports
199
289
 
200
- `src/index.ts` is the package entry point. It exports:
201
-
202
- - `Rossa` and its `RossaOptions`, `serverOptions`, and `dev` types.
203
- - `ContentEncodingType` for the supported response encodings.
204
- - `Methods`, `RouterManager`, `route`, `wss`, and router metadata types.
205
- - `use`, `createGuard`, guard factories, and guard-related types.
206
- - `ctx`, `Req`, `Res`, and response error types.
207
- - `Websocket`, `wssMessage`, `WssConfig`, `WssManager`, `subManager`, and the
208
- default `WSSMAN` singleton.
209
- - `Field` for typed field scopes. See [`doc/field-scopes.md`](doc/field-scopes.md)
210
- for a route example.
290
+ `src/index.ts` exports `Rossa` and its option types; `Methods`, `RouterManager`,
291
+ `route`, and `wss`; guard factories with `use` and `createGuard`; `ctx`, `Req`,
292
+ `Res`, and `sendError`; WebSocket classes and `WSSMAN`; MCP (`McpController`,
293
+ `McpServer`, `mcp`); authentication (`JWTAuthService`, `JwtEngine`,
294
+ `SessionAuthInterface`, `ServerSide`, and the session/JWT types), database, and
295
+ `Field`/`Scope` APIs. `JWTAuthService.sign(payload, lifetimeSeconds?)` accepts a
296
+ per-call lifetime; the lower-level `JwtEngine.signSeconds` is exported too. See
297
+ [`doc/features.md`](doc/features.md) for names.
298
+
299
+ ## Documentation and examples
300
+
301
+ | Document | Contents |
302
+ | ---------------------------------------------------------- | ---------------------------------------------------------- |
303
+ | [`doc/features.md`](doc/features.md) | Complete feature and API reference. |
304
+ | [`doc/guards.md`](doc/guards.md) | Guard behavior, ordering, and custom guards. |
305
+ | [`doc/websockets.md`](doc/websockets.md) | WebSocket client contract, lifecycle, and limits. |
306
+ | [MCP TypeScript SDK](https://ts.sdk.modelcontextprotocol.io/v2/) | Official MCP server docs for tools, resources, and prompts. |
307
+ | [`doc/session-auth.md`](doc/session-auth.md) | Session service implementation and login backend example. |
308
+ | [`doc/db.md`](doc/db.md) | Repository, schema, dialects, and schema synchronization. |
309
+ | [`doc/field-scopes.md`](doc/field-scopes.md) | Typed `Field` decorators and shared [`Scope`](doc/scopes.md) values. |
310
+ | [`doc/routing-style.md`](doc/routing-style.md) | Route registration and matching model. |
311
+ | [`src/wss/examples/README.md`](src/wss/examples/README.md) | Group chat, direct message, and bot examples. |
211
312
 
212
313
  Run the sample with `bun run test.ts`.
213
314
 
214
- For a group chat built on per-conversation topics, session authentication,
215
- membership checks, and a persistence adapter, see
216
- [`src/wss/examples/README.md`](src/wss/examples/README.md).
217
-
218
315
  ## Load harness
219
316
 
220
- Run the repeatable local WebSocket load harness with `bun run test:load`. It
221
- reports fan-out delivery ratio, latency percentiles, publish statuses, and RSS
222
- memory change. Set `BENCH_CLIENTS`, `BENCH_DURATION_SECONDS`,
317
+ Run the local WebSocket load harness with `bun run test:load`. It reports
318
+ fan-out delivery, latency percentiles, publish statuses, and RSS change.
319
+ Configure it with `BENCH_CLIENTS`, `BENCH_DURATION_SECONDS`,
223
320
  `BENCH_MESSAGES_PER_SECOND`, `BENCH_DELIVERY_TIMEOUT_MS`, or
224
- `BENCH_BACKPRESSURE_LIMIT` to adjust the workload. Use a staging environment
225
- and representative deployment limits before drawing production capacity
226
- conclusions.
321
+ `BENCH_BACKPRESSURE_LIMIT`. It is a benchmark, not a capacity guarantee.
322
+ WebSocket rooms, rate-limit counters, and the small-file cache are process-local;
323
+ multi-instance deployments need shared pub/sub, membership state, and rate
324
+ limiting.