@mednours/backon 0.7.1 → 0.8.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 (54) 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 +118 -17
  21. package/dist/express/rate-limit.d.ts.map +1 -1
  22. package/dist/express/require-auth.d.ts +2 -11
  23. package/dist/express/require-auth.d.ts.map +1 -1
  24. package/dist/express/stream.d.ts.map +1 -1
  25. package/dist/express/upload.d.ts.map +1 -1
  26. package/dist/index.d.ts +5 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +120 -15
  29. package/dist/openapi-core.d.ts +1 -1
  30. package/dist/openapi-core.d.ts.map +1 -1
  31. package/dist/openapi.d.ts.map +1 -1
  32. package/dist/rate-limit-core.d.ts.map +1 -1
  33. package/dist/rate-limit.d.ts.map +1 -1
  34. package/dist/require-auth.d.ts +3 -14
  35. package/dist/require-auth.d.ts.map +1 -1
  36. package/dist/stream.d.ts.map +1 -1
  37. package/dist/upload.d.ts.map +1 -1
  38. package/dist/websocket.d.ts.map +1 -1
  39. package/package.json +13 -14
  40. package/src/auth-core.ts +106 -6
  41. package/src/cache-control-core.ts +32 -0
  42. package/src/cache-control.ts +18 -0
  43. package/src/create-app.ts +9 -0
  44. package/src/define-route.ts +7 -5
  45. package/src/express/cache-control.ts +18 -0
  46. package/src/express/create-app.ts +11 -1
  47. package/src/express/define-route.ts +4 -4
  48. package/src/express/index.ts +5 -1
  49. package/src/express/openapi.ts +4 -4
  50. package/src/express/require-auth.ts +11 -14
  51. package/src/index.ts +6 -1
  52. package/src/openapi-core.ts +8 -5
  53. package/src/openapi.ts +5 -2
  54. package/src/require-auth.ts +10 -17
@@ -0,0 +1,18 @@
1
+ import type { Request, Response, NextFunction } from "express";
2
+ import { buildCacheControlHeader, type CacheControlOptions } from "../cache-control-core";
3
+
4
+ export type { CacheControlOptions };
5
+
6
+ /**
7
+ * Express equivalent of `cacheControl()` — sets `Cache-Control` on the
8
+ * response unless the handler sets its own header later.
9
+ */
10
+ export function cacheControl(options: CacheControlOptions) {
11
+ const headerValue = buildCacheControlHeader(options);
12
+ return function cacheControlMiddleware(_req: Request, res: Response, next: NextFunction): void {
13
+ if (!res.getHeader("Cache-Control")) {
14
+ res.setHeader("Cache-Control", headerValue);
15
+ }
16
+ next();
17
+ };
18
+ }
@@ -12,6 +12,11 @@ export interface CreateAppOptions {
12
12
  allowedOrigins?: string[];
13
13
  /** Max request body size in bytes. Defaults to 1mb. */
14
14
  bodyLimitBytes?: number;
15
+ /**
16
+ * Allow browsers to send and accept cookies on cross-origin requests
17
+ * (`Access-Control-Allow-Credentials: true`). Off by default.
18
+ */
19
+ credentials?: boolean;
15
20
  }
16
21
 
17
22
  const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024; // 1mb
