@mednours/backon 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -75,6 +75,47 @@ app.get(
75
75
  serve(app); // attaches the error handler, then app.listen()
76
76
  ```
77
77
 
78
+ ## `requireEnv(schema)`
79
+
80
+ Validates `process.env` against a Zod schema once, at startup, and returns the parsed (typed) result. Fails fast with every missing/invalid var named in one error, instead of the app booting cleanly and only crashing later on whichever request happens to touch a var nobody set.
81
+
82
+ ```ts
83
+ import { z } from "zod";
84
+ import { requireEnv } from "@mednours/backon";
85
+
86
+ export const env = requireEnv(
87
+ z.object({
88
+ DATABASE_URL: z.string().url(),
89
+ PORT: z.coerce.number().default(3000),
90
+ })
91
+ );
92
+ ```
93
+
94
+ ## `requireAuth(options)`
95
+
96
+ Verifies a bearer JWT and makes the decoded payload available on the context — `c.get("auth")` (Hono) or `res.locals.auth` (Express, or `c.get("auth")` inside a `defineRoute` handler). Throws `AppError(401, "unauthorized", ...)` if the header is missing, malformed, or the token fails verification (bad signature, expired, wrong algorithm). Built on `hono/jwt` rather than a new dependency, since `hono` is already a hard dependency of this package regardless of which framework you picked.
97
+
98
+ This is verification only — issuing tokens (login, signup, refresh rotation, revocation) is left to you, since that's genuinely different per project and baking in an opinion there risks being wrong for whatever actually uses it. The algorithm defaults to `HS256` and must be set explicitly rather than trusted from the token's own header — trusting that is how `alg: none` and algorithm-confusion attacks work.
99
+
100
+ ```ts
101
+ import { requireAuth } from "@mednours/backon";
102
+
103
+ app.use("/api/*", requireAuth({ secret: process.env.JWT_SECRET! }));
104
+ app.get("/api/me", (c) => c.json({ auth: c.get("auth") }));
105
+ ```
106
+
107
+ ## `rateLimit(options)`
108
+
109
+ In-memory token-bucket rate limiter. Throws `AppError(429, "rate_limited", ...)` once a key exceeds `max` requests within `windowMs`, with a `Retry-After` header set to when the window resets. Defaults to 60 requests per minute, keyed by the caller's IP; override either with `options`.
110
+
111
+ **Per-process state** — resets on restart and doesn't share counts across multiple instances or serverless invocations. Fine for a single long-running server; for anything horizontally scaled, back it with Redis instead.
112
+
113
+ ```ts
114
+ import { rateLimit } from "@mednours/backon";
115
+
116
+ app.use("/auth/login", rateLimit({ windowMs: 60_000, max: 5 })); // tighter limit on a login route
117
+ ```
118
+
78
119
  ## Requirements
79
120
 
80
121
  Bun >= 1.3. This package ships TypeScript source directly (no build step) since it's Bun-only by design.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mednours/backon",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "Opinionated backend framework wrapper for Bun. Wraps Hono (default) or Express (via @mednours/backon/express) with the same baked-in security, logging, and validation defaults.",
6
6
  "license": "MIT",
@@ -0,0 +1,37 @@
1
+ import { verify } from "hono/jwt";
2
+ import type { JWTPayload } from "hono/utils/jwt/types";
3
+ import type { SignatureAlgorithm } from "hono/utils/jwt/jwa";
4
+
5
+ /**
6
+ * Shared by the Hono and Express requireAuth() middleware — the actual JWT
7
+ * verification is identical, only how each framework reads the incoming
8
+ * request and reports failure differs. Built on hono/jwt's verify() rather
9
+ * than a new dependency, since hono is already a hard dependency of backon
10
+ * regardless of which framework (Hono or Express) a project picked.
11
+ */
12
+ export interface VerifyJwtOptions {
13
+ /** Secret used to verify the token's signature. */
14
+ secret: string;
15
+ /**
16
+ * Algorithm to verify with. Defaults to HS256. Deliberately not inferred
17
+ * from the token's own header — trusting that is how "alg: none" and
18
+ * algorithm-confusion attacks work, so backon always verifies against an
19
+ * algorithm the server chose, never one the token claims for itself.
20
+ */
21
+ alg?: SignatureAlgorithm;
22
+ }
23
+
24
+ const DEFAULT_ALG: SignatureAlgorithm = "HS256";
25
+
26
+ /** Verifies a JWT's signature and standard claims (exp/nbf/iat), returns its payload. Throws on any failure. */
27
+ export function verifyJwt(token: string, options: VerifyJwtOptions): Promise<JWTPayload> {
28
+ return verify(token, options.secret, options.alg ?? DEFAULT_ALG);
29
+ }
30
+
31
+ /** Pulls the token out of a `Bearer <token>` Authorization header, or undefined if it's missing/malformed. */
32
+ export function extractBearerToken(header: string | undefined): string | undefined {
33
+ if (!header) return undefined;
34
+ const [scheme, token] = header.split(" ");
35
+ if (scheme?.toLowerCase() !== "bearer" || !token) return undefined;
36
+ return token;
37
+ }
@@ -11,10 +11,23 @@ export type { ErrorResponseBody } from "../error";
11
11
 
12
12
  export { logger } from "../logger";
13
13
 
14
+ export { requireEnv } from "../require-env";
15
+
16
+ export { requireAuth } from "./require-auth";
17
+ export type { VerifyJwtOptions } from "../auth-core";
18
+
19
+ export { rateLimit } from "./rate-limit";
20
+ export type { RateLimitOptions } from "./rate-limit";
21
+
14
22
  export type { BackonContext } from "./types";
15
23
 
16
24
  /**
17
25
  * Re-exported so generated projects never depend on 'express' directly,
18
- * same reasoning as re-exporting Hono from the default export.
26
+ * same reasoning as re-exporting Hono from the default export. Request/
27
+ * Response/NextFunction are for writing plain Express middleware itself —
28
+ * BackonContext only exists inside defineRoute() handlers, middleware
29
+ * always operates at the framework's own req/res/next layer, there's no
30
+ * getting around that by wrapping it.
19
31
  */
20
32
  export { Router } from "express";
33
+ export type { Request, Response, NextFunction } from "express";
@@ -0,0 +1,40 @@
1
+ import type { Request, Response, NextFunction } from "express";
2
+ import { AppError } from "../error";
3
+ import { RateLimiter } from "../rate-limit-core";
4
+
5
+ export interface RateLimitOptions {
6
+ /** Window size in ms. Defaults to 60_000 (1 minute). */
7
+ windowMs?: number;
8
+ /** Max requests allowed per key within the window. Defaults to 60. */
9
+ max?: number;
10
+ /** How to derive the bucket key from a request. Defaults to the caller's IP. */
11
+ keyGenerator?: (req: Request) => string;
12
+ }
13
+
14
+ const DEFAULT_WINDOW_MS = 60_000;
15
+ const DEFAULT_MAX = 60;
16
+
17
+ /**
18
+ * Express equivalent of the Hono rateLimit(): same in-memory token-bucket
19
+ * limiter, same per-process caveat (see rate-limit-core.ts), calls
20
+ * next(AppError(429, "rate_limited")) once a key exceeds `max` requests in
21
+ * the current window, with a Retry-After header set to when it resets.
22
+ */
23
+ export function rateLimit(options: RateLimitOptions = {}) {
24
+ const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
25
+ const keyGenerator = options.keyGenerator ?? defaultKey;
26
+
27
+ return function rateLimitMiddleware(req: Request, res: Response, next: NextFunction) {
28
+ const result = limiter.check(keyGenerator(req));
29
+ if (!result.allowed) {
30
+ res.setHeader("Retry-After", String(Math.ceil(result.retryAfterMs / 1000)));
31
+ next(new AppError(429, "rate_limited", "Too many requests", { retryAfterMs: result.retryAfterMs }));
32
+ return;
33
+ }
34
+ next();
35
+ };
36
+ }
37
+
38
+ function defaultKey(req: Request): string {
39
+ return req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? req.ip ?? "unknown";
40
+ }
@@ -0,0 +1,34 @@
1
+ import type { Request, Response, NextFunction } from "express";
2
+ import { AppError } from "../error";
3
+ import { extractBearerToken, verifyJwt, type VerifyJwtOptions } from "../auth-core";
4
+
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 for you — see create-app.ts).
13
+ *
14
+ * Verification only, same as the Hono version — issuing tokens is left to
15
+ * you. Apply per-route or per-router, not necessarily globally.
16
+ */
17
+ export function requireAuth(options: VerifyJwtOptions) {
18
+ return async function requireAuthMiddleware(req: Request, res: Response, next: NextFunction) {
19
+ const token = extractBearerToken(req.header("authorization"));
20
+ if (!token) {
21
+ next(new AppError(401, "unauthorized", "Missing or malformed Authorization header"));
22
+ return;
23
+ }
24
+
25
+ try {
26
+ res.locals.auth = await verifyJwt(token, options);
27
+ } catch {
28
+ next(new AppError(401, "unauthorized", "Invalid or expired token"));
29
+ return;
30
+ }
31
+
32
+ next();
33
+ };
34
+ }
package/src/index.ts CHANGED
@@ -11,6 +11,14 @@ export type { ErrorResponseBody } from "./error";
11
11
 
12
12
  export { logger } from "./logger";
13
13
 
14
+ export { requireEnv } from "./require-env";
15
+
16
+ export { requireAuth } from "./require-auth";
17
+ export type { VerifyJwtOptions } from "./auth-core";
18
+
19
+ export { rateLimit } from "./rate-limit";
20
+ export type { RateLimitOptions } from "./rate-limit";
21
+
14
22
  export type { BackonContext, Env } from "./types";
15
23
 
16
24
  /**
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Plain in-memory token-bucket limiter, shared by the Hono and Express
3
+ * rate-limit middleware — the bucket bookkeeping is identical, only how
4
+ * each framework reads a request and reports 429 differs.
5
+ *
6
+ * NOTE: this is per-process state. It resets on restart and does not share
7
+ * counts across multiple instances (a multi-dyno deploy, serverless
8
+ * functions, etc). Fine for a single long-running server; for anything
9
+ * horizontally scaled, back this with Redis instead — this class exists to
10
+ * make that swap easy (same `check()` contract), not to rule it out.
11
+ */
12
+
13
+ interface Bucket {
14
+ count: number;
15
+ resetAt: number;
16
+ }
17
+
18
+ export interface RateLimitCheckResult {
19
+ allowed: boolean;
20
+ /** Milliseconds until this key's window resets. Only meaningful when allowed is false. */
21
+ retryAfterMs: number;
22
+ }
23
+
24
+ export class RateLimiter {
25
+ private readonly buckets = new Map<string, Bucket>();
26
+ private checksSinceSweep = 0;
27
+
28
+ constructor(
29
+ private readonly windowMs: number,
30
+ private readonly max: number
31
+ ) {}
32
+
33
+ check(key: string, now: number = Date.now()): RateLimitCheckResult {
34
+ this.maybeSweep(now);
35
+
36
+ let bucket = this.buckets.get(key);
37
+ if (!bucket || bucket.resetAt <= now) {
38
+ bucket = { count: 0, resetAt: now + this.windowMs };
39
+ this.buckets.set(key, bucket);
40
+ }
41
+
42
+ bucket.count += 1;
43
+
44
+ if (bucket.count > this.max) {
45
+ return { allowed: false, retryAfterMs: bucket.resetAt - now };
46
+ }
47
+ return { allowed: true, retryAfterMs: 0 };
48
+ }
49
+
50
+ /** Opportunistic cleanup so long-lived processes don't accumulate one bucket per distinct key forever. */
51
+ private maybeSweep(now: number): void {
52
+ this.checksSinceSweep += 1;
53
+ if (this.checksSinceSweep < 1000) return;
54
+ this.checksSinceSweep = 0;
55
+
56
+ for (const [key, bucket] of this.buckets) {
57
+ if (bucket.resetAt <= now) this.buckets.delete(key);
58
+ }
59
+ }
60
+ }
@@ -0,0 +1,53 @@
1
+ import type { Context, Next } from "hono";
2
+ import type { Env } from "./types";
3
+ import { AppError } from "./error";
4
+ import { RateLimiter } from "./rate-limit-core";
5
+
6
+ export interface RateLimitOptions {
7
+ /** Window size in ms. Defaults to 60_000 (1 minute). */
8
+ windowMs?: number;
9
+ /** Max requests allowed per key within the window. Defaults to 60. */
10
+ max?: number;
11
+ /** How to derive the bucket key from a request. Defaults to the caller's IP. */
12
+ keyGenerator?: (c: Context<Env>) => string;
13
+ }
14
+
15
+ const DEFAULT_WINDOW_MS = 60_000;
16
+ const DEFAULT_MAX = 60;
17
+
18
+ /**
19
+ * In-memory token-bucket rate limiter. Throws AppError(429, "rate_limited")
20
+ * once a key exceeds `max` requests in the current window, with a
21
+ * Retry-After header set to when the window resets.
22
+ *
23
+ * NOTE: per-process state — resets on restart, and doesn't share counts
24
+ * across multiple instances or serverless invocations. Fine for a single
25
+ * long-running server; for anything horizontally scaled, swap in a
26
+ * Redis-backed limiter instead.
27
+ *
28
+ * Apply per-route or per-group, not necessarily globally — a login route
29
+ * usually wants a tighter limit than the rest of the API:
30
+ *
31
+ * auth.use("/login", rateLimit({ windowMs: 60_000, max: 5 }));
32
+ */
33
+ export function rateLimit(options: RateLimitOptions = {}) {
34
+ const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
35
+ const keyGenerator = options.keyGenerator ?? defaultKey;
36
+
37
+ return async function rateLimitMiddleware(c: Context<Env>, next: Next) {
38
+ const result = limiter.check(keyGenerator(c));
39
+ if (!result.allowed) {
40
+ c.header("Retry-After", String(Math.ceil(result.retryAfterMs / 1000)));
41
+ throw new AppError(429, "rate_limited", "Too many requests", {
42
+ retryAfterMs: result.retryAfterMs,
43
+ });
44
+ }
45
+ await next();
46
+ };
47
+ }
48
+
49
+ function defaultKey(c: Context<Env>): string {
50
+ return (
51
+ c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? c.req.header("x-real-ip") ?? "unknown"
52
+ );
53
+ }
@@ -0,0 +1,37 @@
1
+ import type { Context, Next } from "hono";
2
+ import type { Env } from "./types";
3
+ import { AppError } from "./error";
4
+ import { extractBearerToken, verifyJwt, type VerifyJwtOptions } from "./auth-core";
5
+
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 you, since that's genuinely different
16
+ * per project and baking in an opinion there risks being wrong for whatever
17
+ * project actually uses it. Apply it per-route or per-group, not globally:
18
+ *
19
+ * protectedRoutes.use("*", requireAuth({ secret: process.env.JWT_SECRET! }));
20
+ */
21
+ export function requireAuth(options: VerifyJwtOptions) {
22
+ return async function requireAuthMiddleware(c: Context<Env>, next: Next) {
23
+ const token = extractBearerToken(c.req.header("authorization"));
24
+ if (!token) {
25
+ throw new AppError(401, "unauthorized", "Missing or malformed Authorization header");
26
+ }
27
+
28
+ try {
29
+ const payload = await verifyJwt(token, options);
30
+ c.set("auth", payload);
31
+ } catch {
32
+ throw new AppError(401, "unauthorized", "Invalid or expired token");
33
+ }
34
+
35
+ await next();
36
+ };
37
+ }
@@ -0,0 +1,31 @@
1
+ import type { ZodType } from "zod";
2
+
3
+ /**
4
+ * Validates process.env against a Zod schema once, at startup, and returns
5
+ * the parsed result. Fails fast with every missing/invalid var named in one
6
+ * error, instead of the app booting cleanly and only crashing later on
7
+ * whichever request happens to be the first to touch a var nobody set.
8
+ *
9
+ * Usage, typically in src/config/env.ts:
10
+ *
11
+ * import { z } from "zod";
12
+ * import { requireEnv } from "@mednours/backon";
13
+ *
14
+ * export const env = requireEnv(z.object({
15
+ * DATABASE_URL: z.string().url(),
16
+ * PORT: z.coerce.number().default(3000),
17
+ * }));
18
+ *
19
+ * `env.DATABASE_URL` is then typed as `string`, not `string | undefined` —
20
+ * everywhere else in the app can trust it's actually there.
21
+ */
22
+ export function requireEnv<T>(schema: ZodType<T>): T {
23
+ const parsed = schema.safeParse(process.env);
24
+ if (!parsed.success) {
25
+ const issues = parsed.error.issues
26
+ .map((issue) => ` - ${issue.path.join(".") || "(root)"}: ${issue.message}`)
27
+ .join("\n");
28
+ throw new Error(`Invalid environment variables:\n${issues}`);
29
+ }
30
+ return parsed.data;
31
+ }
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Context } from "hono";
2
+ import type { JWTPayload } from "hono/utils/jwt/types";
2
3
 
3
4
  /**
4
5
  * Hono's own generics for per-request state (c.get/c.set). Extend this as
@@ -8,6 +9,8 @@ import type { Context } from "hono";
8
9
  export interface Env {
9
10
  Variables: {
10
11
  requestId: string;
12
+ /** Set by requireAuth() middleware; undefined on any route it hasn't run on. */
13
+ auth?: JWTPayload;
11
14
  };
12
15
  }
13
16