@mednours/backon 0.7.1 → 0.9.0

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.
Files changed (66) hide show
  1. package/dist/auth-core.d.ts +36 -5
  2. package/dist/auth-core.d.ts.map +1 -1
  3. package/dist/cache-control-core.d.ts +17 -0
  4. package/dist/cache-control-core.d.ts.map +1 -0
  5. package/dist/cache-control.d.ts +9 -0
  6. package/dist/cache-control.d.ts.map +1 -0
  7. package/dist/create-app.d.ts +8 -0
  8. package/dist/create-app.d.ts.map +1 -1
  9. package/dist/define-route.d.ts +1 -1
  10. package/dist/define-route.d.ts.map +1 -1
  11. package/dist/error.d.ts.map +1 -1
  12. package/dist/express/cache-control.d.ts +9 -0
  13. package/dist/express/cache-control.d.ts.map +1 -0
  14. package/dist/express/create-app.d.ts +5 -0
  15. package/dist/express/create-app.d.ts.map +1 -1
  16. package/dist/express/define-route.d.ts +1 -1
  17. package/dist/express/define-route.d.ts.map +1 -1
  18. package/dist/express/index.d.ts +4 -1
  19. package/dist/express/index.d.ts.map +1 -1
  20. package/dist/express/index.js +181 -32
  21. package/dist/express/openapi.d.ts.map +1 -1
  22. package/dist/express/rate-limit.d.ts +6 -0
  23. package/dist/express/rate-limit.d.ts.map +1 -1
  24. package/dist/express/require-auth.d.ts +2 -11
  25. package/dist/express/require-auth.d.ts.map +1 -1
  26. package/dist/express/router-registry.d.ts.map +1 -1
  27. package/dist/express/stream.d.ts.map +1 -1
  28. package/dist/express/upload.d.ts.map +1 -1
  29. package/dist/index.d.ts +5 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +216 -43
  32. package/dist/openapi-core.d.ts +1 -1
  33. package/dist/openapi-core.d.ts.map +1 -1
  34. package/dist/openapi.d.ts.map +1 -1
  35. package/dist/rate-limit-core.d.ts +5 -1
  36. package/dist/rate-limit-core.d.ts.map +1 -1
  37. package/dist/rate-limit.d.ts +6 -0
  38. package/dist/rate-limit.d.ts.map +1 -1
  39. package/dist/require-auth.d.ts +3 -14
  40. package/dist/require-auth.d.ts.map +1 -1
  41. package/dist/serve.d.ts +12 -1
  42. package/dist/serve.d.ts.map +1 -1
  43. package/dist/stream.d.ts.map +1 -1
  44. package/dist/upload.d.ts.map +1 -1
  45. package/dist/websocket.d.ts.map +1 -1
  46. package/package.json +13 -14
  47. package/src/auth-core.ts +108 -9
  48. package/src/cache-control-core.ts +32 -0
  49. package/src/cache-control.ts +18 -0
  50. package/src/create-app.ts +25 -9
  51. package/src/define-route.ts +17 -5
  52. package/src/express/cache-control.ts +22 -0
  53. package/src/express/create-app.ts +24 -6
  54. package/src/express/define-route.ts +4 -4
  55. package/src/express/index.ts +5 -1
  56. package/src/express/openapi.ts +7 -5
  57. package/src/express/rate-limit.ts +15 -4
  58. package/src/express/require-auth.ts +11 -14
  59. package/src/express/router-registry.ts +6 -2
  60. package/src/index.ts +6 -1
  61. package/src/openapi-core.ts +24 -7
  62. package/src/openapi.ts +8 -3
  63. package/src/rate-limit-core.ts +29 -1
  64. package/src/rate-limit.ts +15 -6
  65. package/src/require-auth.ts +10 -17
  66. package/src/serve.ts +48 -16
@@ -1,11 +1,9 @@
1
1
  import type { JWTPayload } from "hono/utils/jwt/types";
2
2
  import type { SignatureAlgorithm } from "hono/utils/jwt/jwa";
3
3
  /**
4
- * Shared by the Hono and Express requireAuth() middleware — the actual JWT
5
- * verification is identical, only how each framework reads the incoming
6
- * request and reports failure differs. Built on hono/jwt's verify() rather
7
- * than a new dependency, since hono is already a hard dependency of backon
8
- * regardless of which framework (Hono or Express) a project picked.
4
+ * Shared by the Hono and Express auth helpers — JWT signing/verification
5
+ * and cookie token extraction are identical across frameworks, built on
6
+ * hono/jwt and Web Crypto so no extra dependencies are needed.
9
7
  */