@@ -50,7 +55,12 @@ export function createApp(options: CreateAppOptions = {}): Express {
50
55
  app.use(helmet());
51
56
 
52
57
  const allowedOrigins = resolveAllowedOrigins(options);
53
- app.use(cors({ origin: allowedOrigins.length ? allowedOrigins : false }));
58
+ app.use(
59
+ cors({
60
+ origin: allowedOrigins.length ? allowedOrigins : false,
61
+ credentials: options.credentials ?? false,
62
+ })
63
+ );
54
64
 
55
65
  app.use(compression());
56
66
  app.use(express.json({ limit: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES }));
@@ -1,5 +1,5 @@
1
1
  import type { Request, Response, NextFunction } from "express";
2
- import type { ZodType } from "zod";
2
+ import { z, type ZodType } from "zod";
3
3
  import { AppError } from "../error";
4
4
  import { createContext, type BackonContext } from "./types";
5
5
 
@@ -57,7 +57,7 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
57
57
  if (schema.body) {
58
58
  const parsed = schema.body.safeParse(req.body ?? {});
59
59
  if (!parsed.success) {
60
- throw new AppError(400, "invalid_body", "Request body failed validation", parsed.error.flatten());
60
+ throw new AppError(400, "invalid_body", "Request body failed validation", z.flattenError(parsed.error));
61
61
  }
62
62
  body = parsed.data;
63
63
  }
@@ -65,7 +65,7 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
65
65
  if (schema.query) {
66
66
  const parsed = schema.query.safeParse(req.query);
67
67
  if (!parsed.success) {
68
- throw new AppError(400, "invalid_query", "Query params failed validation", parsed.error.flatten());
68
+ throw new AppError(400, "invalid_query", "Query params failed validation", z.flattenError(parsed.error));
69
69
  }
70
70
  query = parsed.data;
71
71
  }
@@ -73,7 +73,7 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
73
73
  if (schema.params) {
74
74
  const parsed = schema.params.safeParse(req.params);
75
75
  if (!parsed.success) {
76
- throw new AppError(400, "invalid_params", "Route params failed validation", parsed.error.flatten());
76
+ throw new AppError(400, "invalid_params", "Route params failed validation", z.flattenError(parsed.error));
77
77
  }
78
78
  params = parsed.data;
79
79
  }
@@ -14,7 +14,11 @@ export { logger } from "../logger";
14
14
  export { requireEnv } from "../require-env";
15
15
 
16
16
  export { requireAuth } from "./require-auth";
17
- export type { VerifyJwtOptions } from "../auth-core";
17
+ export { signJwt } from "../auth-core";
18
+ export type { VerifyJwtOptions, SignJwtOptions } from "../auth-core";
19
+
20
+ export { cacheControl } from "./cache-control";
21
+ export type { CacheControlOptions } from "./cache-control";
18
22
 
19
23
  export { rateLimit } from "./rate-limit";
20
24
  export type { RateLimitOptions } from "./rate-limit";
@@ -30,8 +30,8 @@ export function generateOpenApiSpec(app: Express, options: OpenApiOptions = {}):
30
30
  */
31
31
  export function serveApiDocs(app: Express, path = "/docs", options: OpenApiOptions = {}): void {
32
32
  const specPath = `${path}/openapi.json`;
33
- app.get(specPath, (_req, res) => res.json(generateOpenApiSpec(app, options)));
34
- app.get(path, (_req, res) =>
35
- res.type("html").send(apiReferenceHtmlInline(generateOpenApiSpec(app, options), options.title))
36
- );
33
+ const spec = generateOpenApiSpec(app, options);
34
+ const html = apiReferenceHtmlInline(spec, options.title);
35
+ app.get(specPath, (_req, res) => res.json(spec));
36
+ app.get(path, (_req, res) => res.type("html").send(html));
37
37
  }
@@ -1,25 +1,22 @@
1
1
  import type { Request, Response, NextFunction } from "express";
2
2
  import { AppError } from "../error";
3
- import { extractBearerToken, verifyJwt, type VerifyJwtOptions } from "../auth-core";
3
+ import { extractAuthToken, verifyJwt, type VerifyJwtOptions } from "../auth-core";
4
4
 
5
5
  /**
6
- * Express equivalent of the Hono requireAuth: verifies a bearer JWT and
7
- * stashes the decoded payload on res.locals.auth — readable via
8
- * `c.get("auth")` in a defineRoute handler (BackonContext.get() reads
9
- * res.locals) or directly as `res.locals.auth` in plain Express middleware.
10
- * Calls next(AppError(401, "unauthorized")) on a missing, malformed, or
11
- * invalid token; requires attachErrorHandler(app) to be registered
12
- * downstream (serve() does this automatically — see create-app.ts).
13
- *
14
- * Verification only, same as the Hono version — issuing tokens is left to
15
- * the consuming project. Apply per-route or per-router, not necessarily
16
- * globally.
6
+ * Express equivalent of the Hono requireAuth: verifies a bearer (or optional
7
+ * cookie) JWT and stashes the decoded payload on `res.locals.auth`.
17
8
  */
18
9
  export function requireAuth(options: VerifyJwtOptions) {
19
10
  return async function requireAuthMiddleware(req: Request, res: Response, next: NextFunction) {
20
- const token = extractBearerToken(req.header("authorization"));
11
+ const token = await extractAuthToken(req.header("authorization"), req.header("cookie"), options);
21
12
  if (!token) {
22
- next(new AppError(401, "unauthorized", "Missing or malformed Authorization header"));
13
+ next(
14
+ new AppError(
15
+ 401,
16
+ "unauthorized",
17
+ options.cookieName ? "Missing authentication token" : "Missing or malformed Authorization header"
18
+ )
19
+ );
23
20
  return;
24
21
  }
25
22
 
package/src/index.ts CHANGED
@@ -14,7 +14,11 @@ export { logger } from "./logger";
14
14
  export { requireEnv } from "./require-env";
15
15
 
16
16
  export { requireAuth } from "./require-auth";
17
- export type { VerifyJwtOptions } from "./auth-core";
17
+ export { signJwt } from "./auth-core";
18
+ export type { VerifyJwtOptions, SignJwtOptions } from "./auth-core";
19
+
20
+ export { cacheControl } from "./cache-control";
21
+ export type { CacheControlOptions } from "./cache-control";
18
22
 
19
23
  export { rateLimit } from "./rate-limit";
20
24
  export type { RateLimitOptions } from "./rate-limit";
@@ -42,3 +46,4 @@ export type { BackonContext, Env } from "./types";
42
46
  */
43
47
  export { Hono } from "hono";
44
48
  export type { Next } from "hono";
49
+ export { setCookie, getCookie, deleteCookie, setSignedCookie, getSignedCookie } from "hono/cookie";
@@ -1,5 +1,4 @@
1
- import { zodToJsonSchema } from "zod-to-json-schema";
2
- import type { ZodType } from "zod";
1
+ import { z, type ZodType } from "zod";
3
2
 
4
3
  export interface OpenApiOptions {
5
4
  /** Defaults to "API". */
@@ -32,12 +31,16 @@ function paramNames(path: string): string[] {
32
31
  .filter((name): name is string => name !== undefined);
33
32
  }
34
33
 
34
+ function toOpenApiSchema(schema: ZodType<unknown>): Record<string, unknown> {
35
+ return z.toJSONSchema(schema, { target: "openapi-3.0", unrepresentable: "any" }) as Record<string, unknown>;
36
+ }
37
+
35
38
  function buildOperation(path: string, schema: RouteSchemaLike): Record<string, unknown> {
36
39
  const operation: Record<string, unknown> = { responses: { "200": { description: "Success" } } };
37
40
  const parameters: unknown[] = [];
38
41
 
39
42
  if (schema.params) {
40
- const jsonSchema = zodToJsonSchema(schema.params, { target: "openApi3" }) as Record<string, any>;
43
+ const jsonSchema = toOpenApiSchema(schema.params) as Record<string, any>;
41
44
  for (const name of paramNames(path)) {
42
45
  parameters.push({
43
46
  name,
@@ -49,7 +52,7 @@ function buildOperation(path: string, schema: RouteSchemaLike): Record<string, u
49
52
  }
50
53
 
51
54
  if (schema.query) {
52
- const jsonSchema = zodToJsonSchema(schema.query, { target: "openApi3" }) as Record<string, any>;
55
+ const jsonSchema = toOpenApiSchema(schema.query) as Record<string, any>;
53
56
  const required = new Set(jsonSchema.required ?? []);
54
57
  for (const [name, propSchema] of Object.entries(jsonSchema.properties ?? {})) {
55
58
  parameters.push({ name, in: "query", required: required.has(name), schema: propSchema });
@@ -61,7 +64,7 @@ function buildOperation(path: string, schema: RouteSchemaLike): Record<string, u
61
64
  if (schema.body) {
62
65
  operation.requestBody = {
63
66
  required: true,
64
- content: { "application/json": { schema: zodToJsonSchema(schema.body, { target: "openApi3" }) } },
67
+ content: { "application/json": { schema: toOpenApiSchema(schema.body) } },
65
68
  };
66
69
  }
67
70
 
package/src/openapi.ts CHANGED
@@ -36,6 +36,9 @@ export function generateOpenApiSpec(app: Hono<any>, options: OpenApiOptions = {}
36
36
  */
37
37
  export function serveApiDocs(app: Hono<any>, path = "/docs", options: OpenApiOptions = {}): void {
38
38
  const specPath = `${path}/openapi.json`;
39
- app.get(specPath, (c) => c.json(generateOpenApiSpec(app, options)));
40
- app.get(path, (c) => c.html(apiReferenceHtmlInline(generateOpenApiSpec(app, options), options.title)));
39
+ const spec = generateOpenApiSpec(app, options);
40
+ const specJson = JSON.stringify(spec);
41
+ const html = apiReferenceHtmlInline(spec, options.title);
42
+ app.get(specPath, (c) => c.body(specJson, 200, { "Content-Type": "application/json; charset=UTF-8" }));
43
+ app.get(path, (c) => c.html(html));
41
44
  }
@@ -1,29 +1,22 @@
1
1
  import type { Context, Next } from "hono";
2
2
  import type { Env } from "./types";
3
3
  import { AppError } from "./error";
4
- import { extractBearerToken, verifyJwt, type VerifyJwtOptions } from "./auth-core";
4
+ import { extractAuthToken, verifyJwt, type VerifyJwtOptions } from "./auth-core";
5
5
 
6
6
  /**
7
- * Verifies a bearer JWT and stashes the decoded payload on the context as
8
- * `auth`, retrievable in any handler downstream via `c.get("auth")`. Throws
9
- * AppError(401, "unauthorized") if the header is missing, malformed, or the
10
- * token fails verification (bad signature, expired, wrong algorithm) —
11
- * createApp()'s error handler turns that into the standard error JSON shape,
12
- * same as any other AppError.
13
- *
14
- * This is verification only: issuing tokens (login, signup, refresh
15
- * rotation, revocation) is left to the consuming project, since that's
16
- * genuinely different per project and baking in an opinion there risks
17
- * being wrong for whatever project actually uses it. Apply it per-route or
18
- * per-group, not globally:
19
- *
20
- * protectedRoutes.use("*", requireAuth({ secret: process.env.JWT_SECRET! }));
7
+ * Verifies a bearer (or optional cookie) JWT and stashes the decoded payload
8
+ * on the context as `auth`, retrievable in any handler downstream via
9
+ * `c.get("auth")`. Throws AppError(401, "unauthorized") if missing or invalid.
21
10
  */
22
11
  export function requireAuth(options: VerifyJwtOptions) {
23
12
  return async function requireAuthMiddleware(c: Context<Env>, next: Next) {
24
- const token = extractBearerToken(c.req.header("authorization"));
13
+ const token = await extractAuthToken(c.req.header("authorization"), c.req.header("cookie"), options);
25
14
  if (!token) {
26
- throw new AppError(401, "unauthorized", "Missing or malformed Authorization header");
15
+ throw new AppError(
16
+ 401,
17
+ "unauthorized",
18
+ options.cookieName ? "Missing authentication token" : "Missing or malformed Authorization header"
19
+ );
27
20
  }
28
21
 
29
22
  try {