rossa 0.1.1 → 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/dist/index.d.ts CHANGED
@@ -244,6 +244,8 @@ declare class Heder extends Utils {
244
244
  }
245
245
  type HederPlugin = (h: Heder) => void;
246
246
 
247
+ /** A resolved session with both the framework methods and the user's data. */
248
+ type SessionInstance<TData extends Record<string, any> = Record<string, any>> = ServerSide<TData> & TData;
247
249
  declare class ServerSide<TData extends Record<string, any> = Record<string, any>> {
248
250
  sid: string;
249
251
  data: TData;
@@ -252,13 +254,44 @@ declare class ServerSide<TData extends Record<string, any> = Record<string, any>
252
254
  isReadOnly: boolean;
253
255
  isFound: boolean;
254
256
  length: number;
257
+ /**
258
+ * Rotation hook supplied by the session service.
259
+ * @internal
260
+ */
261
+ private _rotator?;
255
262
  constructor(sid?: string, initialData?: Partial<TData>, readOnly?: boolean, isNew?: boolean, isFound?: boolean);
256
263
  /**
257
264
  * Generates the dynamic Proxy trapped instance.
258
265
  * We use `this & TData` so TypeScript knows this object contains both
259
266
  * the class methods AND the dynamic user data.
260
267
  */
261
- get session(): any;
268
+ get session(): SessionInstance<TData>;
269
+ /**
270
+ * Registers the service callback used by {@link ServerSide.rotate}.
271
+ * @internal
272
+ */
273
+ setRotator(rotator: () => Promise<void>): void;
274
+ /**
275
+ * Replaces this session's identifier in place.
276
+ * @internal
277
+ */
278
+ renewSid(sid: string): void;
279
+ /**
280
+ * Rotates the session identifier (session-fixation defence).
281
+ *
282
+ * The previous row is deleted and this session receives a freshly signed
283
+ * `sid`; the guard persists the new row and sends its cookie after the
284
+ * handler returns. Call it after a successful login:
285
+ *
286
+ * ```ts
287
+ * await ctx.session!.rotate();
288
+ * ctx.session!.userId = user.id;
289
+ * ```
290
+ *
291
+ * A readonly mount ignores rotation. Throws when the session was created
292
+ * without a session service (for example a hand-built `new ServerSide()`).
293
+ */
294
+ rotate(): Promise<void>;
262
295
  }
263
296
 
264
297
  declare class ctx<Args extends Record<string, string> = Record<string, string>, SessionType = ServerSide, BodyType = unknown> {
@@ -283,13 +316,33 @@ declare class ctx<Args extends Record<string, string> = Record<string, string>,
283
316
  }
284
317
 
285
318
  type ErrorConfig = {
319
+ /** HTTP status code used for the response. @default 400 */
286
320
  code?: number | undefined;
321
+ /** Message returned in the JSON `error` field; defaults to the status text. */
287
322
  message?: string | undefined;
323
+ /** Redirect target; when set the guard answers `302` instead of an error body. */
288
324
  redirect?: string | undefined;
325
+ /**
326
+ * Extra response headers merged into the response as-is. CORS headers are
327
+ * **not** added automatically: pass `Access-Control-Allow-Origin` here (or
328
+ * mount `cors`) when a browser must read the error response.
329
+ */
289
330
  headers?: Record<string, string> | undefined;
290
331
  error?: (ctx: ctx) => Response;
291
332
  maxSize?: number | undefined;
292
333
  };
334
+ /**
335
+ * Builds a JSON error response (`{ success: false, error, details? }`).
336
+ *
337
+ * Only headers supplied through `config.headers` are emitted (plus
338
+ * `Content-Type`/`Location`); CORS headers are intentionally left to the `cors`
339
+ * guard so a rejection cannot advertise a wildcard grant by itself. Opt in by
340
+ * passing an explicit `Access-Control-Allow-Origin` header in the config.
341
+ *
342
+ * @param config - Status, message, optional headers, or redirect target.
343
+ * @param details - Optional extra payload serialized under `details`.
344
+ * @returns The error `Response`.
345
+ */
293
346
  declare function sendError(config: ErrorConfig, details?: any): Response;
294
347
 
295
348
  type ContentEncodingType = "gzip" | "deflate" | "br" | "zstd" | "none";
