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/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { Server, SocketAddress, BunFile, ServerWebSocket, WebSocketHandler, SQL } from 'bun';
2
+ import { McpServer, McpRequestContext } from '@modelcontextprotocol/server';
3
+ export { McpRequestContext, McpServer } from '@modelcontextprotocol/server';
2
4
 
3
5
  declare class req {
4
6
  readonly request: Request;
@@ -242,6 +244,8 @@ declare class Heder extends Utils {
242
244
  }
243
245
  type HederPlugin = (h: Heder) => void;
244
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;
245
249
  declare class ServerSide<TData extends Record<string, any> = Record<string, any>> {
246
250
  sid: string;
247
251
  data: TData;
@@ -250,13 +254,44 @@ declare class ServerSide<TData extends Record<string, any> = Record<string, any>
250
254
  isReadOnly: boolean;
251
255
  isFound: boolean;
252
256
  length: number;
257
+ /**
258
+ * Rotation hook supplied by the session service.
259
+ * @internal
260
+ */
261
+ private _rotator?;
253
262
  constructor(sid?: string, initialData?: Partial<TData>, readOnly?: boolean, isNew?: boolean, isFound?: boolean);
254
263
  /**
255
264
  * Generates the dynamic Proxy trapped instance.
256
265
  * We use `this & TData` so TypeScript knows this object contains both
257
266
  * the class methods AND the dynamic user data.
258
267
  */
259
- 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>;
260
295
  }
261
296
 
262
297
  declare class ctx<Args extends Record<string, string> = Record<string, string>, SessionType = ServerSide, BodyType = unknown> {
@@ -281,13 +316,33 @@ declare class ctx<Args extends Record<string, string> = Record<string, string>,
281
316
  }
282
317
 
283
318
  type ErrorConfig = {
319
+ /** HTTP status code used for the response. @default 400 */
284
320
  code?: number | undefined;
321
+ /** Message returned in the JSON `error` field; defaults to the status text. */
285
322
  message?: string | undefined;
323
+ /** Redirect target; when set the guard answers `302` instead of an error body. */
286
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
+ */
287
330
  headers?: Record<string, string> | undefined;
288
331
  error?: (ctx: ctx) => Response;
289
332
  maxSize?: number | undefined;
290
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
+ */
291
346
  declare function sendError(config: ErrorConfig, details?: any): Response;
292
347
 
293
348
  type ContentEncodingType = "gzip" | "deflate" | "br" | "zstd" | "none";
@@ -315,7 +370,14 @@ declare class StaticFileServer {
315
370
  private readonly CACHE_TTL;
316
371
  constructor(resolvedAssetRootPath: string, additionalExtensions?: string[]);
317
372
  isFile(path: string): boolean;
318
- serve(req: req, res: res): Promise<Response>;
373
+ /**
374
+ * Serves the request from this server's root.
375
+ *
376
+ * @param lookupPath - Optional already-decoded path to resolve instead of the
377
+ * request pathname. Scoped mounts use it to serve a prefix-stripped path;
378
+ * when omitted the request URL is decoded exactly as before.
379
+ */
380
+ serve(req: req, res: res, lookupPath?: string): Promise<Response>;
319
381
  }
320
382
 
321
383
  type HeaderObject = Record<string, string>;
@@ -728,15 +790,32 @@ type GuardFactoryHandler<TOptions = void, ExtraCfg = Record<string, any>> = (ctx
728
790
  type GuardConfig = ErrorConfig & {
729
791
  id?: string | undefined;
730
792
  };
731
- 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;
732
798
  type GuardReturnType = {
733
799
  (ctx: ctx, next: () => Promise<Response> | Response): Promise<Response>;
734
800
  _middlewareId: string;
735
801
  id: string;
736
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
+ */
737
815
  declare function createGuard<TOptions = void, ExtraCfg = Record<string, unknown>>(handler: GuardFactoryHandler<TOptions, ExtraCfg>, defaultConfig?: GuardConfig): (options?: TOptions, overrideConfig?: BaseConfig) => GuardReturnType;
738
816
 
739
817
  type Class = new (...args: any[]) => any;
818
+ type RouteHandler = (ctx: ctx) => Promise<Response> | Response;
740
819
  interface WssBaseController {
741
820
  open?(ws: any): void;
742
821
  message(ws: any, message: string | Uint8Array): void;
@@ -768,12 +847,23 @@ declare class RouterManager {
768
847
  wssRoutes: WssRouteConfig[];
769
848
  protected globalGuards: any[];
770
849
  private registeredSignatures;
850
+ private programmaticRoutes;
771
851
  constructor(globalBasePath?: string);
772
852
  use(...guards: GuardReturnType[]): void;
853
+ private fullRoutePath;
773
854
  private compiler;
774
855
  private checkSignature;
775
856
  registerWSS(...ControllerClass: (typeof Websocket<{}>)[]): void;
776
857
  register(...ControllerClass: (typeof Methods)[]): void;
858
+ /**
859
+ * Registers a programmatic HTTP route without a decorated controller class.
860
+ * Used by framework features such as MCP endpoints; a matching programmatic
861
+ * route can be replaced, while a decorated HTTP route at the same path is a
862
+ * collision.
863
+ */
864
+ protected registerHandlerRoute(path: string, handlers: Partial<Record<methodsKeys, RouteHandler>>, options?: {
865
+ replace?: boolean;
866
+ }): void;
777
867
  protected matchWSS(url: string): Partial<WssRouteConfig & {
778
868
  params: HttpRouteMatch["params"];
779
869
  }>;
@@ -783,6 +873,51 @@ declare class RouterManager {
783
873
  getPaths(): string[];
784
874
  }
785
875
 
876
+ /**
877
+ * Base class for decorator-driven MCP endpoints.
878
+ *
879
+ * The framework creates a fresh `McpServer` for each request (named after the
880
+ * controller class) and calls {@link McpController.build} before serving it.
881
+ * Combine it with the `@mcp("/path")` decorator and register it with
882
+ * `app.registerMCP(MyController)`.
883
+ */
884
+ declare abstract class McpController {
885
+ /**
886
+ * Builds the MCP server: register tools, resources, and prompts here.
887
+ * Runs once per request via the SDK factory, so async setup is supported.
888
+ */
889
+ abstract build(server: McpServer): void | Promise<void>;
890
+ }
891
+
892
+ /**
893
+ * Produces a fresh MCP server for one HTTP exchange. Under the SDK's v2
894
+ * handler the factory runs once per request, so per-request tools are possible.
895
+ * Zero-argument factories remain assignable.
896
+ */
897
+ type McpServerFactory = (context: McpRequestContext) => McpServer | Promise<McpServer>;
898
+ interface McpOptions {
899
+ /**
900
+ * Allowed browser `Origin` values. Entries may be full origins
901
+ * (`https://app.example.com`), hostnames (`app.example.com`), or the SDK's
902
+ * extension form (`moz-extension://*`). Full origins are matched exactly
903
+ * (scheme, host, and port); hostnames are matched port-agnostically.
904
+ *
905
+ * Requests without an `Origin` header always pass, as non-browser MCP
906
+ * clients do not send one. When omitted, Origin validation is disabled;
907
+ * production apps should set this or use the CORS and IP guards.
908
+ */
909
+ origin?: string | string[];
910
+ }
911
+
912
+ /**
913
+ * Marks an {@link McpController} subclass as an MCP endpoint.
914
+ *
915
+ * @param path - MCP endpoint path, resolved under the app's `basePath`.
916
+ * @param options - Optional MCP endpoint settings such as allowed origins.
917
+ * @returns A class decorator, used as `@mcp("/mcp")`.
918
+ */
919
+ declare function mcp(path?: string, options?: McpOptions): <TTarget extends abstract new (...args: any[]) => McpController>(target: TTarget, context: ClassDecoratorContext<any>) => void | TTarget;
920
+
786
921
  interface dev {
787
922
  path?: string;
788
923
  hostname?: string;
@@ -791,7 +926,14 @@ interface dev {
791
926
  }
792
927
  interface serverOptions {
793
928
  server: Partial<Bun.Serve.Options<any, never>> & dev & {
794
- 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;
795
937
  };
796
938
  wss?: RossaWebSocketOptions | undefined;
797
939
  }
@@ -813,11 +955,57 @@ declare class Rossa extends RouterManager {
813
955
  fileServer: StaticFileServer;
814
956
  private clientRoot;
815
957
  constructor(options?: RossaOptions);
958
+ /**
959
+ * Mounts an MCP server over Streamable HTTP.
960
+ *
961
+ * Use the decorator idiom for controllers:
962
+ * ```ts
963
+ * @mcp("/mcp")
964
+ * class MyMcp extends McpController {
965
+ * build(server: McpServer) { ... }
966
+ * }
967
+ * app.registerMCP(MyMcp);
968
+ * ```
969
+ *
970
+ * A raw per-request factory remains available when an explicit path is
971
+ * supplied: `app.registerMCP("/mcp", () => new McpServer(...))`.
972
+ *
973
+ * Decorator-provided options are merged with per-call options; a per-call
974
+ * `origin` wins. Global guards added with `use(...)` run before the MCP
975
+ * handler. Registering the same path again replaces the previous MCP route.
976
+ *
977
+ * @param controller - A decorated `McpController` class or instance.
978
+ * @param options - Optional per-call MCP settings.
979
+ */
980
+ registerMCP(controller: McpController, options?: McpOptions): void;
981
+ registerMCP(controller: new () => McpController, options?: McpOptions): void;
982
+ /**
983
+ * Mounts a raw MCP factory at an explicit path.
984
+ *
985
+ * @param path - MCP endpoint path, for example `/mcp`.
986
+ * @param factory - Produces the `McpServer` served for each request.
987
+ * @param options - Optional allowed browser origins.
988
+ */
989
+ registerMCP(path: string, factory: McpServerFactory, options?: McpOptions): void;
990
+ private mountMcp;
816
991
  private get getClientRoot();
817
992
  private pipeline;
818
993
  private processRouter;
819
994
  private processWSS;
820
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
+ */
821
1009
  serve(server?: serverOptions["server"], wss?: serverOptions["wss"]): Bun.Server<undefined>;
822
1010
  protected errorHandler(res: res, error: any): Response;
823
1011
  }
@@ -878,28 +1066,28 @@ interface DbDialectAdapter {
878
1066
  buildColumnType(column: Column): string;
879
1067
  normalizeOperator(operator: string): string;
880
1068
  version(db: SQL): Promise<string>;
881
- createTable(db: SQL, schema: Schema<any>): Promise<void>;
882
- getColumns(db: SQL, schema: Schema<any>): Promise<string[]>;
883
- addColumn(db: SQL, schema: Schema<any>, name: string, type: string): Promise<void>;
884
- dropColumn(db: SQL, schema: Schema<any>, name: string): Promise<void>;
885
- upsert<T extends Record<string, any>>(db: SQL, schema: Schema<T>, data: T, conflictColumn: keyof T): Promise<T | undefined>;
1069
+ createTable(db: SQL, schema: DbSchema<any>): Promise<void>;
1070
+ getColumns(db: SQL, schema: DbSchema<any>): Promise<string[]>;
1071
+ addColumn(db: SQL, schema: DbSchema<any>, name: string, type: string): Promise<void>;
1072
+ dropColumn(db: SQL, schema: DbSchema<any>, name: string): Promise<void>;
1073
+ upsert<T extends Record<string, any>>(db: SQL, schema: DbSchema<T>, data: T, conflictColumn: keyof T): Promise<T | undefined>;
886
1074
  listTables(db: SQL): Promise<string[]>;
887
- dropTable(db: SQL, schema: Schema<any>): Promise<void>;
888
- truncateTable(db: SQL, schema: Schema<any>): Promise<void>;
889
- getTableStats(db: SQL, schema: Schema<any>): Promise<TableStats>;
890
- getTableIndices(db: SQL, schema: Schema<any>): Promise<any[]>;
891
- getTableSchema(db: SQL, schema: Schema<any>): Promise<any[]>;
892
- getTableData(db: SQL, schema: Schema<any>, limit: number, offset: number): Promise<any[]>;
893
- optimize(db: SQL, schema: Schema<any>): Promise<void>;
1075
+ dropTable(db: SQL, schema: DbSchema<any>): Promise<void>;
1076
+ truncateTable(db: SQL, schema: DbSchema<any>): Promise<void>;
1077
+ getTableStats(db: SQL, schema: DbSchema<any>): Promise<TableStats>;
1078
+ getTableIndices(db: SQL, schema: DbSchema<any>): Promise<any[]>;
1079
+ getTableSchema(db: SQL, schema: DbSchema<any>): Promise<any[]>;
1080
+ getTableData(db: SQL, schema: DbSchema<any>, limit: number, offset: number): Promise<any[]>;
1081
+ optimize(db: SQL, schema: DbSchema<any>): Promise<void>;
894
1082
  }
895
1083
 
896
- declare class Schema<T extends Record<string, any>> {
1084
+ declare class DbSchema<T extends Record<string, any>> {
897
1085
  readonly table: string;
898
1086
  private readonly definitions;
899
1087
  readonly dialect: DbDialectAdapter;
900
1088
  constructor(table: string, definitions: Record<keyof T, Column>, dialect: DbDialectAdapter);
901
1089
  entries(): Array<[string, Column]>;
902
- withDialect(dialect: DbDialectAdapter): Schema<T>;
1090
+ withDialect(dialect: DbDialectAdapter): DbSchema<T>;
903
1091
  createSQL(adapter?: DbDialectAdapter): string;
904
1092
  columnDefinitions(adapter?: DbDialectAdapter): Record<string, string>;
905
1093
  get columns(): {
@@ -910,8 +1098,8 @@ declare class Schema<T extends Record<string, any>> {
910
1098
  /** Shared inspection API; SQL-specific operations live in the dialect adapter. */
911
1099
  declare class DbInspector<T extends Record<string, any>> {
912
1100
  private readonly db;
913
- readonly schema: Schema<T>;
914
- constructor(db: SQL, schema: Schema<T>);
1101
+ readonly schema: DbSchema<T>;
1102
+ constructor(db: SQL, schema: DbSchema<T>);
915
1103
  listTables(): Promise<string[]>;
916
1104
  dropTable(): Promise<void>;
917
1105
  truncateTable(): Promise<void>;
@@ -920,8 +1108,8 @@ declare class DbInspector<T extends Record<string, any>> {
920
1108
  getTableSchema(): Promise<any[]>;
921
1109
  getTableData(limit?: number, offset?: number): Promise<any[]>;
922
1110
  optimize(): Promise<void>;
923
- static sqlite<T extends Record<string, any>>(db: SQL, schema: Schema<T>): DbInspector<T>;
924
- static postgres<T extends Record<string, any>>(db: SQL, schema: Schema<T>): DbInspector<T>;
1111
+ static sqlite<T extends Record<string, any>>(db: SQL, schema: DbSchema<T>): DbInspector<T>;
1112
+ static postgres<T extends Record<string, any>>(db: SQL, schema: DbSchema<T>): DbInspector<T>;
925
1113
  }
926
1114
 
927
1115
  type Where<T> = {
@@ -933,8 +1121,8 @@ type Where<T> = {
933
1121
  /** Shared CRUD repository. Dialect-specific statements are delegated to its adapter. */
934
1122
  declare class DbRepository<T extends Record<string, any>> {
935
1123
  private readonly db;
936
- readonly schema: Schema<T>;
937
- constructor(db: SQL, schema: Schema<T>);
1124
+ readonly schema: DbSchema<T>;
1125
+ constructor(db: SQL, schema: DbSchema<T>);
938
1126
  private get dialect();
939
1127
  get inspect(): DbInspector<T>;
940
1128
  withContext(context: SQL): DbRepository<T>;
@@ -1087,6 +1275,28 @@ interface CsrfOptions {
1087
1275
  */
1088
1276
  declare const csrf: (options?: CsrfOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1089
1277
 
1278
+ type DenyConfig = ErrorConfig & {
1279
+ /** When provided, the guard denies only requests where the predicate returns true; otherwise it continues. */
1280
+ when?: (ctx: ctx) => boolean | Promise<boolean>;
1281
+ };
1282
+ /**
1283
+ * Rejects requests with an HTTP error, optionally only when a predicate matches.
1284
+ *
1285
+ * Without `when` every request is denied, which is useful for maintenance
1286
+ * windows or permanently closing a route. With `when`, non-matching requests
1287
+ * continue through the remaining guards and the handler.
1288
+ *
1289
+ * ```ts
1290
+ * @use(deny()) // always 403
1291
+ * @use(deny({ code: 503, message: "Under maintenance" })) // custom status
1292
+ * @use(deny({ when: (ctx) => ctx.req.method === "TRACE" })) // conditional
1293
+ * ```
1294
+ *
1295
+ * @param options - Optional status, message, headers, redirect, and predicate.
1296
+ * @returns A guard factory that denies matching requests and continues otherwise.
1297
+ */
1298
+ declare const deny: (options?: DenyConfig | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1299
+
1090
1300
  interface ErrorGuardOptions {
1091
1301
  /** Log caught errors. Defaults to false. */
1092
1302
  logErrors?: boolean;
@@ -1127,36 +1337,397 @@ type IpOptions = {
1127
1337
  */
1128
1338
  declare const ipFilter: (options?: IpOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1129
1339
 
1130
- declare class SchemaBuilder<T extends Record<string, any>> {
1131
- private schema;
1132
- private rules;
1133
- private defaults;
1134
- string(key: keyof T, defaultValue?: T[keyof T]): this;
1135
- number(key: keyof T, defaultValue?: T[keyof T]): this;
1136
- boolean(key: keyof T, defaultValue?: T[keyof T]): this;
1137
- min(key: keyof T, val: number): this;
1138
- max(key: keyof T, val: number): this;
1139
- email(key: keyof T): this;
1140
- private addRule;
1141
- private noBool;
1142
- private noKey;
1143
- validate(data: any): {
1144
- errors: string[];
1145
- processedData: any;
1146
- };
1147
- private validateObject;
1340
+ /**
1341
+ * TypeScript types for the
1342
+ * {@link https://standardschema.dev/ | Standard Schema} and
1343
+ * Standard JSON Schema interfaces.
1344
+ *
1345
+ * They mirror the vendor-neutral contracts consumed by the MCP SDK. Keeping
1346
+ * local copies avoids a runtime dependency on the SDK from the schema library.
1347
+ */
1348
+ /** A single property key or named path segment in an issue path. */
1349
+ type StandardPathSegment = PropertyKey | {
1350
+ readonly key: PropertyKey;
1351
+ };
1352
+ /** One validation problem in the Standard Schema shape. */
1353
+ interface StandardIssue {
1354
+ /** Human-readable explanation of the failure. */
1355
+ readonly message: string;
1356
+ /** Location of the failing value inside nested data. */
1357
+ readonly path?: ReadonlyArray<StandardPathSegment> | undefined;
1358
+ }
1359
+ /** Successful validation result. */
1360
+ interface StandardSuccessResult<Output> {
1361
+ /** Parsed and normalized output value. */
1362
+ readonly value: Output;
1363
+ readonly issues?: undefined;
1364
+ }
1365
+ /** Failed validation result. */
1366
+ interface StandardFailureResult {
1367
+ /** Every problem found while validating the input. */
1368
+ readonly issues: ReadonlyArray<StandardIssue>;
1369
+ }
1370
+ /** Discriminated union returned by `~standard.validate`. */
1371
+ type StandardValidateResult<Output> = StandardSuccessResult<Output> | StandardFailureResult;
1372
+ /** Options passed to `~standard.validate`. */
1373
+ interface StandardValidateOptions {
1374
+ /** Extra options for the producing library; unused by Rossa schemas. */
1375
+ readonly libraryOptions?: Record<string, unknown> | undefined;
1376
+ }
1377
+ /** JSON Schema dialect requested by a consumer. */
1378
+ type StandardJSONSchemaTarget = "draft-2020-12" | "draft-07" | "openapi-3.0" | (object & string);
1379
+ /** Options passed to the `~standard.jsonSchema` converters. */
1380
+ interface StandardJSONSchemaOptions {
1381
+ /** Target dialect. Rossa emits the same subset for every target. */
1382
+ readonly target?: StandardJSONSchemaTarget | undefined;
1383
+ /** Extra options for the producing library; unused by Rossa schemas. */
1384
+ readonly libraryOptions?: Record<string, unknown> | undefined;
1385
+ }
1386
+ /** Converters that advertise a schema's wire shape as JSON Schema. */
1387
+ interface StandardJSONSchemaConverter {
1388
+ /** JSON Schema describing accepted input values. */
1389
+ readonly input: (options: StandardJSONSchemaOptions) => Record<string, unknown>;
1390
+ /** JSON Schema describing produced output values. */
1391
+ readonly output: (options: StandardJSONSchemaOptions) => Record<string, unknown>;
1392
+ }
1393
+ /** Phantom input/output type pair exposed through `~standard.types`. */
1394
+ interface StandardTypes<Input = unknown, Output = Input> {
1395
+ readonly input: Input;
1396
+ readonly output: Output;
1397
+ }
1398
+ /** Properties attached to every schema under the `~standard` key. */
1399
+ interface StandardSchemaProps<Input = unknown, Output = Input> {
1400
+ readonly version: 1;
1401
+ readonly vendor: string;
1402
+ readonly types?: StandardTypes<Input, Output> | undefined;
1403
+ readonly validate: (value: unknown, options?: StandardValidateOptions | undefined) => StandardValidateResult<Output>;
1404
+ readonly jsonSchema: StandardJSONSchemaConverter;
1405
+ }
1406
+ /** Any value implementing the Standard Schema contract. */
1407
+ interface StandardSchema<Input = unknown, Output = Input> {
1408
+ readonly "~standard": StandardSchemaProps<Input, Output>;
1409
+ }
1410
+
1411
+ /**
1412
+ * A single validation problem found while parsing a value.
1413
+ *
1414
+ * `path` identifies the failing location in nested data (for example
1415
+ * `["address", "city"]` or `["tags", 0]`), while `message` is a human-friendly
1416
+ * explanation written for API consumers.
1417
+ */
1418
+ type Issue = {
1419
+ path: (string | number)[];
1420
+ message: string;
1421
+ };
1422
+ /** Result of a successful {@link Schema.safeParse} call. */
1423
+ type SafeParseSuccess<T> = {
1424
+ success: true;
1425
+ data: T;
1426
+ };
1427
+ /** Result of a failed {@link Schema.safeParse} call. */
1428
+ type SafeParseFailure = {
1429
+ success: false;
1430
+ error: SchemaError;
1431
+ };
1432
+ /** Discriminated union returned by {@link Schema.safeParse}. */
1433
+ type SafeParseResult<T> = SafeParseSuccess<T> | SafeParseFailure;
1434
+ /**
1435
+ * Error thrown by {@link Schema.parse} when validation fails.
1436
+ *
1437
+ * Inspect `issues` for structured, path-aware details, or read `message` for a
1438
+ * short joined summary.
1439
+ */
1440
+ declare class SchemaError extends Error {
1441
+ /** Structured validation problems, in the order they were discovered. */
1442
+ readonly issues: Issue[];
1443
+ constructor(issues: Issue[]);
1444
+ }
1445
+ /**
1446
+ * Any schema, regardless of its output type. Useful for guard options and for
1447
+ * accepting schemas whose exact output is not important.
1448
+ */
1449
+ type AnySchema = Schema<unknown>;
1450
+ /** Resolve the output type carried by a schema. */
1451
+ type InferSchema<S> = S extends Schema<infer Output> ? Output : never;
1452
+ /** Internal, cloneable flags shared by every schema. */
1453
+ interface SchemaState {
1454
+ optional: boolean;
1455
+ nullable: boolean;
1456
+ hasDefault: boolean;
1457
+ defaultValue: unknown;
1458
+ }
1459
+ /**
1460
+ * Base class for every schema.
1461
+ *
1462
+ * It owns the shared modifier flags (`.optional()`, `.nullable()`, `.default()`)
1463
+ * and the parse/safeParse entry points. Concrete schemas implement `_clone` and
1464
+ * `_validate`. All modifier methods return fresh instances, so a schema value
1465
+ * can be safely reused in multiple chains.
1466
+ */
1467
+ declare abstract class Schema<Output> {
1468
+ /** Phantom output type used by `z.infer`. */
1469
+ readonly _output: Output;
1470
+ /**
1471
+ * Standard Schema and Standard JSON Schema interface.
1472
+ *
1473
+ * This is the vendor-neutral contract used by the MCP SDK's `registerTool`
1474
+ * and `registerPrompt`. `validate` runs the same pipeline as
1475
+ * {@link Schema.safeParse}; `jsonSchema` advertises the wire shape.
1476
+ */
1477
+ readonly "~standard": StandardSchemaProps<unknown, Output>;
1478
+ protected readonly _state: SchemaState;
1479
+ constructor(state?: SchemaState);
1480
+ /** Create a fresh copy of this schema, including its modifier flags. */
1481
+ protected abstract _clone(): this;
1482
+ /** Validate a defined, non-null value and return the parsed output. */
1483
+ protected abstract _validate(value: unknown, path: (string | number)[], issues: Issue[]): Output | undefined;
1484
+ /**
1485
+ * Render this schema as JSON Schema.
1486
+ *
1487
+ * The result uses a subset that is valid for draft-07 and draft-2020-12.
1488
+ * Unknown top-level input keys are described with
1489
+ * `additionalProperties: false`; the requested target is ignored.
1490
+ */
1491
+ toJSONSchema(options?: StandardJSONSchemaOptions): Record<string, unknown>;
1492
+ /**
1493
+ * Implement each concrete schema's JSON Schema mapping.
1494
+ *
1495
+ * @internal
1496
+ */
1497
+ protected abstract _jsonSchema(options: StandardJSONSchemaOptions): Record<string, unknown>;
1498
+ /**
1499
+ * Whether the field must appear in an object's `required` list.
1500
+ *
1501
+ * Fields with `.optional()` or `.default(...)` are not required.
1502
+ *
1503
+ * @internal
1504
+ */
1505
+ _isRequired(): boolean;
1506
+ /** Return a copy that also accepts `undefined` (a missing key is allowed). */
1507
+ optional(): Schema<Output | undefined>;
1508
+ /** Return a copy that also accepts `null`, but still rejects `undefined`. */
1509
+ nullable(): Schema<Output | null>;
1510
+ /**
1511
+ * Return a copy that substitutes `value` when the input is `undefined`.
1512
+ * The same default reference is used for every parse.
1513
+ */
1514
+ default(value: Exclude<Output, undefined>): Schema<Exclude<Output, undefined>>;
1515
+ /**
1516
+ * Shared handling for `undefined`, `null`, and defaults before a concrete
1517
+ * schema runs its own type checks.
1518
+ *
1519
+ * @internal
1520
+ */
1521
+ _run(value: unknown, path: (string | number)[], issues: Issue[]): Output | undefined;
1522
+ /**
1523
+ * Validate a value without throwing.
1524
+ *
1525
+ * Unknown object keys are stripped from the returned data. On failure the
1526
+ * result contains a {@link SchemaError} with every collected issue.
1527
+ */
1528
+ safeParse(data: unknown): SafeParseResult<Output>;
1529
+ /**
1530
+ * Validate a value and return the parsed output.
1531
+ *
1532
+ * @throws {SchemaError} When the input does not satisfy this schema.
1533
+ */
1534
+ parse(data: unknown): Output;
1535
+ }
1536
+
1537
+ type StringRule = {
1538
+ kind: "min";
1539
+ value: number;
1540
+ } | {
1541
+ kind: "max";
1542
+ value: number;
1543
+ } | {
1544
+ kind: "email";
1545
+ } | {
1546
+ kind: "trim";
1547
+ };
1548
+ type NumberRule = {
1549
+ kind: "min";
1550
+ value: number;
1551
+ } | {
1552
+ kind: "max";
1553
+ value: number;
1554
+ } | {
1555
+ kind: "int";
1556
+ };
1557
+ interface StringOptions {
1558
+ coerce?: boolean;
1559
+ rules?: StringRule[];
1560
+ state?: SchemaState;
1561
+ }
1562
+ interface NumberOptions {
1563
+ coerce?: boolean;
1564
+ rules?: NumberRule[];
1565
+ state?: SchemaState;
1566
+ }
1567
+ interface BooleanOptions {
1568
+ coerce?: boolean;
1569
+ state?: SchemaState;
1570
+ }
1571
+ /** Schema for text values, with `.min`, `.max`, and `.email` rules. */
1572
+ declare class StringSchema extends Schema<string> {
1573
+ private readonly _rules;
1574
+ private readonly _coerce;
1575
+ constructor(options?: StringOptions);
1576
+ protected _clone(): this;
1577
+ /** Require at least `length` characters. */
1578
+ min(length: number): this;
1579
+ /** Require at most `length` characters. */
1580
+ max(length: number): this;
1581
+ /** Require a conventional email address (`local@domain.tld`). */
1582
+ email(): this;
1583
+ /**
1584
+ * Trim leading and trailing whitespace before validation.
1585
+ *
1586
+ * `.min`, `.max`, and `.email` see the trimmed value, and the parsed output
1587
+ * is trimmed.
1588
+ */
1589
+ trim(): this;
1590
+ private _withRule;
1591
+ protected _jsonSchema(_options: StandardJSONSchemaOptions): Record<string, unknown>;
1592
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): string | undefined;
1593
+ }
1594
+ /** Schema for numeric values, with `.min`, `.max`, and `.int` rules. */
1595
+ declare class NumberSchema extends Schema<number> {
1596
+ private readonly _rules;
1597
+ private readonly _coerce;
1598
+ constructor(options?: NumberOptions);
1599
+ protected _clone(): this;
1600
+ /** Require a value greater than or equal to `minimum`. */
1601
+ min(minimum: number): this;
1602
+ /** Require a value less than or equal to `maximum`. */
1603
+ max(maximum: number): this;
1604
+ /** Require a whole number. */
1605
+ int(): this;
1606
+ private _withRule;
1607
+ protected _jsonSchema(_options: StandardJSONSchemaOptions): Record<string, unknown>;
1608
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): number | undefined;
1609
+ }
1610
+ /** Schema for boolean values. */
1611
+ declare class BooleanSchema extends Schema<boolean> {
1612
+ private readonly _coerce;
1613
+ constructor(options?: BooleanOptions);
1614
+ protected _clone(): this;
1615
+ protected _jsonSchema(_options: StandardJSONSchemaOptions): Record<string, unknown>;
1616
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): boolean | undefined;
1617
+ }
1618
+
1619
+ /** A map of field names to schemas. */
1620
+ type Shape = Record<string, AnySchema>;
1621
+ type OptionalShapeKeys<TShape extends Shape> = {
1622
+ [K in keyof TShape]: undefined extends InferSchema<TShape[K]> ? K : never;
1623
+ }[keyof TShape];
1624
+ /** Output type produced by an object schema, with optional fields preserved. */
1625
+ type InferShape<TShape extends Shape> = {
1626
+ [K in Exclude<keyof TShape, OptionalShapeKeys<TShape>>]: InferSchema<TShape[K]>;
1627
+ } & {
1628
+ [K in OptionalShapeKeys<TShape>]?: Exclude<InferSchema<TShape[K]>, undefined>;
1629
+ };
1630
+ type ArrayRule = {
1631
+ kind: "min";
1632
+ value: number;
1633
+ } | {
1634
+ kind: "max";
1635
+ value: number;
1636
+ };
1637
+ interface ArrayOptions {
1638
+ rules?: ArrayRule[];
1639
+ state?: SchemaState;
1640
+ }
1641
+ /** Schema for arrays whose items share a single item schema. */
1642
+ declare class ArraySchema<Item extends AnySchema> extends Schema<InferSchema<Item>[]> {
1643
+ private readonly _item;
1644
+ private readonly _rules;
1645
+ constructor(item: Item, options?: ArrayOptions);
1646
+ protected _clone(): this;
1647
+ /** Require at least `length` items. */
1648
+ min(length: number): this;
1649
+ /** Require at most `length` items. */
1650
+ max(length: number): this;
1651
+ private _withRule;
1652
+ protected _jsonSchema(options: StandardJSONSchemaOptions): Record<string, unknown>;
1653
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): InferSchema<Item>[] | undefined;
1654
+ }
1655
+ interface ObjectOptions {
1656
+ state?: SchemaState;
1657
+ }
1658
+ /**
1659
+ * Schema for objects with a fixed shape.
1660
+ *
1661
+ * Unknown input keys are stripped from the parsed output (zod `.strip()`
1662
+ * behavior).
1663
+ */
1664
+ declare class ObjectSchema<TShape extends Shape> extends Schema<InferShape<TShape>> {
1665
+ /** Field schemas keyed by output property name. */
1666
+ readonly shape: TShape;
1667
+ constructor(shape: TShape, options?: ObjectOptions);
1668
+ protected _clone(): this;
1669
+ protected _jsonSchema(options: StandardJSONSchemaOptions): Record<string, unknown>;
1670
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): InferShape<TShape> | undefined;
1671
+ }
1672
+
1673
+ /** Create a text schema. */
1674
+ declare const string: () => StringSchema;
1675
+ /** Create a numeric schema. */
1676
+ declare const number: () => NumberSchema;
1677
+ /** Create a boolean schema. */
1678
+ declare const boolean: () => BooleanSchema;
1679
+ /** Create an array schema for the given item schema. */
1680
+ declare const array: <Item extends AnySchema>(item: Item) => ArraySchema<Item>;
1681
+ /** Create an object schema with a fixed shape. */
1682
+ declare const object: <TShape extends Shape>(shape: TShape) => ObjectSchema<TShape>;
1683
+ /**
1684
+ * Coercing variants that convert raw query/form strings before validation.
1685
+ * Non-string inputs pass through to the underlying type checks.
1686
+ */
1687
+ declare const coerce: {
1688
+ /** Create a text schema that stringifies numbers and booleans. */
1689
+ string: () => StringSchema;
1690
+ /** Create a numeric schema that converts numeric strings with `Number()`. */
1691
+ number: () => NumberSchema;
1692
+ /**
1693
+ * Create a boolean schema that accepts `"true"`/`"1"` and
1694
+ * `"false"`/`"0"` case-insensitively.
1695
+ */
1696
+ boolean: () => BooleanSchema;
1697
+ };
1698
+ /**
1699
+ * Resolve the output type of a schema.
1700
+ *
1701
+ * ```ts
1702
+ * const User = z.object({ name: z.string() });
1703
+ * type User = z.infer<typeof User>; // { name: string }
1704
+ * ```
1705
+ */
1706
+ type Infer<S extends AnySchema> = InferSchema<S>;
1707
+
1708
+ declare const z_d_array: typeof array;
1709
+ declare const z_d_boolean: typeof boolean;
1710
+ declare const z_d_coerce: typeof coerce;
1711
+ declare const z_d_number: typeof number;
1712
+ declare const z_d_object: typeof object;
1713
+ declare const z_d_string: typeof string;
1714
+ declare namespace z_d {
1715
+ export { z_d_array as array, z_d_boolean as boolean, z_d_coerce as coerce, z_d_number as number, z_d_object as object, z_d_string as string };
1716
+ export type { Infer as infer };
1148
1717
  }
1149
- declare function z<T extends Record<string, any>>(): SchemaBuilder<T>;
1150
1718
 
1151
1719
  declare const DEFAULT_MAX_SIZE: number;
1152
1720
  /**
1153
1721
  * Parses and validates JSON request bodies for POST, PUT, and PATCH requests.
1154
- * 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.
1155
1726
  *
1156
1727
  * @param schema - Schema used to validate the parsed JSON object.
1157
1728
  * @returns A guard factory that accepts a schema and optional error config.
1158
1729
  */
1159
- declare const json: (options?: SchemaBuilder<any> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1730
+ declare const json: (options?: AnySchema | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1160
1731
  interface RequireKeysOptions {
1161
1732
  keys: string[];
1162
1733
  }
@@ -1172,22 +1743,108 @@ declare const keys: (options?: string[] | undefined, overrideConfig?: BaseConfig
1172
1743
  type JwtPayload<T> = T & {
1173
1744
  iat: number;
1174
1745
  exp: number;
1746
+ /**
1747
+ * Unique token identifier assigned on every signature.
1748
+ *
1749
+ * Optional only so tokens issued before this claim existed remain readable.
1750
+ */
1751
+ jti?: string;
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";
1175
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
+ }
1176
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
+ };
1177
1818
  /**
1178
1819
  * Persistence contract for refresh tokens.
1179
1820
  *
1180
1821
  * Implement this interface with any database, key-value store, or external
1181
- * persistence service. `consume` must atomically remove a token and return
1182
- * `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.
1183
1828
  */
1184
1829
  interface JwtRefreshTokenStore {
1185
1830
  /** Initialize the backing store or its schema when needed. */
1186
1831
  initialize?(): Promise<void>;
1187
1832
  /** Persist a refresh token until its Unix expiration time in milliseconds. */
1188
1833
  save(token: string, expiresAt: number): Promise<void>;
1189
- /** 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
+ */
1190
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>;
1191
1848
  }
1192
1849
  interface JWTConfig {
1193
1850
  /** Refresh token lifetime in days. Defaults to 7. */
@@ -1208,8 +1865,14 @@ declare class JWTAuthService<T extends Record<string, any> = {}> {
1208
1865
  constructor(refreshTokens: JwtRefreshTokenStore, secret: string, config?: JWTConfig);
1209
1866
  /** Initialize the configured persistence adapter, if it needs initialization. */
1210
1867
  init(): Promise<void>;
1211
- /** Sign an access token using the configured access-token lifetime. */
1212
- 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;
1213
1876
  /** Verify an access token and return its claims, or `null` if invalid. */
1214
1877
  verify(token: string): JwtPayload<T> | null;
1215
1878
  /**
@@ -1218,6 +1881,20 @@ declare class JWTAuthService<T extends Record<string, any> = {}> {
1218
1881
  * @returns The token claims when consumption succeeds; otherwise `null`.
1219
1882
  */
1220
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>;
1221
1898
  /** Issue a refresh token, persist it, and return it with a new access token. */
1222
1899
  issue(payload: T): Promise<{
1223
1900
  accessToken: string;
@@ -1226,7 +1903,16 @@ declare class JWTAuthService<T extends Record<string, any> = {}> {
1226
1903
  }
1227
1904
 
1228
1905
  /**
1229
- * 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
+ * ```
1230
1916
  *
1231
1917
  * @param service - JWT service used to verify the access token.
1232
1918
  * @returns A guard factory that accepts a JWT service and optional error config.
@@ -1234,13 +1920,48 @@ declare class JWTAuthService<T extends Record<string, any> = {}> {
1234
1920
  declare const jwtAuth: (options?: JWTAuthService<any> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1235
1921
  /**
1236
1922
  * Consumes an `x-refresh-token`, issues a replacement token pair, and stores
1237
- * the authenticated claims in `ctx.jwtData` and the new tokens in
1923
+ * the refresh claims in `ctx.data.jwtRefreshData` and the new tokens in
1238
1924
  * `ctx.data.jwtTokens`.
1239
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
+ *
1240
1939
  * @param service - JWT service used to consume and issue tokens.
1241
1940
  * @returns A guard factory that accepts a JWT service and optional error config.
1242
1941
  */
1243
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;
1244
1965
 
1245
1966
  /**
1246
1967
  * Logs the request method, path, timestamp, and optional label before continuing.
@@ -1248,7 +1969,7 @@ declare const jwtRefresh: (options?: JWTAuthService<any> | undefined, overrideCo
1248
1969
  * @param label - Optional text included in the log entry.
1249
1970
  * @returns A guard factory that accepts a label and optional error config.
1250
1971
  */
1251
- declare const logger: (options?: void | string | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1972
+ declare const logger: (options?: string | void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1252
1973
  type logFN = {
1253
1974
  ctx: ctx;
1254
1975
  res: Response;
@@ -1269,15 +1990,23 @@ declare const loggerFN: (options?: ((ff: logFN) => any) | undefined, overrideCon
1269
1990
  * Parses a multipart request and stores its fields and uploaded files in
1270
1991
  * `ctx.form`.
1271
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
+ *
1272
1997
  * @returns A guard factory that parses multipart form data before continuing.
1273
1998
  */
1274
1999
  declare const multipart: (options?: void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1275
2000
 
1276
- interface QueryValidationOptions<T extends Record<string, any>> {
1277
- schema: SchemaBuilder<T>;
2001
+ /** Options accepted by {@link validateQuery}. */
2002
+ interface QueryValidationOptions {
2003
+ /** Schema used to validate and coerce query parameters. */
2004
+ schema: AnySchema;
1278
2005
  }
1279
- interface FormValidationOptions<T extends Record<string, any>> {
1280
- schema: SchemaBuilder<T>;
2006
+ /** Options accepted by {@link validateForm}. */
2007
+ interface FormValidationOptions {
2008
+ /** Schema used to validate and coerce form fields. */
2009
+ schema: AnySchema;
1281
2010
  }
1282
2011
  /**
1283
2012
  * Validates and coerces URL query parameters against a schema, then stores the
@@ -1286,7 +2015,7 @@ interface FormValidationOptions<T extends Record<string, any>> {
1286
2015
  * @param schema - Schema used to validate and coerce query values.
1287
2016
  * @returns A guard factory that accepts the schema and optional error config.
1288
2017
  */
1289
- declare const validateQuery: (options?: SchemaBuilder<{}> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2018
+ declare const validateQuery: (options?: AnySchema | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1290
2019
  /**
1291
2020
  * Validates multipart or URL-encoded form fields against a schema and stores
1292
2021
  * the processed result in `ctx.form`.
@@ -1294,7 +2023,7 @@ declare const validateQuery: (options?: SchemaBuilder<{}> | undefined, overrideC
1294
2023
  * @param schema - Schema used to validate and coerce form values.
1295
2024
  * @returns A guard factory that accepts the schema and optional error config.
1296
2025
  */
1297
- declare const validateForm: (options?: SchemaBuilder<{}> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2026
+ declare const validateForm: (options?: AnySchema | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1298
2027
 
1299
2028
  interface RateLimitOptions {
1300
2029
  /** Maximum number of connections/requests allowed within the window. @default 100 */
@@ -1400,29 +2129,65 @@ type newSession = {
1400
2129
  readonly?: boolean | undefined;
1401
2130
  isFound?: boolean;
1402
2131
  };
1403
- 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 {
1404
2140
  config: Required<AuthConfig>;
1405
2141
  constructor(config: AuthConfig, salt?: string);
1406
2142
  init(): Promise<void>;
1407
2143
  /**
1408
2144
  * Verifies the cryptographic signature and opens the session.
1409
2145
  */
1410
- openSession(sid?: string, readonly?: boolean): Promise<ServerSide>;
2146
+ openSession(sid?: string, readonly?: boolean): Promise<SessionInstance<TData>>;
1411
2147
  /** To be implemented by child class: Retrieve from DB */
1412
- fetchSession(sid: string, readonly?: boolean): Promise<any>;
2148
+ fetchSession(sid: string, readonly?: boolean): Promise<SessionInstance<TData>>;
1413
2149
  abstract fetchData(sid: string, readonly?: boolean): Promise<any | undefined>;
1414
2150
  /** To be implemented by child class: Save to DB */
1415
2151
  abstract saveSession(session: ServerSide, headers: Headers): Promise<void>;
1416
2152
  /** To be implemented by child class: Save to DB */
1417
2153
  abstract deleteSession(session: ServerSide, headers: Headers): Promise<void>;
1418
2154
  /** Instantiates a fresh, writable session */
1419
- new({ sid, isFound, readonly, }: newSession): ServerSide;
2155
+ new({ sid, isFound, readonly, }: newSession): SessionInstance<TData>;
1420
2156
  /** Instantiates a read-only session */
1421
- 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;
1422
2179
  /**
1423
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`.
1424
2184
  */
1425
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
+ */
1426
2191
  get getCookieExpirationDate(): Date;
1427
2192
  /**
1428
2193
  * Verifies if the session is still active and has not expired.
@@ -1438,29 +2203,132 @@ declare abstract class SessionAuthInterface extends SidGenerator {
1438
2203
  /**
1439
2204
  * Extracts the Cookie directly from the Web API Request instance.
1440
2205
  */
1441
- loadHeader(req: Request, readonly?: boolean): Promise<[string | undefined, ServerSide]>;
2206
+ loadHeader(req: Request, readonly?: boolean): Promise<[string | undefined, SessionInstance<TData>]>;
1442
2207
  }
1443
2208
 
1444
- interface SessionConfig {
1445
- 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`. */
1446
2217
  readonly?: boolean;
1447
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
+ };
1448
2229
  /**
1449
2230
  * Loads the request session into `ctx.session` and persists session changes
1450
2231
  * after downstream guards and handlers complete.
1451
2232
  *
1452
- * @param auth - Session service used to load, save, and delete sessions.
1453
- * @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
+ * ```
2260
+ */
2261
+ type SessionContext<TData extends Record<string, any> = Record<string, any>> = ctx<Record<string, string>, SessionInstance<TData>>;
2262
+ /** Optional extra check applied to a session that `session()` already resolved. */
2263
+ type SessionValidator = (session: ServerSide) => boolean | Promise<boolean>;
2264
+ /**
2265
+ * Rejects requests that do not carry a valid, stored session.
2266
+ *
2267
+ * A session counts as authenticated only when the cookie signature is valid,
2268
+ * the row still exists in the store, it has not expired, and it is not a
2269
+ * freshly created anonymous session. Compose this guard after
2270
+ * `session(service)` — it reads `ctx.session` and never loads the cookie
2271
+ * itself:
2272
+ *
2273
+ * ```ts
2274
+ * @use(session(service), requireSession())
2275
+ * ```
2276
+ *
2277
+ * Pass a validator to add an application-level check, for example an identity
2278
+ * field written during login. Session data keys are not part of the
2279
+ * `ServerSide` type, so cast to your session shape:
2280
+ *
2281
+ * ```ts
2282
+ * @use(session(service), requireSession((s) => typeof (s as AccountSession).userId === "number"))
2283
+ * ```
2284
+ *
2285
+ * @param validator - Optional additional check for the resolved session.
2286
+ * @returns A guard factory that returns 401 and continues otherwise.
1454
2287
  */
1455
- declare const session: (options?: SessionAuthInterface | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2288
+ declare const requireSession: (options?: SessionValidator | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1456
2289
 
2290
+ /** Configuration for a {@link staticFiles} mount. */
2291
+ interface StaticFilesOptions {
2292
+ /**
2293
+ * Restricts this mount to request paths under the given prefix. The decoded
2294
+ * pathname is compared at a path-segment boundary, so `/assets` matches
2295
+ * `/assets` and `/assets/app.js` but not `/assetsfoo.png`. Requests outside
2296
+ * the prefix fall through to the remaining guards and routes, which keeps
2297
+ * authentication and route handling reachable. Omit it to intercept every
2298
+ * file-like path, as a global static mount does.
2299
+ */
2300
+ prefix?: string;
2301
+ /**
2302
+ * Directory this mount serves from. Relative paths resolve against
2303
+ * `process.cwd()`; absolute paths are used as-is. When set, the mount uses a
2304
+ * dedicated static file server instead of the app-wide `clientPath` server.
2305
+ * With a `prefix`, the prefix is stripped before the lookup, so
2306
+ * `/files/logo.png` maps to `<root>/logo.png`. Without a prefix the full
2307
+ * request path is used.
2308
+ */
2309
+ root?: string;
2310
+ /**
2311
+ * Additional file extensions recognized by this mount, with or without a
2312
+ * leading dot. They extend the built-in extension list but do not replace
2313
+ * the app-wide `fileExtensions` configuration.
2314
+ */
2315
+ extensions?: string[];
2316
+ }
1457
2317
  /**
1458
- * Serves requests for file-like paths through the configured static file server.
1459
- * Only GET and HEAD requests are intercepted.
2318
+ * Serves requests for file-like paths through a static file server.
2319
+ * Only GET and HEAD requests are intercepted; HEAD responses keep the file
2320
+ * headers but drop the body.
2321
+ *
2322
+ * Without options it behaves like a global mount: every recognized file-like
2323
+ * path is served from the app-wide `clientPath` server before route guards run.
2324
+ * Pass `prefix` and/or `root` to scope a mount, for example
2325
+ * `staticFiles({ prefix: "/files", root: "./private-files" })` registered
2326
+ * behind an authentication guard.
1460
2327
  *
2328
+ * @param options - Optional prefix, root, and extension configuration.
1461
2329
  * @returns A guard factory that serves static assets before route handling.
1462
2330
  */
1463
- declare const staticFiles: (options?: void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2331
+ declare const staticFiles: (options?: StaticFilesOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1464
2332
 
1465
2333
  /**
1466
2334
  * Stops waiting for downstream work after the configured number of milliseconds.
@@ -1479,23 +2347,47 @@ interface UrlValidationOptions {
1479
2347
  allowedKeys?: string[];
1480
2348
  disallowedKeys?: string[];
1481
2349
  noDuplicates?: boolean;
2350
+ /** Block path traversal attempts in the pathname and decoded query string (`../` or `%2e%2e`). */
1482
2351
  sanitizePaths?: boolean;
1483
2352
  patterns?: Record<string, RegExp>;
1484
2353
  }
1485
2354
  /**
1486
2355
  * Validates URL and query limits, query keys, duplicate keys, and path safety.
1487
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
+ *
1488
2361
  * @param options - URL size, query, and path validation rules.
1489
2362
  * @returns A guard factory that accepts validation rules and optional error config.
1490
2363
  */
1491
- declare const validateUrl: (options?: void | number | UrlValidationOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2364
+ declare const validateUrl: (options?: number | void | UrlValidationOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1492
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
+ }
1493
2378
  /**
1494
2379
  * Parses an URL-encoded form request and stores its fields in `ctx.form`.
1495
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.
1496
2388
  * @returns A guard factory that parses URL-encoded form data before continuing.
1497
2389
  */
1498
- declare const urlencoded: (options?: void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2390
+ declare const urlencoded: (options?: UrlencodedOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1499
2391
 
1500
2392
  type ScopeDecorator<V> = (value: undefined, context: ClassFieldDecoratorContext<any, V>) => (this: any) => V;
1501
2393
  type ScopeProxy<T> = {
@@ -1536,5 +2428,5 @@ interface ScopeStatic {
1536
2428
  type Scope = _Scope;
1537
2429
  declare const Scope: ScopeStatic;
1538
2430
 
1539
- export { Column, DEFAULT_MAX_SIZE, DatabaseError, DbInspector, DbRepository, Field, ForeignKeyError, JWTAuthService, Methods, req as Req, res as Res, Rossa, RouterManager, Schema, SchemaBuilder, Scope, ServerSide, SessionAuthInterface, UniqueConstraintError, WSSMAN, Websocket, WssManager, apiKey, auth, authBearer, authorize, contentType, cookies, cors, createGuard, csrf, ctx, errorHandler, getDialect, header, ipFilter, json, jwtAuth, jwtRefresh, keys, logger, loggerFN, mariadbDialect, multipart, mysqlDialect, postgresDialect, rateLimit, route, sanitize, security, sendError, session, smartCache, sqliteDialect, staticFiles, subManager, t, timeout, urlencoded, use, validateForm, validateQuery, validateUrl, wss, z };
1540
- export type { AuthConfig, BaseConfig, CacheOptions, ColumnType, ContentEncodingType, ContentTypeRules, CorsOptions, CsrfOptions, DbDialectAdapter, DbDialectName, ErrorConfig, ErrorGuardOptions, FormValidationOptions, GlobalGuard, GuardConfig, GuardFactoryHandler, GuardReturnType, HeaderValidationRules, HttpRouteConfig, HttpRouteMatch, JWTConfig, JwtPayload, JwtRefreshTokenStore, QueryValidationOptions, RateLimitOptions, RequireKeysOptions, RossaOptions, RossaWebSocketOptions, SanitizeOptions, SecurityHeadersOptions, SessionConfig, 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 };