10
8
  export interface VerifyJwtOptions {
11
9
  /** Secret used to verify the token's signature. */
@@ -17,9 +15,42 @@ export interface VerifyJwtOptions {
17
15
  * algorithm the server chose, never one the token claims for itself.
18
16
  */
19
17
  alg?: SignatureAlgorithm;
18
+ /**
19
+ * Optional cookie name to fall back to when no `Authorization: Bearer`
20
+ * header is present (e.g. `"authToken"`).
21
+ */
22
+ cookieName?: string;
23
+ /**
24
+ * When set alongside `cookieName`, verifies Hono-style signed cookies
25
+ * (`<value>.<base64-hmac-sha256>`) using this secret before verifying the JWT.
26
+ */
27
+ cookieSecret?: string;
20
28
  }
29
+ export interface SignJwtOptions {
30
+ /** Secret used to sign the token. */
31
+ secret: string;
32
+ /** Algorithm to sign with. Defaults to HS256. */
33
+ alg?: SignatureAlgorithm;
34
+ /**
35
+ * Optional lifetime in seconds. When set and `payload.exp` is omitted,
36
+ * sets `exp = Math.floor(Date.now() / 1000) + expiresInSeconds`.
37
+ */
38
+ expiresInSeconds?: number;
39
+ }
40
+ /** Signs a JWT payload using HS256 by default (matching requireAuth's default). */
41
+ export declare function signJwt(payload: JWTPayload, options: SignJwtOptions): Promise<string>;
21
42
  /** Verifies a JWT's signature and standard claims (exp/nbf/iat), returns its payload. Throws on any failure. */
22
43
  export declare function verifyJwt(token: string, options: VerifyJwtOptions): Promise<JWTPayload>;
23
44
  /** Pulls the token out of a `Bearer <token>` Authorization header, or undefined if it's missing/malformed. */
24
45
  export declare function extractBearerToken(header: string | undefined): string | undefined;
46
+ /** Parses one named cookie from a raw `Cookie` request header, decoding percent-encoding. */
47
+ export declare function parseCookieHeader(cookieHeader: string | undefined, name: string): string | undefined;
48
+ /** Verifies a Hono-compatible signed cookie (`<value>.<base64-hmac-sha256>`) using Web Crypto. */
49
+ export declare function verifySignedCookieValue(signedValue: string, secret: string): Promise<string | undefined>;
50
+ /**
51
+ * Extracts a JWT from `Authorization: Bearer <token>`, or falls back to
52
+ * `options.cookieName` (verifying its HMAC signature if `options.cookieSecret`
53
+ * is configured).
54
+ */
55
+ export declare function extractAuthToken(authHeader: string | undefined, cookieHeader: string | undefined, options: VerifyJwtOptions): Promise<string | undefined>;
25
56
  //# sourceMappingURL=auth-core.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth-core.d.ts","sourceRoot":"","sources":["../src/auth-core.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7D;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;IACf;;;;;OAKG;IACH,GAAG,CAAC,EAAE,kBAAkB,CAAC;CAC1B;AAID,gHAAgH;AAChH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,UAAU,CAAC,CAEvF;AAED,8GAA8G;AAC9G,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAKjF"}
1
+ {"version":3,"file":"auth-core.d.ts","sourceRoot":"","sources":["../src/auth-core.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7D;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;IACf;;;;;OAKG;IACH,GAAG,CAAC,EAAE,kBAAkB,CAAC;IACzB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,cAAc;IAC7B,qCAAqC;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,iDAAiD;IACjD,GAAG,CAAC,EAAE,kBAAkB,CAAC;IACzB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAKD,mFAAmF;AACnF,wBAAgB,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,CAMrF;AAED,gHAAgH;AAChH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,UAAU,CAAC,CAEvF;AAED,8GAA8G;AAC9G,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAIjF;AAED,6FAA6F;AAC7F,wBAAgB,iBAAiB,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAepG;AAED,kGAAkG;AAClG,wBAAsB,uBAAuB,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA0B9G;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CACpC,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAY7B"}
@@ -0,0 +1,17 @@
1
+ export interface CacheControlOptions {
2
+ /** Browser cache lifetime in seconds (`max-age=<n>`). Defaults to 0 when `sMaxAge` is set without `maxAge`. */
3
+ maxAge?: number;
4
+ /** Shared/CDN (e.g. Vercel Edge) cache lifetime in seconds (`s-maxage=<n>`). */
5
+ sMaxAge?: number;
6
+ /** Seconds a CDN may serve stale content while refreshing asynchronously (`stale-while-revalidate=<n>`). */
7
+ staleWhileRevalidate?: number;
8
+ /** Marks the response private to one user (`private`) — never set `sMaxAge` alongside this. */
9
+ private?: boolean;
10
+ /** Disables caching completely (`no-store`). */
11
+ noStore?: boolean;
12
+ /** Marks hashed/versioned responses as immutable (`immutable`). */
13
+ immutable?: boolean;
14
+ }
15
+ /** Builds a standardized `Cache-Control` header value from structured options. */
16
+ export declare function buildCacheControlHeader(options: CacheControlOptions): string;
17
+ //# sourceMappingURL=cache-control-core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-control-core.d.ts","sourceRoot":"","sources":["../src/cache-control-core.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,mBAAmB;IAClC,+GAA+G;IAC/G,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gFAAgF;IAChF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,4GAA4G;IAC5G,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,+FAA+F;IAC/F,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,gDAAgD;IAChD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,mEAAmE;IACnE,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,kFAAkF;AAClF,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,mBAAmB,GAAG,MAAM,CAe5E"}
@@ -0,0 +1,9 @@
1
+ import type { Context, Next } from "hono";
2
+ import { type CacheControlOptions } from "./cache-control-core";
3
+ export type { CacheControlOptions };
4
+ /**
5
+ * Sets `Cache-Control` headers on public or private routes (e.g. Vercel Edge
6
+ * `s-maxage` + `stale-while-revalidate`) unless the handler already set one.
7
+ */
8
+ export declare function cacheControl(options: CacheControlOptions): (c: Context, next: Next) => Promise<void>;
9
+ //# sourceMappingURL=cache-control.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-control.d.ts","sourceRoot":"","sources":["../src/cache-control.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,EAA2B,KAAK,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAEzF,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC;;;GAGG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,mBAAmB,OAEP,OAAO,QAAQ,IAAI,mBAMpE"}
@@ -9,6 +9,14 @@ export interface CreateAppOptions {
9
9
  allowedOrigins?: string[];
10
10
  /** Max request body size in bytes. Defaults to 1mb. */
11
11
  bodyLimitBytes?: number;
12
+ /**
13
+ * Allow browsers to send and accept cookies on cross-origin requests
14
+ * (`Access-Control-Allow-Credentials: true`). Off by default — only needed
15
+ * when frontend and API live on different origins (alongside
16
+ * `credentials: "include"` on frontend fetches). Safe with `allowedOrigins`
17
+ * because backon uses an explicit allowlist, never `*`.
18
+ */
19
+ credentials?: boolean;
12
20
  }
13
21
  /**
14
22
  * Builds a Hono app pre-wired with backon's opinionated defaults: request
@@ -1 +1 @@
1
- {"version":3,"file":"create-app.d.ts","sourceRoot":"","sources":["../src/create-app.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAO5B,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,uDAAuD;IACvD,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAUD;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,oDA+CvD"}
1
+ {"version":3,"file":"create-app.d.ts","sourceRoot":"","sources":["../src/create-app.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAO5B,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,uDAAuD;IACvD,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAUD;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,oDAuDvD"}
@@ -1,4 +1,4 @@
1
- import type { ZodType } from "zod";
1
+ import { type ZodType } from "zod";
2
2
  import type { BackonContext } from "./types";
3
3
  /** Zod schemas for the parts of a request worth validating. All optional — skip whatever isn't needed. */
4
4
  export interface RouteSchema<B = undefined, Q = undefined, P = undefined> {
@@ -1 +1 @@
1
- {"version":3,"file":"define-route.d.ts","sourceRoot":"","sources":["../src/define-route.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAEnC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,0GAA0G;AAC1G,MAAM,WAAW,WAAW,CAAC,CAAC,GAAG,SAAS,EAAE,CAAC,GAAG,SAAS,EAAE,CAAC,GAAG,SAAS;IACtE,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IAClB,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IACnB,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;CACrB;AAED,MAAM,WAAW,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;IAChC,IAAI,EAAE,CAAC,CAAC;IACR,KAAK,EAAE,CAAC,CAAC;IACT,MAAM,EAAE,CAAC,CAAC;CACX;AAED,MAAM,MAAM,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAClC,CAAC,EAAE,aAAa,EAChB,IAAI,EAAE,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,KACrB,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAElC,6GAA6G;AAC7G,MAAM,WAAW,cAAc;IAC7B,CAAC,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IACtC,mBAAmB,CAAC,EAAE,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;CAC9D;AAED;;;;;;;;;;;;;;;;GAgBG;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AAE,OAAO,CAAC,CAAC;CAC9D;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,WAAW,CAAC,CAAC,GAAG,SAAS,EAAE,CAAC,GAAG,SAAS,EAAE,CAAC,GAAG,SAAS,EACrE,MAAM,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAC5B,OAAO,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAC7B,cAAc,CAiDhB"}
@@ -1 +1 @@
1
- {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,qBAAa,QAAS,SAAQ,KAAK;IACjC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;gBAEf,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO;CAOjF;AAED,oEAAoE;AACpE,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE;QACL,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,CAAC,EAAE,OAAO,CAAC;KACnB,CAAC;CACH"}
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,qBAAa,QAAS,SAAQ,KAAK;IACjC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAE3B,YAAY,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAM/E;CACF;AAED,oEAAoE;AACpE,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE;QACL,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,CAAC,EAAE,OAAO,CAAC;KACnB,CAAC;CACH"}
@@ -0,0 +1,9 @@
1
+ import type { Request, Response, NextFunction } from "express";
2
+ import { type CacheControlOptions } from "../cache-control-core";
3
+ export type { CacheControlOptions };
4
+ /**
5
+ * Express equivalent of `cacheControl()` — sets `Cache-Control` on the
6
+ * response unless the handler sets its own header later.
7
+ */
8
+ export declare function cacheControl(options: CacheControlOptions): (_req: Request, res: Response, next: NextFunction) => void;
9
+ //# sourceMappingURL=cache-control.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-control.d.ts","sourceRoot":"","sources":["../../src/express/cache-control.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAA2B,KAAK,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE1F,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC;;;GAGG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,mBAAmB,UAEV,OAAO,OAAO,QAAQ,QAAQ,YAAY,KAAG,IAAI,CAU/F"}
@@ -4,6 +4,11 @@ export interface CreateAppOptions {
4
4
  allowedOrigins?: string[];
5
5
  /** Max request body size in bytes. Defaults to 1mb. */
6
6
  bodyLimitBytes?: number;
7
+ /**
8
+ * Allow browsers to send and accept cookies on cross-origin requests
9
+ * (`Access-Control-Allow-Credentials: true`). Off by default.
10
+ */
11
+ credentials?: boolean;
7
12
  }
8
13
  /**
9
14
  * Builds an Express app pre-wired with the same defaults as the Hono
@@ -1 +1 @@
1
- {"version":3,"file":"create-app.d.ts","sourceRoot":"","sources":["../../src/express/create-app.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,KAAK,OAAO,EAAkD,MAAM,SAAS,CAAC;AAShG,MAAM,WAAW,gBAAgB;IAC/B,sGAAsG;IACtG,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,uDAAuD;IACvD,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAUD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,GAAG,OAAO,CAuBjE;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAwBrD"}
1
+ {"version":3,"file":"create-app.d.ts","sourceRoot":"","sources":["../../src/express/create-app.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,KAAK,OAAO,EAAkD,MAAM,SAAS,CAAC;AAShG,MAAM,WAAW,gBAAgB;IAC/B,sGAAsG;IACtG,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,uDAAuD;IACvD,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAUD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,GAAG,OAAO,CA4BjE;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAgCrD"}
@@ -1,5 +1,5 @@
1
1
  import type { Request, Response, NextFunction } from "express";
2
- import type { ZodType } from "zod";
2
+ import { type ZodType } from "zod";
3
3
  import { type BackonContext } from "./types";
4
4
  export interface RouteSchema<B = undefined, Q = undefined, P = undefined> {
5
5
  body?: ZodType<B>;
@@ -1 +1 @@
1
- {"version":3,"file":"define-route.d.ts","sourceRoot":"","sources":["../../src/express/define-route.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,KAAK,EAAE,OAAO,EAAE,M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CAAC,GAAG,SAAS,EACrE,MAAM,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAC5B,OAAO,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAC7B,cAAc,CAuChB"}
@@ -8,7 +8,10 @@ export type { ErrorResponseBody } from "../error";
8
8
  export { logger } from "../logger";
9
9
  export { requireEnv } from "../require-env";
10
10
  export { requireAuth } from "./require-auth";
11
- export type { VerifyJwtOptions } from "../auth-core";
11
+ export { signJwt } from "../auth-core";
12
+ export type { VerifyJwtOptions, SignJwtOptions } from "../auth-core";
13
+ export { cacheControl } from "./cache-control";
14
+ export type { CacheControlOptions } from "./cache-control";
12
15
  export { rateLimit } from "./rate-limit";
13
16
  export type { RateLimitOptions } from "./rate-limit";
14
17
  export type { BackonContext } from "./types";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/express/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAC7D,YAAY,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAEhC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE3E,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,YAAY,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAElD,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,EAAE,SAAS,EAAE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EAAE,MAAM,WAAW,CAAC;AAEnC,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAErE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,YAAY,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,YAAY,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC;;;;;GAKG;AACH,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE/D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE7D,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC9D,YAAY,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC"}
@@ -67,8 +67,12 @@ function trackRoutes(target) {
67
67
  if (typeof originalUse === "function") {
68
68
  const boundUse = originalUse.bind(tracked);
69
69
  tracked.use = (...args) => {
70
- if (typeof args[0] === "string" && isTracked(args[1])) {
71
- tracked.__backonEntries.push({ type: "mount", prefix: args[0], target: args[1] });
70
+ const prefix = typeof args[0] === "string" ? args[0] : "";
71
+ const candidates = typeof args[0] === "string" ? args.slice(1) : args;
72
+ for (const candidate of candidates) {
73
+ if (isTracked(candidate)) {
74
+ tracked.__backonEntries.push({ type: "mount", prefix, target: candidate });
75
+ }
72
76
  }
73
77
  return boundUse(...args);
74
78
  };
@@ -96,14 +100,19 @@ var DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024;
96
100
  function resolveAllowedOrigins(options) {
97
101
  if (options.allowedOrigins) return options.allowedOrigins;
98
102
  const fromEnv = process.env.ALLOWED_ORIGINS;
99
- return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
103
+ return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()).filter(Boolean) : [];
100
104
  }
101
105
  function createApp(options = {}) {
102
106
  const app = trackRoutes(express());
103
107
  app.use(requestLogger);
104
108
  app.use(helmet());
105
109
  const allowedOrigins = resolveAllowedOrigins(options);
106
- app.use(cors({ origin: allowedOrigins.length ? allowedOrigins : false }));
110
+ app.use(
111
+ cors({
112
+ origin: allowedOrigins.length ? allowedOrigins : false,
113
+ credentials: options.credentials ?? false
114
+ })
115
+ );
107
116
  app.use(compression());
108
117
  app.use(express.json({ limit: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES }));
109
118
  app.get("/health", (_req, res) => {
@@ -112,7 +121,11 @@ function createApp(options = {}) {
112
121
  return app;
113
122
  }
114
123
  function attachErrorHandler(app) {
115
- app.use((err, _req, res, _next) => {
124
+ app.use((err, _req, res, next) => {
125
+ if (res.headersSent) {
126
+ next(err);
127
+ return;
128
+ }
116
129
  if (err instanceof AppError) {
117
130
  logger.warn(
118
131
  { requestId: res.locals.requestId, code: err.code, details: err.details },
@@ -121,11 +134,16 @@ function attachErrorHandler(app) {
121
134
  res.status(err.statusCode).json({ error: { code: err.code, message: err.message, details: err.details } });
122
135
  return;
123
136
  }
124
- const status = err?.status ?? err?.statusCode;
137
+ const errObj = err;
138
+ const status = errObj?.status ?? errObj?.statusCode;
125
139
  if (status === 413) {
126
140
  res.status(413).json({ error: { code: "payload_too_large", message: "Request body too large" } });
127
141
  return;
128
142
  }
143
+ if (status === 400 && errObj?.type === "entity.parse.failed") {
144
+ res.status(400).json({ error: { code: "invalid_body", message: "Invalid JSON request body" } });
145
+ return;
146
+ }
129
147
  logger.error({ requestId: res.locals.requestId, err }, "unhandled error");
130
148
  res.status(500).json({ error: { code: "internal_error", message: "Something went wrong" } });
131
149
  });
@@ -169,6 +187,9 @@ function serve(app, port = Number(process.env.PORT) || 3e3) {
169
187
  return server;
170
188
  }
171
189
 
190
+ // src/express/define-route.ts
191
+ import { z } from "zod";
192
+
172
193
  // src/express/types.ts
173
194
  function createContext(req, res) {
174
195
  return {
@@ -200,21 +221,21 @@ function defineRoute(schema, handler) {
200
221
  if (schema.body) {
201
222
  const parsed = schema.body.safeParse(req.body ?? {});
202
223
  if (!parsed.success) {
203
- throw new AppError(400, "invalid_body", "Request body failed validation", parsed.error.flatten());
224
+ throw new AppError(400, "invalid_body", "Request body failed validation", z.flattenError(parsed.error));
204
225
  }
205
226
  body = parsed.data;
206
227
  }
207
228
  if (schema.query) {
208
229
  const parsed = schema.query.safeParse(req.query);
209
230
  if (!parsed.success) {
210
- throw new AppError(400, "invalid_query", "Query params failed validation", parsed.error.flatten());
231
+ throw new AppError(400, "invalid_query", "Query params failed validation", z.flattenError(parsed.error));
211
232
  }
212
233
  query = parsed.data;
213
234
  }
214
235
  if (schema.params) {
215
236
  const parsed = schema.params.safeParse(req.params);
216
237
  if (!parsed.success) {
217
- throw new AppError(400, "invalid_params", "Route params failed validation", parsed.error.flatten());
238
+ throw new AppError(400, "invalid_params", "Route params failed validation", z.flattenError(parsed.error));
218
239
  }
219
240
  params = parsed.data;
220
241
  }
@@ -240,24 +261,85 @@ ${issues}`);
240
261
  }
241
262
 
242
263
  // src/auth-core.ts
243
- import { verify } from "hono/jwt";
264
+ import { sign, verify } from "hono/jwt";
244
265
  var DEFAULT_ALG = "HS256";
266
+ var textEncoder = new TextEncoder();
267
+ function signJwt(payload, options) {
268
+ const finalPayload = options.expiresInSeconds !== void 0 && payload.exp === void 0 ? { ...payload, exp: Math.floor(Date.now() / 1e3) + options.expiresInSeconds } : payload;
269
+ return sign(finalPayload, options.secret, options.alg ?? DEFAULT_ALG);
270
+ }
245
271
  function verifyJwt(token, options) {
246
272
  return verify(token, options.secret, options.alg ?? DEFAULT_ALG);
247
273
  }
248
274
  function extractBearerToken(header) {
249
275
  if (!header) return void 0;
250
- const [scheme, token] = header.split(" ");
251
- if (scheme?.toLowerCase() !== "bearer" || !token) return void 0;
252
- return token;
276
+ const match = header.trim().match(/^Bearer\s+(\S+)$/i);
277
+ return match ? match[1] : void 0;
278
+ }
279
+ function parseCookieHeader(cookieHeader, name) {
280
+ if (!cookieHeader) return void 0;
281
+ for (const part of cookieHeader.split(";")) {
282
+ const eq = part.indexOf("=");
283
+ if (eq === -1) continue;
284
+ const key = part.slice(0, eq).trim();
285
+ if (key !== name) continue;
286
+ const raw = part.slice(eq + 1).trim();
287
+ try {
288
+ return decodeURIComponent(raw);
289
+ } catch {
290
+ return raw;
291
+ }
292
+ }
293
+ return void 0;
294
+ }
295
+ async function verifySignedCookieValue(signedValue, secret) {
296
+ const dot = signedValue.lastIndexOf(".");
297
+ if (dot <= 0) return void 0;
298
+ const value = signedValue.slice(0, dot);
299
+ const sigB64 = signedValue.slice(dot + 1);
300
+ if (sigB64.length !== 44 || !sigB64.endsWith("=")) return void 0;
301
+ let sigBytes;
302
+ try {
303
+ const binary = atob(sigB64);
304
+ sigBytes = new Uint8Array(new ArrayBuffer(binary.length));
305
+ for (let i = 0; i < binary.length; i++) sigBytes[i] = binary.charCodeAt(i);
306
+ } catch {
307
+ return void 0;
308
+ }
309
+ const key = await crypto.subtle.importKey(
310
+ "raw",
311
+ textEncoder.encode(secret),
312
+ { name: "HMAC", hash: "SHA-256" },
313
+ false,
314
+ ["verify"]
315
+ );
316
+ const valid = await crypto.subtle.verify("HMAC", key, sigBytes, textEncoder.encode(value));
317
+ return valid ? value : void 0;
318
+ }
319
+ async function extractAuthToken(authHeader, cookieHeader, options) {
320
+ const bearer = extractBearerToken(authHeader);
321
+ if (bearer) return bearer;
322
+ if (!options.cookieName) return void 0;
323
+ const rawCookie = parseCookieHeader(cookieHeader, options.cookieName);
324
+ if (!rawCookie) return void 0;
325
+ if (options.cookieSecret) {
326
+ return verifySignedCookieValue(rawCookie, options.cookieSecret);
327
+ }
328
+ return rawCookie;
253
329
  }
254
330
 
255
331
  // src/express/require-auth.ts
256
332
  function requireAuth(options) {
257
333
  return async function requireAuthMiddleware(req, res, next) {
258
- const token = extractBearerToken(req.header("authorization"));
334
+ const token = await extractAuthToken(req.header("authorization"), req.header("cookie"), options);
259
335
  if (!token) {
260
- next(new AppError(401, "unauthorized", "Missing or malformed Authorization header"));
336
+ next(
337
+ new AppError(
338
+ 401,
339
+ "unauthorized",
340
+ options.cookieName ? "Missing authentication token" : "Missing or malformed Authorization header"
341
+ )
342
+ );
261
343
  return;
262
344
  }
263
345
  try {
@@ -270,20 +352,67 @@ function requireAuth(options) {
270
352
  };
271
353
  }
272
354
 
355
+ // src/cache-control-core.ts
356
+ function buildCacheControlHeader(options) {
357
+ if (options.noStore) return "no-store";
358
+ const directives = [options.private ? "private" : "public"];
359
+ const maxAge = options.maxAge ?? (options.sMaxAge !== void 0 ? 0 : void 0);
360
+ if (maxAge !== void 0) directives.push(`max-age=${Math.max(0, Math.floor(maxAge))}`);
361
+ if (!options.private && options.sMaxAge !== void 0) {
362
+ directives.push(`s-maxage=${Math.max(0, Math.floor(options.sMaxAge))}`);
363
+ }
364
+ if (options.staleWhileRevalidate !== void 0) {
365
+ directives.push(`stale-while-revalidate=${Math.max(0, Math.floor(options.staleWhileRevalidate))}`);
366
+ }
367
+ if (options.immutable) directives.push("immutable");
368
+ return directives.join(", ");
369
+ }
370
+
371
+ // src/express/cache-control.ts
372
+ function cacheControl(options) {
373
+ const headerValue = buildCacheControlHeader(options);
374
+ return function cacheControlMiddleware(_req, res, next) {
375
+ const origWriteHead = res.writeHead.bind(res);
376
+ res.writeHead = (...args) => {
377
+ if (res.statusCode < 400 && !res.getHeader("Cache-Control")) {
378
+ res.setHeader("Cache-Control", headerValue);
379
+ }
380
+ return origWriteHead(...args);
381
+ };
382
+ next();
383
+ };
384
+ }
385
+
273
386
  // src/rate-limit-core.ts
387
+ var DEFAULT_MAX_KEYS = 1e4;
388
+ function extractForwardedIp(forwardedFor, realIp) {
389
+ const firstForwarded = forwardedFor?.split(",").map((part) => part.trim()).find((part) => part.length > 0);
390
+ if (firstForwarded) return firstForwarded;
391
+ const trimmedRealIp = realIp?.trim();
392
+ return trimmedRealIp || void 0;
393
+ }
274
394
  var RateLimiter = class {
275
- constructor(windowMs, max) {
395
+ constructor(windowMs, max, maxKeys = DEFAULT_MAX_KEYS) {
276
396
  this.windowMs = windowMs;
277
397
  this.max = max;
398
+ this.maxKeys = maxKeys;
278
399
  }
279
400
  windowMs;
280
401
  max;
402
+ maxKeys;
281
403
  buckets = /* @__PURE__ */ new Map();
282
404
  checksSinceSweep = 0;
283
405
  check(key, now = Date.now()) {
284
406
  this.maybeSweep(now);
285
407
  let bucket = this.buckets.get(key);
286
408
  if (!bucket || bucket.resetAt <= now) {
409
+ if (!bucket && this.buckets.size >= this.maxKeys) {
410
+ this.sweepExpired(now);
411
+ if (this.buckets.size >= this.maxKeys) {
412
+ const oldestKey = this.buckets.keys().next().value;
413
+ if (oldestKey !== void 0) this.buckets.delete(oldestKey);
414
+ }
415
+ }
287
416
  bucket = { count: 0, resetAt: now + this.windowMs };
288
417
  this.buckets.set(key, bucket);
289
418
  }
@@ -298,6 +427,9 @@ var RateLimiter = class {
298
427
  this.checksSinceSweep += 1;
299
428
  if (this.checksSinceSweep < 1e3) return;
300
429
  this.checksSinceSweep = 0;
430
+ this.sweepExpired(now);
431
+ }
432
+ sweepExpired(now) {
301
433
  for (const [key, bucket] of this.buckets) {
302
434
  if (bucket.resetAt <= now) this.buckets.delete(key);
303
435
  }
@@ -309,7 +441,8 @@ var DEFAULT_WINDOW_MS = 6e4;
309
441
  var DEFAULT_MAX = 60;
310
442
  function rateLimit(options = {}) {
311
443
  const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
312
- const keyGenerator = options.keyGenerator ?? defaultKey;
444
+ const trustProxy = options.trustProxy ?? false;
445
+ const keyGenerator = options.keyGenerator ?? ((req) => defaultKey(req, trustProxy));
313
446
  return function rateLimitMiddleware(req, res, next) {
314
447
  const result = limiter.check(keyGenerator(req));
315
448
  if (!result.allowed) {
@@ -320,8 +453,12 @@ function rateLimit(options = {}) {
320
453
  next();
321
454
  };
322
455
  }
323
- function defaultKey(req) {
324
- return req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? req.ip ?? "unknown";
456
+ function defaultKey(req, trustProxy) {
457
+ if (trustProxy) {
458
+ const forwarded = extractForwardedIp(req.header("x-forwarded-for"), req.header("x-real-ip"));
459
+ if (forwarded) return forwarded;
460
+ }
461
+ return req.ip || "unknown";
325
462
  }
326
463
 
327
464
  // src/express/router.ts
@@ -381,18 +518,21 @@ function defineUpload(options, handler) {
381
518
  }
382
519
 
383
520
  // src/openapi-core.ts
384
- import { zodToJsonSchema } from "zod-to-json-schema";
521
+ import { z as z2 } from "zod";
385
522
  function toOpenApiPath(path) {
386
523
  return path.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
387
524
  }
388
525
  function paramNames(path) {
389
526
  return [...path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]).filter((name) => name !== void 0);
390
527
  }
528
+ function toOpenApiSchema(schema) {
529
+ return z2.toJSONSchema(schema, { target: "openapi-3.0", unrepresentable: "any" });
530
+ }
391
531
  function buildOperation(path, schema) {
392
532
  const operation = { responses: { "200": { description: "Success" } } };
393
533
  const parameters = [];
394
534
  if (schema.params) {
395
- const jsonSchema = zodToJsonSchema(schema.params, { target: "openApi3" });
535
+ const jsonSchema = toOpenApiSchema(schema.params);
396
536
  for (const name of paramNames(path)) {
397
537
  parameters.push({
398
538
  name,
@@ -403,7 +543,7 @@ function buildOperation(path, schema) {
403
543
  }
404
544
  }
405
545
  if (schema.query) {
406
- const jsonSchema = zodToJsonSchema(schema.query, { target: "openApi3" });
546
+ const jsonSchema = toOpenApiSchema(schema.query);
407
547
  const required = new Set(jsonSchema.required ?? []);
408
548
  for (const [name, propSchema] of Object.entries(jsonSchema.properties ?? {})) {
409
549
  parameters.push({ name, in: "query", required: required.has(name), schema: propSchema });
@@ -413,7 +553,7 @@ function buildOperation(path, schema) {
413
553
  if (schema.body) {
414
554
  operation.requestBody = {
415
555
  required: true,
416
- content: { "application/json": { schema: zodToJsonSchema(schema.body, { target: "openApi3" }) } }
556
+ content: { "application/json": { schema: toOpenApiSchema(schema.body) } }
417
557
  };
418
558
  }
419
559
  return operation;
@@ -436,12 +576,18 @@ function buildOpenApiDocument(routes, options) {
436
576
  paths
437
577
  };
438
578
  }
579
+ function escapeHtml(value) {
580
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
581
+ }
582
+ function serializeInlineJson(value) {
583
+ return JSON.stringify(value).replace(/</g, "\\u003c");
584
+ }
439
585
  function pageShell(title, config) {
440
586
  const fullConfig = { showDeveloperTools: "never", ...config };
441
587
  return `<!doctype html>
442
588
  <html>
443
589
  <head>
444
- <title>${title}</title>
590
+ <title>${escapeHtml(title)}</title>
445
591
  <meta charset="utf-8" />
446
592
  <meta name="viewport" content="width=device-width, initial-scale=1" />
447
593
  </head>
@@ -449,7 +595,7 @@ function pageShell(title, config) {
449
595
  <div id="api-reference"></div>
450
596
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
451
597
  <script>
452
- Scalar.createApiReference("#api-reference", ${JSON.stringify(fullConfig)});
598
+ Scalar.createApiReference("#api-reference", ${serializeInlineJson(fullConfig)});
453
599
  </script>
454
600
  </body>
455
601
  </html>
@@ -468,12 +614,13 @@ function generateOpenApiSpec(app, options = {}) {
468
614
  return buildOpenApiDocument(routes, options);
469
615
  }
470
616
  function serveApiDocs(app, path = "/docs", options = {}) {
471
- const specPath = `${path}/openapi.json`;
472
- app.get(specPath, (_req, res) => res.json(generateOpenApiSpec(app, options)));
473
- app.get(
474
- path,
475
- (_req, res) => res.type("html").send(apiReferenceHtmlInline(generateOpenApiSpec(app, options), options.title))
476
- );
617
+ const basePath = path === "/" ? "" : path.replace(/\/+$/, "");
618
+ const docPath = basePath || "/";
619
+ const specPath = `${basePath}/openapi.json`;
620
+ const spec = generateOpenApiSpec(app, options);
621
+ const html = apiReferenceHtmlInline(spec, options.title);
622
+ app.get(specPath, (_req, res) => res.json(spec));
623
+ app.get(docPath, (_req, res) => res.type("html").send(html));
477
624
  }
478
625
  export {
479
626
  AppError,
@@ -481,6 +628,7 @@ export {
481
628
  apiReferenceHtml,
482
629
  apiReferenceHtmlInline,
483
630
  attachErrorHandler,
631
+ cacheControl,
484
632
  createApp,
485
633
  defineRoute,
486
634
  defineStream,
@@ -492,5 +640,6 @@ export {
492
640
  requireAuth,
493
641
  requireEnv,
494
642
  serve,
495
- serveApiDocs
643
+ serveApiDocs,
644
+ signJwt
496
645
  };
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../../src/express/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAGL,KAAK,cAAc,EAEpB,MAAM,iBAAiB,CAAC;AAGzB;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGvG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,CAM7F"}
1
+ {"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../../src/express/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAGL,KAAK,cAAc,EAEpB,MAAM,iBAAiB,CAAC;AAGzB;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGvG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,CAQ7F"}
@@ -4,6 +4,12 @@ export interface RateLimitOptions {
4
4
  windowMs?: number;
5
5
  /** Max requests allowed per key within the window. Defaults to 60. */
6
6
  max?: number;
7
+ /**
8
+ * Trust `X-Forwarded-For` / `X-Real-IP` headers when deriving the default key.
9
+ * Off by default because untrusted clients can spoof those headers; enable
10
+ * only when running behind a reverse proxy that sets/overwrites them.
11
+ */
12
+ trustProxy?: boolean;
7
13
  /** How to derive the bucket key from a request. Defaults to the caller's IP. */
8
14
  keyGenerator?: (req: Request) => string;
9
15
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../../src/express/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAI/D,MAAM,WAAW,gBAAgB;IAC/B,wDAAwD;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gFAAgF;IAChF,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,CAAC;CACzC;AAKD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,IAIlB,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,UASpF"}
1
+ {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../../src/express/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAI/D,MAAM,WAAW,gBAAgB;IAC/B,wDAAwD;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,gFAAgF;IAChF,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,CAAC;CACzC;AAKD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,SAKb,OAAO,OAAO,QAAQ,QAAQ,YAAY,UASpF"}