@@ -737,12 +790,28 @@ type GuardFactoryHandler<TOptions = void, ExtraCfg = Record<string, any>> = (ctx
737
790
  type GuardConfig = ErrorConfig & {
738
791
  id?: string | undefined;
739
792
  };
740
- type BaseConfig = Omit<ErrorConfig, "code">;
793
+ /**
794
+ * Per-call guard error configuration. Any field that is provided overrides the
795
+ * factory default; omitted fields keep the default (or `400` for `code`).
796
+ */
797
+ type BaseConfig = ErrorConfig;
741
798
  type GuardReturnType = {
742
799
  (ctx: ctx, next: () => Promise<Response> | Response): Promise<Response>;
743
800
  _middlewareId: string;
744
801
  id: string;
745
802
  };
803
+ /**
804
+ * Creates a guard factory that merges a shared default error config with a
805
+ * per-call override.
806
+ *
807
+ * The override wins for every field it defines (`code` included); omitted
808
+ * fields fall back to the default, and `code` finally defaults to `400`.
809
+ * `message` defaults to `"Request Failed"` and `headers` are shallow-merged.
810
+ *
811
+ * @param handler - Guard body invoked with the merged error config.
812
+ * @param defaultConfig - Factory-wide id and default error config.
813
+ * @returns A guard factory accepting `(options?, overrideConfig?)`.
814
+ */
746
815
  declare function createGuard<TOptions = void, ExtraCfg = Record<string, unknown>>(handler: GuardFactoryHandler<TOptions, ExtraCfg>, defaultConfig?: GuardConfig): (options?: TOptions, overrideConfig?: BaseConfig) => GuardReturnType;
747
816
 
748
817
  type Class = new (...args: any[]) => any;
@@ -857,7 +926,14 @@ interface dev {
857
926
  }
858
927
  interface serverOptions {
859
928
  server: Partial<Bun.Serve.Options<any, never>> & dev & {
860
- fn?: (port: number) => void;
929
+ /**
930
+ * Called after Bun has bound the server, so `port` is the port actually
931
+ * in use (including an OS-assigned ephemeral port when `port: 0`).
932
+ *
933
+ * The second argument is the bound `Bun.Server`; its `url` reflects the
934
+ * effective host, port, and `https` scheme when `tls` is set.
935
+ */
936
+ fn?: (port: number, server: Bun.Server<any>) => void;
861
937
  };
862
938
  wss?: RossaWebSocketOptions | undefined;
863
939
  }
@@ -917,6 +993,19 @@ declare class Rossa extends RouterManager {
917
993
  private processRouter;
918
994
  private processWSS;
919
995
  test(req: Request, encoding?: ContentEncodingType): Promise<Response>;
996
+ /**
997
+ * Starts a Bun server for the app.
998
+ *
999
+ * Server options are passed directly (`port`, `hostname`, `tls`, ...). The
1000
+ * returned `Bun.Server` is already bound. When `fn` is supplied it runs after
1001
+ * binding and receives the bound port and server, so `port: 0` resolves to
1002
+ * the OS-assigned port. Without `fn`, the startup log prints the bound URL
1003
+ * (`server.url`), including `https` when `tls` is configured.
1004
+ *
1005
+ * @param server - Bun serve options plus the optional `fn` ready callback.
1006
+ * @param wss - Optional WebSocket handler options and message rate limit.
1007
+ * @returns The bound `Bun.Server` instance.
1008
+ */
920
1009
  serve(server?: serverOptions["server"], wss?: serverOptions["wss"]): Bun.Server<undefined>;
921
1010
  protected errorHandler(res: res, error: any): Response;
922
1011
  }
@@ -1630,7 +1719,10 @@ declare namespace z_d {
1630
1719
  declare const DEFAULT_MAX_SIZE: number;
1631
1720
  /**
1632
1721
  * Parses and validates JSON request bodies for POST, PUT, and PATCH requests.
1633
- * The validated value is stored on the request as `_json`.
1722
+ *
1723
+ * The validated value is stored on `ctx.body` (the same field populated by
1724
+ * `keys([...])`) and, for backwards compatibility, on the request as `_json`.
1725
+ * Handlers should read `ctx.body`; `ctx.req._json` remains supported.
1634
1726
  *
1635
1727
  * @param schema - Schema used to validate the parsed JSON object.
1636
1728
  * @returns A guard factory that accepts a schema and optional error config.
@@ -1658,21 +1750,101 @@ type JwtPayload<T> = T & {
1658
1750
  */
1659
1751
  jti?: string;
1660
1752
  };
1753
+ /** Result of inspecting a token without throwing. */
1754
+ type JwtInspection<T> = {
1755
+ ok: true;
1756
+ payload: JwtPayload<T>;
1757
+ } | {
1758
+ ok: false;
1759
+ reason: "invalid" | "expired";
1760
+ };
1761
+ declare class JwtEngine<T extends Record<string, any> = Record<string, any>> {
1762
+ private readonly secretKey;
1763
+ constructor(secret: string);
1764
+ /**
1765
+ * Generates a signed JWT Access Token.
1766
+ *
1767
+ * A fresh `jti` is always assigned, so signing the same claims twice within
1768
+ * the same clock second still produces two distinct tokens. Any caller
1769
+ * supplied `jti`, `iat`, or `exp` is replaced rather than reused.
1770
+ */
1771
+ sign(payload: T, expiresInMinutes?: number): string;
1772
+ /**
1773
+ * Generates a signed token with a lifetime expressed in seconds.
1774
+ *
1775
+ * Use this for sub-minute lifetimes (tests, short-lived one-off tokens)
1776
+ * without changing the service's minute-based default.
1777
+ */
1778
+ signSeconds(payload: T, expiresInSeconds: number): string;
1779
+ /** Shared token builder; `lifetimeSeconds` is added to the current `iat`. */
1780
+ private build;
1781
+ /**
1782
+ * Verifies the JWT mathematically and reports why an unusable token failed.
1783
+ *
1784
+ * Signature and shape failures are `"invalid"`; a valid signature whose
1785
+ * `exp` has passed is `"expired"`. Never throws.
1786
+ */
1787
+ inspect(token: string): JwtInspection<T>;
1788
+ /**
1789
+ * Verifies the JWT mathematically. Returns payload if valid, or null if expired/tampered.
1790
+ */
1791
+ verify(token: string): JwtPayload<T> | null;
1792
+ /**
1793
+ * Issues a long-lived refresh token.
1794
+ *
1795
+ * Each call produces a distinct token because `sign` assigns a fresh `jti`,
1796
+ * which is what makes rotation + single-use stores replay-safe.
1797
+ */
1798
+ issue(data: T, daysValid?: number): string;
1799
+ }
1661
1800
 
1801
+ /**
1802
+ * Why a refresh token was rejected.
1803
+ *
1804
+ * - `invalid` — missing, malformed, or forged token (bad signature/shape).
1805
+ * - `expired` — validly signed token whose `exp` has passed.
1806
+ * - `reused` — valid, unexpired token that the store no longer considers
1807
+ * available (already consumed or otherwise claimed).
1808
+ */
1809
+ type RefreshRejectionReason = "invalid" | "expired" | "reused";
1810
+ /** Result of a refresh-token consumption attempt. */
1811
+ type RefreshConsumeResult<T extends Record<string, any> = {}> = {
1812
+ ok: true;
1813
+ claims: JwtPayload<T>;
1814
+ } | {
1815
+ ok: false;
1816
+ reason: RefreshRejectionReason;
1817
+ };
1662
1818
  /**
1663
1819
  * Persistence contract for refresh tokens.
1664
1820
  *
1665
1821
  * Implement this interface with any database, key-value store, or external
1666
- * persistence service. `consume` must atomically remove a token and return
1667
- * `true` only for the caller that removed it, preventing concurrent reuse.
1822
+ * persistence service. `consume` must atomically *claim* a token and return
1823
+ * `true` only for the caller that claimed it, preventing concurrent reuse.
1824
+ *
1825
+ * Claim-once does not require deleting the row: a store may keep the row and
1826
+ * stamp `consumed_at`, returning `false` on every later attempt. Keeping the
1827
+ * audit trail is therefore allowed; only the boolean contract matters.
1668
1828
  */
1669
1829
  interface JwtRefreshTokenStore {
1670
1830
  /** Initialize the backing store or its schema when needed. */
1671
1831
  initialize?(): Promise<void>;
1672
1832
  /** Persist a refresh token until its Unix expiration time in milliseconds. */
1673
1833
  save(token: string, expiresAt: number): Promise<void>;
1674
- /** Atomically remove a stored refresh token and report whether it existed. */
1834
+ /**
1835
+ * Atomically claim a stored refresh token and report whether this caller
1836
+ * won. May delete the row or mark it consumed; later calls must return
1837
+ * `false`.
1838
+ */
1675
1839
  consume(token: string): Promise<boolean>;
1840
+ /**
1841
+ * Optional maintenance hook: remove rows that expired before `before`
1842
+ * (Unix milliseconds). Implementations without it keep working; callers
1843
+ * should treat a missing hook as a no-op.
1844
+ *
1845
+ * @returns The number of removed rows, when the store reports it.
1846
+ */
1847
+ deleteExpired?(before: number): Promise<number | void>;
1676
1848
  }
1677
1849
  interface JWTConfig {
1678
1850
  /** Refresh token lifetime in days. Defaults to 7. */
@@ -1693,8 +1865,14 @@ declare class JWTAuthService<T extends Record<string, any> = {}> {
1693
1865
  constructor(refreshTokens: JwtRefreshTokenStore, secret: string, config?: JWTConfig);
1694
1866
  /** Initialize the configured persistence adapter, if it needs initialization. */
1695
1867
  init(): Promise<void>;
1696
- /** Sign an access token using the configured access-token lifetime. */
1697
- sign(payload: T): string;
1868
+ /**
1869
+ * Sign an access token.
1870
+ *
1871
+ * @param payload - Claims to embed.
1872
+ * @param lifetimeSeconds - Optional per-call lifetime in seconds. When
1873
+ * omitted, the service's minute-based `tokenValidity` is used.
1874
+ */
1875
+ sign(payload: T, lifetimeSeconds?: number): string;
1698
1876
  /** Verify an access token and return its claims, or `null` if invalid. */
1699
1877
  verify(token: string): JwtPayload<T> | null;
1700
1878
  /**
@@ -1703,6 +1881,20 @@ declare class JWTAuthService<T extends Record<string, any> = {}> {
1703
1881
  * @returns The token claims when consumption succeeds; otherwise `null`.
1704
1882
  */
1705
1883
  consume(token: string): Promise<JwtPayload<T> | null>;
1884
+ /**
1885
+ * Atomically consume a refresh token and report why it was rejected.
1886
+ *
1887
+ * Expired, malformed, and already-claimed tokens are distinguished without
1888
+ * changing {@link JWTAuthService.consume}'s existing claims/`null` result.
1889
+ */
1890
+ consumeWithReason(token: string): Promise<RefreshConsumeResult<T>>;
1891
+ /**
1892
+ * Remove refresh-token rows that expired before `before` when the store
1893
+ * implements the optional cleanup hook. Stores without it are a no-op.
1894
+ *
1895
+ * @param before - Unix milliseconds cutoff (defaults to now).
1896
+ */
1897
+ deleteExpired(before?: number): Promise<number | void>;
1706
1898
  /** Issue a refresh token, persist it, and return it with a new access token. */
1707
1899
  issue(payload: T): Promise<{
1708
1900
  accessToken: string;
@@ -1711,7 +1903,16 @@ declare class JWTAuthService<T extends Record<string, any> = {}> {
1711
1903
  }
1712
1904
 
1713
1905
  /**
1714
- * Verifies a Bearer access token and stores its decoded claims in `ctx.jwtData`.
1906
+ * Verifies a Bearer access token and stores its decoded claims in
1907
+ * `ctx.jwtData`.
1908
+ *
1909
+ * Every rejection carries `WWW-Authenticate: Bearer` and the guard's 401
1910
+ * body. When composing with {@link jwtRefresh}, mount this guard first so the
1911
+ * refresh guard runs with an already-validated access token:
1912
+ *
1913
+ * ```ts
1914
+ * @use(jwtAuth(service), jwtRefresh(service))
1915
+ * ```
1715
1916
  *
1716
1917
  * @param service - JWT service used to verify the access token.
1717
1918
  * @returns A guard factory that accepts a JWT service and optional error config.
@@ -1719,13 +1920,48 @@ declare class JWTAuthService<T extends Record<string, any> = {}> {
1719
1920
  declare const jwtAuth: (options?: JWTAuthService<any> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1720
1921
  /**
1721
1922
  * Consumes an `x-refresh-token`, issues a replacement token pair, and stores
1722
- * the authenticated claims in `ctx.jwtData` and the new tokens in
1923
+ * the refresh claims in `ctx.data.jwtRefreshData` and the new tokens in
1723
1924
  * `ctx.data.jwtTokens`.
1724
1925
  *
1926
+ * `ctx.jwtData` is only populated with the refresh claims when the access
1927
+ * guard has not already set it; access claims therefore win on combined
1928
+ * routes. When an `Authorization` header is present, the access token is
1929
+ * verified before the refresh token is consumed, so a refresh-first route
1930
+ * does not burn the token when authentication ultimately fails.
1931
+ *
1932
+ * Compose after {@link jwtAuth} where possible, or use {@link jwtRotate} for
1933
+ * a single rotation endpoint:
1934
+ *
1935
+ * ```ts
1936
+ * @use(jwtAuth(service), jwtRefresh(service))
1937
+ * ```
1938
+ *
1725
1939
  * @param service - JWT service used to consume and issue tokens.
1726
1940
  * @returns A guard factory that accepts a JWT service and optional error config.
1727
1941
  */
1728
1942
  declare const jwtRefresh: (options?: JWTAuthService<any> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1943
+ /**
1944
+ * Rotates a session in one guard: verifies the access token when present and
1945
+ * then consumes the refresh token.
1946
+ *
1947
+ * - Access token present and invalid → 401 without consuming the refresh
1948
+ * token, so a failed authentication never burns it.
1949
+ * - Access token present and valid → its claims stay in `ctx.jwtData`.
1950
+ * - Access token absent → refresh claims become `ctx.jwtData` (refresh-only
1951
+ * rotation).
1952
+ *
1953
+ * The refresh claims are always also exposed as `ctx.data.jwtRefreshData` and
1954
+ * the replacement pair as `ctx.data.jwtTokens`. Every 401 carries
1955
+ * `WWW-Authenticate: Bearer`; refresh failures include `error_code`.
1956
+ *
1957
+ * ```ts
1958
+ * @use(jwtRotate(service))
1959
+ * ```
1960
+ *
1961
+ * @param service - JWT service used to verify, consume, and issue tokens.
1962
+ * @returns A guard factory that accepts a JWT service and optional error config.
1963
+ */
1964
+ declare const jwtRotate: (options?: JWTAuthService<any> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1729
1965
 
1730
1966
  /**
1731
1967
  * Logs the request method, path, timestamp, and optional label before continuing.
@@ -1754,6 +1990,10 @@ declare const loggerFN: (options?: ((ff: logFN) => any) | undefined, overrideCon
1754
1990
  * Parses a multipart request and stores its fields and uploaded files in
1755
1991
  * `ctx.form`.
1756
1992
  *
1993
+ * Uploaded `File` objects keep the MIME type declared in their part headers,
1994
+ * including when Bun's parser reports `File.type` as empty. Field names,
1995
+ * file names, sizes, and bytes are unchanged.
1996
+ *
1757
1997
  * @returns A guard factory that parses multipart form data before continuing.
1758
1998
  */
1759
1999
  declare const multipart: (options?: void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
@@ -1889,29 +2129,65 @@ type newSession = {
1889
2129
  readonly?: boolean | undefined;
1890
2130
  isFound?: boolean;
1891
2131
  };
1892
- declare abstract class SessionAuthInterface extends SidGenerator {
2132
+ /**
2133
+ * Abstract session service: signing, cookie serialization, expiration, and
2134
+ * identifier rotation. Subclasses implement the storage hooks.
2135
+ *
2136
+ * @typeParam TData - Shape of the data stored on the session. It types the
2137
+ * resolved session (see {@link SessionInstance}) without casts.
2138
+ */
2139
+ declare abstract class SessionAuthInterface<TData extends Record<string, any> = Record<string, any>> extends SidGenerator {
1893
2140
  config: Required<AuthConfig>;
1894
2141
  constructor(config: AuthConfig, salt?: string);
1895
2142
  init(): Promise<void>;
1896
2143
  /**
1897
2144
  * Verifies the cryptographic signature and opens the session.
1898
2145
  */
1899
- openSession(sid?: string, readonly?: boolean): Promise<ServerSide>;
2146
+ openSession(sid?: string, readonly?: boolean): Promise<SessionInstance<TData>>;
1900
2147
  /** To be implemented by child class: Retrieve from DB */
1901
- fetchSession(sid: string, readonly?: boolean): Promise<any>;
2148
+ fetchSession(sid: string, readonly?: boolean): Promise<SessionInstance<TData>>;
1902
2149
  abstract fetchData(sid: string, readonly?: boolean): Promise<any | undefined>;
1903
2150
  /** To be implemented by child class: Save to DB */
1904
2151
  abstract saveSession(session: ServerSide, headers: Headers): Promise<void>;
1905
2152
  /** To be implemented by child class: Save to DB */
1906
2153
  abstract deleteSession(session: ServerSide, headers: Headers): Promise<void>;
1907
2154
  /** Instantiates a fresh, writable session */
1908
- new({ sid, isFound, readonly, }: newSession): ServerSide;
2155
+ new({ sid, isFound, readonly, }: newSession): SessionInstance<TData>;
1909
2156
  /** Instantiates a read-only session */
1910
- get readonly(): ServerSide;
2157
+ get readonly(): SessionInstance<TData>;
2158
+ /**
2159
+ * Attaches the rotation hook and exposes the proxy that merges the
2160
+ * framework API with the session data.
2161
+ */
2162
+ protected materialize(session: ServerSide<TData>): SessionInstance<TData>;
2163
+ /**
2164
+ * Mints a new signed `sid` for the session and deletes the previous row.
2165
+ *
2166
+ * The guard persists the new row (and sends its cookie) after the handler
2167
+ * returns because the session is marked modified. Used by
2168
+ * {@link ServerSide.rotate}; call that instead of this method directly.
2169
+ *
2170
+ * @param session - Session to re-key. Must not be readonly.
2171
+ */
2172
+ rotateSession(session: ServerSide<TData>): Promise<void>;
2173
+ /**
2174
+ * Deletes a stored row without emitting a cookie for the new session.
2175
+ * A store that fails after deleting the row (for example while serializing
2176
+ * the removal cookie) is still treated as successful.
2177
+ */
2178
+ private removeStoredSession;
1911
2179
  /**
1912
2180
  * Calculates the exact Date object when this session expires.
2181
+ *
2182
+ * Fractional-day lifetimes are preserved: computation is performed in
2183
+ * milliseconds instead of truncating through `Date#setDate`.
1913
2184
  */
1914
2185
  get getSessionExpirationDate(): Date;
2186
+ /**
2187
+ * Calculates the exact Date object when the session cookie expires.
2188
+ *
2189
+ * Fractional-day lifetimes are preserved to the millisecond.
2190
+ */
1915
2191
  get getCookieExpirationDate(): Date;
1916
2192
  /**
1917
2193
  * Verifies if the session is still active and has not expired.
@@ -1927,21 +2203,62 @@ declare abstract class SessionAuthInterface extends SidGenerator {
1927
2203
  /**
1928
2204
  * Extracts the Cookie directly from the Web API Request instance.
1929
2205
  */
1930
- loadHeader(req: Request, readonly?: boolean): Promise<[string | undefined, ServerSide]>;
2206
+ loadHeader(req: Request, readonly?: boolean): Promise<[string | undefined, SessionInstance<TData>]>;
1931
2207
  }
1932
2208
 
1933
- interface SessionConfig {
1934
- auth: SessionAuthInterface;
2209
+ /**
2210
+ * Object form accepted by {@link session}. A readonly mount loads the session
2211
+ * without letting handlers mutate or persist it.
2212
+ */
2213
+ interface SessionMount<TData extends Record<string, any> = Record<string, any>> {
2214
+ /** Session service used to load, save, and delete sessions. */
2215
+ auth: SessionAuthInterface<TData>;
2216
+ /** Discard handler writes and skip persistence. Defaults to `false`. */
1935
2217
  readonly?: boolean;
1936
2218
  }
2219
+ /**
2220
+ * Legacy name for {@link SessionMount}; kept so existing imports keep
2221
+ * compiling.
2222
+ */
2223
+ type SessionConfig = SessionMount;
2224
+ /** A session guard with its data shape attached for editor hints. */
2225
+ type SessionGuard<TData extends Record<string, any>> = GuardReturnType & {
2226
+ /** Phantom marker: the session data shape mounted by this guard. */
2227
+ readonly __sessionData?: TData;
2228
+ };
1937
2229
  /**
1938
2230
  * Loads the request session into `ctx.session` and persists session changes
1939
2231
  * after downstream guards and handlers complete.
1940
2232
  *
1941
- * @param auth - Session service used to load, save, and delete sessions.
1942
- * @returns A guard factory that accepts a session service and optional error config.
2233
+ * Accepts a session service directly (the original form) or a mount object
2234
+ * with a readonly switch:
2235
+ *
2236
+ * ```ts
2237
+ * @use(session(sessions)) // writable
2238
+ * @use(session({ auth: sessions, readonly: true })) // discard writes
2239
+ * @use(session<AccountSession>(sessions)) // typed ctx.session data
2240
+ * ```
2241
+ *
2242
+ * Type the handler context with {@link SessionContext} (or read the session
2243
+ * from the generic mount) to avoid casting `ctx.session` data properties.
2244
+ *
2245
+ * @param mount - Session service, or `{ auth, readonly? }`.
2246
+ * @param overrideConfig - Optional error configuration for persistence errors.
2247
+ * @returns A guard that loads, exposes, and persists the request session.
2248
+ */
2249
+ declare function session<TData extends Record<string, any> = Record<string, any>>(mount: SessionAuthInterface<any> | SessionMount<any>, overrideConfig?: BaseConfig): SessionGuard<TData>;
2250
+ /**
2251
+ * A `ctx` whose `session` is typed with the mounted session data.
2252
+ *
2253
+ * ```ts
2254
+ * import type { SessionContext } from "rossa";
2255
+ *
2256
+ * async post(ctx: SessionContext<AccountSession>) {
2257
+ * ctx.session?.email; // string — no cast
2258
+ * }
2259
+ * ```
1943
2260
  */
1944
- declare const session: (options?: SessionAuthInterface | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2261
+ type SessionContext<TData extends Record<string, any> = Record<string, any>> = ctx<Record<string, string>, SessionInstance<TData>>;
1945
2262
  /** Optional extra check applied to a session that `session()` already resolved. */
1946
2263
  type SessionValidator = (session: ServerSide) => boolean | Promise<boolean>;
1947
2264
  /**
@@ -2030,23 +2347,47 @@ interface UrlValidationOptions {
2030
2347
  allowedKeys?: string[];
2031
2348
  disallowedKeys?: string[];
2032
2349
  noDuplicates?: boolean;
2350
+ /** Block path traversal attempts in the pathname and decoded query string (`../` or `%2e%2e`). */
2033
2351
  sanitizePaths?: boolean;
2034
2352
  patterns?: Record<string, RegExp>;
2035
2353
  }
2036
2354
  /**
2037
2355
  * Validates URL and query limits, query keys, duplicate keys, and path safety.
2038
2356
  *
2357
+ * Traversal markers are rejected in both the decoded pathname and the decoded
2358
+ * query string unless `sanitizePaths` is `false`, so `/search?x=../etc`
2359
+ * answers 400 under the default configuration.
2360
+ *
2039
2361
  * @param options - URL size, query, and path validation rules.
2040
2362
  * @returns A guard factory that accepts validation rules and optional error config.
2041
2363
  */
2042
2364
  declare const validateUrl: (options?: number | void | UrlValidationOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2043
2365
 
2366
+ interface UrlencodedOptions {
2367
+ /**
2368
+ * Reject malformed percent-encoding (`%ZZ`, a bare `%`) and NUL bytes as a
2369
+ * normal guard rejection instead of passing them through verbatim.
2370
+ *
2371
+ * The rejection uses the guard's error config, so the message and status are
2372
+ * configurable: `urlencoded({ strict: true }, { code: 422, message: "..." })`.
2373
+ *
2374
+ * @default false
2375
+ */
2376
+ strict?: boolean;
2377
+ }
2044
2378
  /**
2045
2379
  * Parses an URL-encoded form request and stores its fields in `ctx.form`.
2046
2380
  *
2381
+ * By default malformed percent-encoding and NUL bytes are accepted verbatim
2382
+ * (the lenient behavior of `Request.formData()`). Pass
2383
+ * `urlencoded({ strict: true })` to reject them with the guard's error config
2384
+ * (400 by default).
2385
+ *
2386
+ * @param options - Optional `strict` parsing mode.
2387
+ * @param overrideConfig - Per-call error status/message/headers.
2047
2388
  * @returns A guard factory that parses URL-encoded form data before continuing.
2048
2389
  */
2049
- declare const urlencoded: (options?: void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2390
+ declare const urlencoded: (options?: UrlencodedOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2050
2391
 
2051
2392
  type ScopeDecorator<V> = (value: undefined, context: ClassFieldDecoratorContext<any, V>) => (this: any) => V;
2052
2393
  type ScopeProxy<T> = {
@@ -2087,5 +2428,5 @@ interface ScopeStatic {
2087
2428
  type Scope = _Scope;
2088
2429
  declare const Scope: ScopeStatic;
2089
2430
 
2090
- export { ArraySchema, BooleanSchema, Column, DEFAULT_MAX_SIZE, DatabaseError, DbInspector, DbRepository, DbSchema, Field, ForeignKeyError, JWTAuthService, McpController, Methods, NumberSchema, ObjectSchema, req as Req, res as Res, Rossa, RouterManager, Schema, SchemaError, Scope, ServerSide, SessionAuthInterface, StringSchema, UniqueConstraintError, WSSMAN, Websocket, WssManager, apiKey, auth, authBearer, authorize, contentType, cookies, cors, createGuard, csrf, ctx, deny, errorHandler, getDialect, header, ipFilter, json, jwtAuth, jwtRefresh, keys, logger, loggerFN, mariadbDialect, mcp, multipart, mysqlDialect, postgresDialect, rateLimit, requireSession, route, sanitize, security, sendError, session, smartCache, sqliteDialect, staticFiles, subManager, t, timeout, urlencoded, use, validateForm, validateQuery, validateUrl, wss, z_d as z };
2091
- export type { AnySchema, AuthConfig, BaseConfig, CacheOptions, ColumnType, ContentEncodingType, ContentTypeRules, CorsOptions, CsrfOptions, DbDialectAdapter, DbDialectName, DenyConfig, ErrorConfig, ErrorGuardOptions, FormValidationOptions, GlobalGuard, GuardConfig, GuardFactoryHandler, GuardReturnType, HeaderValidationRules, HttpRouteConfig, HttpRouteMatch, InferSchema, InferShape, Issue, JWTConfig, JwtPayload, JwtRefreshTokenStore, McpOptions, McpServerFactory, QueryValidationOptions, RateLimitOptions, RequireKeysOptions, RossaOptions, RossaWebSocketOptions, SafeParseFailure, SafeParseResult, SafeParseSuccess, SanitizeOptions, SchemaState, SecurityHeadersOptions, SessionConfig, SessionValidator, Shape, StandardIssue, StandardJSONSchemaConverter, StandardJSONSchemaOptions, StandardJSONSchemaTarget, StandardPathSegment, StandardSchema, StandardSchemaProps, StandardTypes, StandardValidateOptions, StandardValidateResult, StaticFilesOptions, TableStats, TopicPublishResult, TopicPublishStatus, UrlValidationOptions, Where, WssBaseController, WssConfig, WssMessageRateLimit, WssRouteConfig, dev, methodsKeys, serverOptions, wssMessage };
2431
+ export { ArraySchema, BooleanSchema, Column, DEFAULT_MAX_SIZE, DatabaseError, DbInspector, DbRepository, DbSchema, Field, ForeignKeyError, JWTAuthService, JwtEngine, McpController, Methods, NumberSchema, ObjectSchema, req as Req, res as Res, Rossa, RouterManager, Schema, SchemaError, Scope, ServerSide, SessionAuthInterface, StringSchema, UniqueConstraintError, WSSMAN, Websocket, WssManager, apiKey, auth, authBearer, authorize, contentType, cookies, cors, createGuard, csrf, ctx, deny, errorHandler, getDialect, header, ipFilter, json, jwtAuth, jwtRefresh, jwtRotate, keys, logger, loggerFN, mariadbDialect, mcp, multipart, mysqlDialect, postgresDialect, rateLimit, requireSession, route, sanitize, security, sendError, session, smartCache, sqliteDialect, staticFiles, subManager, t, timeout, urlencoded, use, validateForm, validateQuery, validateUrl, wss, z_d as z };
2432
+ export type { AnySchema, AuthConfig, BaseConfig, CacheOptions, ColumnType, ContentEncodingType, ContentTypeRules, CorsOptions, CsrfOptions, DbDialectAdapter, DbDialectName, DenyConfig, ErrorConfig, ErrorGuardOptions, FormValidationOptions, GlobalGuard, GuardConfig, GuardFactoryHandler, GuardReturnType, HeaderValidationRules, HttpRouteConfig, HttpRouteMatch, InferSchema, InferShape, Issue, JWTConfig, JwtInspection, JwtPayload, JwtRefreshTokenStore, McpOptions, McpServerFactory, QueryValidationOptions, RateLimitOptions, RefreshConsumeResult, RefreshRejectionReason, RequireKeysOptions, RossaOptions, RossaWebSocketOptions, SafeParseFailure, SafeParseResult, SafeParseSuccess, SanitizeOptions, SchemaState, SecurityHeadersOptions, SessionConfig, SessionContext, SessionGuard, SessionInstance, SessionMount, SessionValidator, Shape, StandardIssue, StandardJSONSchemaConverter, StandardJSONSchemaOptions, StandardJSONSchemaTarget, StandardPathSegment, StandardSchema, StandardSchemaProps, StandardTypes, StandardValidateOptions, StandardValidateResult, StaticFilesOptions, TableStats, TopicPublishResult, TopicPublishStatus, UrlValidationOptions, UrlencodedOptions, Where, WssBaseController, WssConfig, WssMessageRateLimit, WssRouteConfig, dev, methodsKeys, serverOptions, wssMessage };