@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.
- package/dist/auth-core.d.ts +36 -5
- package/dist/auth-core.d.ts.map +1 -1
- package/dist/cache-control-core.d.ts +17 -0
- package/dist/cache-control-core.d.ts.map +1 -0
- package/dist/cache-control.d.ts +9 -0
- package/dist/cache-control.d.ts.map +1 -0
- package/dist/create-app.d.ts +8 -0
- package/dist/create-app.d.ts.map +1 -1
- package/dist/define-route.d.ts +1 -1
- package/dist/define-route.d.ts.map +1 -1
- package/dist/error.d.ts.map +1 -1
- package/dist/express/cache-control.d.ts +9 -0
- package/dist/express/cache-control.d.ts.map +1 -0
- package/dist/express/create-app.d.ts +5 -0
- package/dist/express/create-app.d.ts.map +1 -1
- package/dist/express/define-route.d.ts +1 -1
- package/dist/express/define-route.d.ts.map +1 -1
- package/dist/express/index.d.ts +4 -1
- package/dist/express/index.d.ts.map +1 -1
- package/dist/express/index.js +181 -32
- package/dist/express/openapi.d.ts.map +1 -1
- package/dist/express/rate-limit.d.ts +6 -0
- package/dist/express/rate-limit.d.ts.map +1 -1
- package/dist/express/require-auth.d.ts +2 -11
- package/dist/express/require-auth.d.ts.map +1 -1
- package/dist/express/router-registry.d.ts.map +1 -1
- package/dist/express/stream.d.ts.map +1 -1
- package/dist/express/upload.d.ts.map +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +216 -43
- package/dist/openapi-core.d.ts +1 -1
- package/dist/openapi-core.d.ts.map +1 -1
- package/dist/openapi.d.ts.map +1 -1
- package/dist/rate-limit-core.d.ts +5 -1
- package/dist/rate-limit-core.d.ts.map +1 -1
- package/dist/rate-limit.d.ts +6 -0
- package/dist/rate-limit.d.ts.map +1 -1
- package/dist/require-auth.d.ts +3 -14
- package/dist/require-auth.d.ts.map +1 -1
- package/dist/serve.d.ts +12 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/stream.d.ts.map +1 -1
- package/dist/upload.d.ts.map +1 -1
- package/dist/websocket.d.ts.map +1 -1
- package/package.json +13 -14
- package/src/auth-core.ts +108 -9
- package/src/cache-control-core.ts +32 -0
- package/src/cache-control.ts +18 -0
- package/src/create-app.ts +25 -9
- package/src/define-route.ts +17 -5
- package/src/express/cache-control.ts +22 -0
- package/src/express/create-app.ts +24 -6
- package/src/express/define-route.ts +4 -4
- package/src/express/index.ts +5 -1
- package/src/express/openapi.ts +7 -5
- package/src/express/rate-limit.ts +15 -4
- package/src/express/require-auth.ts +11 -14
- package/src/express/router-registry.ts +6 -2
- package/src/index.ts +6 -1
- package/src/openapi-core.ts +24 -7
- package/src/openapi.ts +8 -3
- package/src/rate-limit-core.ts +29 -1
- package/src/rate-limit.ts +15 -6
- package/src/require-auth.ts +10 -17
- package/src/serve.ts +48 -16
package/dist/serve.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,uIAAuI;AACvI,UAAU,eAAe;IACvB,IAAI,CAAC,EAAE,
|
|
1
|
+
{"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,uIAAuI;AACvI,UAAU,eAAe;IACvB,IAAI,CAAC,EAAE,CAAC,sBAAsB,CAAC,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClE,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,KAAK,IAAI,KAAK,IAAI,CAAC;IACnD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,GAAG,IAAI,CAAC;CACnD;AASD,oFAAoF;AACpF,wBAAsB,qBAAqB,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAUlF;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,eAAe,EACvB,IAAI,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAmC,GAC1D,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CASnC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,GAAE,MAAyC,4BAe1F;AAWD,wBAAsB,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAGvF;AAED,wBAAsB,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAWxF"}
|
package/dist/stream.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEzE;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEzE;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,OACjF,aAAa,cAMzB"}
|
package/dist/upload.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAO7C,MAAM,WAAW,aAAa;IAC5B,wEAAwE;IACxE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6FAA6F;IAC7F,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED,MAAM,MAAM,aAAa,GAAG,CAC1B,CAAC,EAAE,aAAa,EAChB,IAAI,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAA;CAAE,KACpC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAElC;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,aAAa,
|
|
1
|
+
{"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAO7C,MAAM,WAAW,aAAa;IAC5B,wEAAwE;IACxE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6FAA6F;IAC7F,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED,MAAM,MAAM,aAAa,GAAG,CAC1B,CAAC,EAAE,aAAa,EAChB,IAAI,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAA;CAAE,KACpC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAElC;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,aAAa,OACxD,aAAa,KAAG,OAAO,CAAC,QAAQ,CAAC,CA2BnD"}
|
package/dist/websocket.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../src/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3D,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,0HAA0H;AAC1H,MAAM,WAAW,iBAAiB;IAChC,MAAM,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC5D,OAAO,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,KAAK,IAAI,CAAC;CACnC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,iBAAiB,
|
|
1
|
+
{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../src/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3D,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,0HAA0H;AAC1H,MAAM,WAAW,iBAAiB;IAChC,MAAM,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC5D,OAAO,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,KAAK,IAAI,CAAC;CACnC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,iBAAiB,OACxC,OAAO,CAAC,GAAG,CAAC,8BAgB9B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mednours/backon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Opinionated backend framework wrapper, Bun-first but Node-compatible. Wraps Hono (default) or Express (via @mednours/backon/express) with the same baked-in security, logging, and validation defaults.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"bugs": "https://github.com/mednours/backon/issues",
|
|
14
14
|
"engines": {
|
|
15
15
|
"bun": ">=1.3.0",
|
|
16
|
-
"node": ">=
|
|
16
|
+
"node": ">=20"
|
|
17
17
|
},
|
|
18
18
|
"publishConfig": {
|
|
19
19
|
"access": "public"
|
|
@@ -41,22 +41,21 @@
|
|
|
41
41
|
"test": "bun test",
|
|
42
42
|
"typecheck": "tsc --noEmit",
|
|
43
43
|
"build": "rm -rf dist && tsc -p tsconfig.build.json && bun run build:js",
|
|
44
|
-
"build:js": "esbuild src/index.ts src/express/index.ts --outdir=dist --outbase=src --bundle --platform=node --format=esm --target=
|
|
44
|
+
"build:js": "esbuild src/index.ts src/express/index.ts --outdir=dist --outbase=src --bundle --platform=node --format=esm --target=node20 --packages=external",
|
|
45
45
|
"prepublishOnly": "bun run typecheck && bun run test && bun run build"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"hono": "^4.
|
|
49
|
-
"pino": "^
|
|
50
|
-
"zod": "^
|
|
51
|
-
"zod-to-json-schema": "^3.25.2"
|
|
48
|
+
"hono": "^4.13.23",
|
|
49
|
+
"pino": "^10",
|
|
50
|
+
"zod": "^4"
|
|
52
51
|
},
|
|
53
52
|
"peerDependencies": {
|
|
54
|
-
"express": "^
|
|
53
|
+
"express": "^5.0.0",
|
|
55
54
|
"cors": "^2.8.5",
|
|
56
55
|
"helmet": "^8.0.0",
|
|
57
56
|
"compression": "^1.7.5",
|
|
58
57
|
"ws": "^8.18.0",
|
|
59
|
-
"multer": "^
|
|
58
|
+
"multer": "^2.0.0",
|
|
60
59
|
"@hono/node-server": "^2.0.0"
|
|
61
60
|
},
|
|
62
61
|
"peerDependenciesMeta": {
|
|
@@ -87,18 +86,18 @@
|
|
|
87
86
|
"@types/bun": "latest",
|
|
88
87
|
"@types/compression": "^1.7.5",
|
|
89
88
|
"@types/cors": "^2.8.17",
|
|
90
|
-
"@types/express": "^
|
|
91
|
-
"@types/multer": "^
|
|
89
|
+
"@types/express": "^5",
|
|
90
|
+
"@types/multer": "^2",
|
|
92
91
|
"@types/supertest": "^6.0.2",
|
|
93
92
|
"@types/ws": "^8.5.13",
|
|
94
93
|
"compression": "^1.7.5",
|
|
95
94
|
"cors": "^2.8.5",
|
|
96
95
|
"esbuild": "^0.28.2",
|
|
97
|
-
"express": "^
|
|
96
|
+
"express": "^5",
|
|
98
97
|
"helmet": "^8.0.0",
|
|
99
|
-
"multer": "^
|
|
98
|
+
"multer": "^2",
|
|
100
99
|
"supertest": "^7.0.0",
|
|
101
|
-
"typescript": "^
|
|
100
|
+
"typescript": "^7",
|
|
102
101
|
"ws": "^8.18.0"
|
|
103
102
|
}
|
|
104
103
|
}
|
package/src/auth-core.ts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
import { verify } from "hono/jwt";
|
|
1
|
+
import { sign, verify } from "hono/jwt";
|
|
2
2
|
import type { JWTPayload } from "hono/utils/jwt/types";
|
|
3
3
|
import type { SignatureAlgorithm } from "hono/utils/jwt/jwa";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
* Shared by the Hono and Express
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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.
|
|
6
|
+
* Shared by the Hono and Express auth helpers — JWT signing/verification
|
|
7
|
+
* and cookie token extraction are identical across frameworks, built on
|
|
8
|
+
* hono/jwt and Web Crypto so no extra dependencies are needed.
|
|
11
9
|
*/
|
|
12
10
|
export interface VerifyJwtOptions {
|
|
13
11
|
/** Secret used to verify the token's signature. */
|
|
@@ -19,9 +17,41 @@ export interface VerifyJwtOptions {
|
|
|
19
17
|
* algorithm the server chose, never one the token claims for itself.
|
|
20
18
|
*/
|
|
21
19
|
alg?: SignatureAlgorithm;
|
|
20
|
+
/**
|
|
21
|
+
* Optional cookie name to fall back to when no `Authorization: Bearer`
|
|
22
|
+
* header is present (e.g. `"authToken"`).
|
|
23
|
+
*/
|
|
24
|
+
cookieName?: string;
|
|
25
|
+
/**
|
|
26
|
+
* When set alongside `cookieName`, verifies Hono-style signed cookies
|
|
27
|
+
* (`<value>.<base64-hmac-sha256>`) using this secret before verifying the JWT.
|
|
28
|
+
*/
|
|
29
|
+
cookieSecret?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SignJwtOptions {
|
|
33
|
+
/** Secret used to sign the token. */
|
|
34
|
+
secret: string;
|
|
35
|
+
/** Algorithm to sign with. Defaults to HS256. */
|
|
36
|
+
alg?: SignatureAlgorithm;
|
|
37
|
+
/**
|
|
38
|
+
* Optional lifetime in seconds. When set and `payload.exp` is omitted,
|
|
39
|
+
* sets `exp = Math.floor(Date.now() / 1000) + expiresInSeconds`.
|
|
40
|
+
*/
|
|
41
|
+
expiresInSeconds?: number;
|
|
22
42
|
}
|
|
23
43
|
|
|
24
44
|
const DEFAULT_ALG: SignatureAlgorithm = "HS256";
|
|
45
|
+
const textEncoder = new TextEncoder();
|
|
46
|
+
|
|
47
|
+
/** Signs a JWT payload using HS256 by default (matching requireAuth's default). */
|
|
48
|
+
export function signJwt(payload: JWTPayload, options: SignJwtOptions): Promise<string> {
|
|
49
|
+
const finalPayload: JWTPayload =
|
|
50
|
+
options.expiresInSeconds !== undefined && payload.exp === undefined
|
|
51
|
+
? { ...payload, exp: Math.floor(Date.now() / 1000) + options.expiresInSeconds }
|
|
52
|
+
: payload;
|
|
53
|
+
return sign(finalPayload, options.secret, options.alg ?? DEFAULT_ALG);
|
|
54
|
+
}
|
|
25
55
|
|
|
26
56
|
/** Verifies a JWT's signature and standard claims (exp/nbf/iat), returns its payload. Throws on any failure. */
|
|
27
57
|
export function verifyJwt(token: string, options: VerifyJwtOptions): Promise<JWTPayload> {
|
|
@@ -31,7 +61,76 @@ export function verifyJwt(token: string, options: VerifyJwtOptions): Promise<JWT
|
|
|
31
61
|
/** Pulls the token out of a `Bearer <token>` Authorization header, or undefined if it's missing/malformed. */
|
|
32
62
|
export function extractBearerToken(header: string | undefined): string | undefined {
|
|
33
63
|
if (!header) return undefined;
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
64
|
+
const match = header.trim().match(/^Bearer\s+(\S+)$/i);
|
|
65
|
+
return match ? match[1] : undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Parses one named cookie from a raw `Cookie` request header, decoding percent-encoding. */
|
|
69
|
+
export function parseCookieHeader(cookieHeader: string | undefined, name: string): string | undefined {
|
|
70
|
+
if (!cookieHeader) return undefined;
|
|
71
|
+
for (const part of cookieHeader.split(";")) {
|
|
72
|
+
const eq = part.indexOf("=");
|
|
73
|
+
if (eq === -1) continue;
|
|
74
|
+
const key = part.slice(0, eq).trim();
|
|
75
|
+
if (key !== name) continue;
|
|
76
|
+
const raw = part.slice(eq + 1).trim();
|
|
77
|
+
try {
|
|
78
|
+
return decodeURIComponent(raw);
|
|
79
|
+
} catch {
|
|
80
|
+
return raw;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Verifies a Hono-compatible signed cookie (`<value>.<base64-hmac-sha256>`) using Web Crypto. */
|
|
87
|
+
export async function verifySignedCookieValue(signedValue: string, secret: string): Promise<string | undefined> {
|
|
88
|
+
const dot = signedValue.lastIndexOf(".");
|
|
89
|
+
if (dot <= 0) return undefined;
|
|
90
|
+
|
|
91
|
+
const value = signedValue.slice(0, dot);
|
|
92
|
+
const sigB64 = signedValue.slice(dot + 1);
|
|
93
|
+
if (sigB64.length !== 44 || !sigB64.endsWith("=")) return undefined;
|
|
94
|
+
|
|
95
|
+
let sigBytes: Uint8Array<ArrayBuffer>;
|
|
96
|
+
try {
|
|
97
|
+
const binary = atob(sigB64);
|
|
98
|
+
sigBytes = new Uint8Array(new ArrayBuffer(binary.length));
|
|
99
|
+
for (let i = 0; i < binary.length; i++) sigBytes[i] = binary.charCodeAt(i);
|
|
100
|
+
} catch {
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const key = await crypto.subtle.importKey(
|
|
105
|
+
"raw",
|
|
106
|
+
textEncoder.encode(secret),
|
|
107
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
108
|
+
false,
|
|
109
|
+
["verify"]
|
|
110
|
+
);
|
|
111
|
+
const valid = await crypto.subtle.verify("HMAC", key, sigBytes, textEncoder.encode(value));
|
|
112
|
+
return valid ? value : undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Extracts a JWT from `Authorization: Bearer <token>`, or falls back to
|
|
117
|
+
* `options.cookieName` (verifying its HMAC signature if `options.cookieSecret`
|
|
118
|
+
* is configured).
|
|
119
|
+
*/
|
|
120
|
+
export async function extractAuthToken(
|
|
121
|
+
authHeader: string | undefined,
|
|
122
|
+
cookieHeader: string | undefined,
|
|
123
|
+
options: VerifyJwtOptions
|
|
124
|
+
): Promise<string | undefined> {
|
|
125
|
+
const bearer = extractBearerToken(authHeader);
|
|
126
|
+
if (bearer) return bearer;
|
|
127
|
+
if (!options.cookieName) return undefined;
|
|
128
|
+
|
|
129
|
+
const rawCookie = parseCookieHeader(cookieHeader, options.cookieName);
|
|
130
|
+
if (!rawCookie) return undefined;
|
|
131
|
+
|
|
132
|
+
if (options.cookieSecret) {
|
|
133
|
+
return verifySignedCookieValue(rawCookie, options.cookieSecret);
|
|
134
|
+
}
|
|
135
|
+
return rawCookie;
|
|
37
136
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
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
|
+
|
|
16
|
+
/** Builds a standardized `Cache-Control` header value from structured options. */
|
|
17
|
+
export function buildCacheControlHeader(options: CacheControlOptions): string {
|
|
18
|
+
if (options.noStore) return "no-store";
|
|
19
|
+
|
|
20
|
+
const directives: string[] = [options.private ? "private" : "public"];
|
|
21
|
+
const maxAge = options.maxAge ?? (options.sMaxAge !== undefined ? 0 : undefined);
|
|
22
|
+
if (maxAge !== undefined) directives.push(`max-age=${Math.max(0, Math.floor(maxAge))}`);
|
|
23
|
+
if (!options.private && options.sMaxAge !== undefined) {
|
|
24
|
+
directives.push(`s-maxage=${Math.max(0, Math.floor(options.sMaxAge))}`);
|
|
25
|
+
}
|
|
26
|
+
if (options.staleWhileRevalidate !== undefined) {
|
|
27
|
+
directives.push(`stale-while-revalidate=${Math.max(0, Math.floor(options.staleWhileRevalidate))}`);
|
|
28
|
+
}
|
|
29
|
+
if (options.immutable) directives.push("immutable");
|
|
30
|
+
|
|
31
|
+
return directives.join(", ");
|
|
32
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Context, Next } from "hono";
|
|
2
|
+
import { buildCacheControlHeader, type CacheControlOptions } from "./cache-control-core";
|
|
3
|
+
|
|
4
|
+
export type { CacheControlOptions };
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Sets `Cache-Control` headers on public or private routes (e.g. Vercel Edge
|
|
8
|
+
* `s-maxage` + `stale-while-revalidate`) unless the handler already set one.
|
|
9
|
+
*/
|
|
10
|
+
export function cacheControl(options: CacheControlOptions) {
|
|
11
|
+
const headerValue = buildCacheControlHeader(options);
|
|
12
|
+
return async function cacheControlMiddleware(c: Context, next: Next) {
|
|
13
|
+
await next();
|
|
14
|
+
if (c.res.status < 400 && !c.res.headers.has("cache-control")) {
|
|
15
|
+
c.header("Cache-Control", headerValue);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
package/src/create-app.ts
CHANGED
|
@@ -16,6 +16,14 @@ export interface CreateAppOptions {
|
|
|
16
16
|
allowedOrigins?: string[];
|
|
17
17
|
/** Max request body size in bytes. Defaults to 1mb. */
|
|
18
18
|
bodyLimitBytes?: number;
|
|
19
|
+
/**
|
|
20
|
+
* Allow browsers to send and accept cookies on cross-origin requests
|
|
21
|
+
* (`Access-Control-Allow-Credentials: true`). Off by default — only needed
|
|
22
|
+
* when frontend and API live on different origins (alongside
|
|
23
|
+
* `credentials: "include"` on frontend fetches). Safe with `allowedOrigins`
|
|
24
|
+
* because backon uses an explicit allowlist, never `*`.
|
|
25
|
+
*/
|
|
26
|
+
credentials?: boolean;
|
|
19
27
|
}
|
|
20
28
|
|
|
21
29
|
const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024; // 1mb
|
|
@@ -23,7 +31,7 @@ const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024; // 1mb
|
|
|
23
31
|
function resolveAllowedOrigins(options: CreateAppOptions): string[] {
|
|
24
32
|
if (options.allowedOrigins) return options.allowedOrigins;
|
|
25
33
|
const fromEnv = process.env.ALLOWED_ORIGINS;
|
|
26
|
-
return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
|
|
34
|
+
return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()).filter(Boolean) : [];
|
|
27
35
|
}
|
|
28
36
|
|
|
29
37
|
/**
|
|
@@ -45,17 +53,25 @@ export function createApp(options: CreateAppOptions = {}) {
|
|
|
45
53
|
"*",
|
|
46
54
|
cors({
|
|
47
55
|
origin: resolveAllowedOrigins(options),
|
|
56
|
+
credentials: options.credentials ?? false,
|
|
48
57
|
})
|
|
49
58
|
);
|
|
50
59
|
app.use("*", compress());
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
60
|
+
const jsonBodyLimit = bodyLimit({
|
|
61
|
+
maxSize: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES,
|
|
62
|
+
onError: (c) =>
|
|
63
|
+
c.json({ error: { code: "payload_too_large", message: "Request body too large" } }, 413),
|
|
64
|
+
});
|
|
65
|
+
app.use("*", async (c, next) => {
|
|
66
|
+
// Multipart uploads enforce their own maxFileSizeBytes inside defineUpload(),
|
|
67
|
+
// matching the Express adapter where express.json() only caps JSON bodies.
|
|
68
|
+
const contentType = c.req.header("content-type")?.toLowerCase() ?? "";
|
|
69
|
+
if (contentType.startsWith("multipart/form-data")) {
|
|
70
|
+
await next();
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
return jsonBodyLimit(c, next);
|
|
74
|
+
});
|
|
59
75
|
|
|
60
76
|
// Registered here, before createApp() returns, so it always gets the
|
|
61
77
|
// middleware above (logging, secure headers, CORS, compression, body
|
package/src/define-route.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { z, type ZodType } from "zod";
|
|
2
2
|
import { AppError } from "./error";
|
|
3
3
|
import type { BackonContext } from "./types";
|
|
4
4
|
|
|
@@ -53,10 +53,22 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
|
53
53
|
let params = undefined as P;
|
|
54
54
|
|
|
55
55
|
if (schema.body) {
|
|
56
|
-
const
|
|
56
|
+
const contentLength = c.req.header("content-length");
|
|
57
|
+
const hasBody = c.req.raw.body !== null && contentLength !== "0";
|
|
58
|
+
let raw: unknown = {};
|
|
59
|
+
if (hasBody) {
|
|
60
|
+
const text = await c.req.text();
|
|
61
|
+
if (text.length > 0) {
|
|
62
|
+
try {
|
|
63
|
+
raw = JSON.parse(text);
|
|
64
|
+
} catch {
|
|
65
|
+
throw new AppError(400, "invalid_body", "Invalid JSON request body");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
57
69
|
const parsed = schema.body.safeParse(raw);
|
|
58
70
|
if (!parsed.success) {
|
|
59
|
-
throw new AppError(400, "invalid_body", "Request body failed validation", parsed.error
|
|
71
|
+
throw new AppError(400, "invalid_body", "Request body failed validation", z.flattenError(parsed.error));
|
|
60
72
|
}
|
|
61
73
|
body = parsed.data;
|
|
62
74
|
}
|
|
@@ -65,7 +77,7 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
|
65
77
|
const raw = c.req.query();
|
|
66
78
|
const parsed = schema.query.safeParse(raw);
|
|
67
79
|
if (!parsed.success) {
|
|
68
|
-
throw new AppError(400, "invalid_query", "Query params failed validation", parsed.error
|
|
80
|
+
throw new AppError(400, "invalid_query", "Query params failed validation", z.flattenError(parsed.error));
|
|
69
81
|
}
|
|
70
82
|
query = parsed.data;
|
|
71
83
|
}
|
|
@@ -74,7 +86,7 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
|
74
86
|
const raw = c.req.param();
|
|
75
87
|
const parsed = schema.params.safeParse(raw);
|
|
76
88
|
if (!parsed.success) {
|
|
77
|
-
throw new AppError(400, "invalid_params", "Route params failed validation", parsed.error
|
|
89
|
+
throw new AppError(400, "invalid_params", "Route params failed validation", z.flattenError(parsed.error));
|
|
78
90
|
}
|
|
79
91
|
params = parsed.data;
|
|
80
92
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
const origWriteHead = res.writeHead.bind(res) as (...args: unknown[]) => Response;
|
|
14
|
+
(res as unknown as { writeHead: (...args: unknown[]) => Response }).writeHead = (...args: unknown[]) => {
|
|
15
|
+
if (res.statusCode < 400 && !res.getHeader("Cache-Control")) {
|
|
16
|
+
res.setHeader("Cache-Control", headerValue);
|
|
17
|
+
}
|
|
18
|
+
return origWriteHead(...args);
|
|
19
|
+
};
|
|
20
|
+
next();
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -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
|
|
@@ -19,7 +24,7 @@ const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024; // 1mb
|
|
|
19
24
|
function resolveAllowedOrigins(options: CreateAppOptions): string[] {
|
|
20
25
|
if (options.allowedOrigins) return options.allowedOrigins;
|
|
21
26
|
const fromEnv = process.env.ALLOWED_ORIGINS;
|
|
22
|
-
return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
|
|
27
|
+
return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()).filter(Boolean) : [];
|
|
23
28
|
}
|
|
24
29
|
|
|
25
30
|
/**
|
|
@@ -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(
|
|
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 }));
|
|
@@ -74,7 +84,12 @@ export function createApp(options: CreateAppOptions = {}): Express {
|
|
|
74
84
|
* 500 without leaking internals.
|
|
75
85
|
*/
|
|
76
86
|
export function attachErrorHandler(app: Express): void {
|
|
77
|
-
app.use((err: unknown, _req: Request, res: Response,
|
|
87
|
+
app.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {
|
|
88
|
+
if (res.headersSent) {
|
|
89
|
+
next(err);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
78
93
|
if (err instanceof AppError) {
|
|
79
94
|
logger.warn(
|
|
80
95
|
{ requestId: res.locals.requestId, code: err.code, details: err.details },
|
|
@@ -86,13 +101,16 @@ export function attachErrorHandler(app: Express): void {
|
|
|
86
101
|
return;
|
|
87
102
|
}
|
|
88
103
|
|
|
89
|
-
const status
|
|
90
|
-
|
|
91
|
-
(err as { statusCode?: number } | undefined)?.statusCode;
|
|
104
|
+
const errObj = err as { status?: number; statusCode?: number; type?: string } | undefined;
|
|
105
|
+
const status = errObj?.status ?? errObj?.statusCode;
|
|
92
106
|
if (status === 413) {
|
|
93
107
|
res.status(413).json({ error: { code: "payload_too_large", message: "Request body too large" } });
|
|
94
108
|
return;
|
|
95
109
|
}
|
|
110
|
+
if (status === 400 && errObj?.type === "entity.parse.failed") {
|
|
111
|
+
res.status(400).json({ error: { code: "invalid_body", message: "Invalid JSON request body" } });
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
96
114
|
|
|
97
115
|
logger.error({ requestId: res.locals.requestId, err }, "unhandled error");
|
|
98
116
|
res.status(500).json({ error: { code: "internal_error", message: "Something went wrong" } });
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Request, Response, NextFunction } from "express";
|
|
2
|
-
import type
|
|
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
|
|
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
|
|
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
|
|
76
|
+
throw new AppError(400, "invalid_params", "Route params failed validation", z.flattenError(parsed.error));
|
|
77
77
|
}
|
|
78
78
|
params = parsed.data;
|
|
79
79
|
}
|
package/src/express/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
|
|
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";
|
package/src/express/openapi.ts
CHANGED
|
@@ -29,9 +29,11 @@ export function generateOpenApiSpec(app: Express, options: OpenApiOptions = {}):
|
|
|
29
29
|
* serveApiDocs(app, "/docs", { title: "My API" });
|
|
30
30
|
*/
|
|
31
31
|
export function serveApiDocs(app: Express, path = "/docs", options: OpenApiOptions = {}): void {
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
);
|
|
32
|
+
const basePath = path === "/" ? "" : path.replace(/\/+$/, "");
|
|
33
|
+
const docPath = basePath || "/";
|
|
34
|
+
const specPath = `${basePath}/openapi.json`;
|
|
35
|
+
const spec = generateOpenApiSpec(app, options);
|
|
36
|
+
const html = apiReferenceHtmlInline(spec, options.title);
|
|
37
|
+
app.get(specPath, (_req, res) => res.json(spec));
|
|
38
|
+
app.get(docPath, (_req, res) => res.type("html").send(html));
|
|
37
39
|
}
|
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import type { Request, Response, NextFunction } from "express";
|
|
2
2
|
import { AppError } from "../error";
|
|
3
|
-
import { RateLimiter } from "../rate-limit-core";
|
|
3
|
+
import { extractForwardedIp, RateLimiter } from "../rate-limit-core";
|
|
4
4
|
|
|
5
5
|
export interface RateLimitOptions {
|
|
6
6
|
/** Window size in ms. Defaults to 60_000 (1 minute). */
|
|
7
7
|
windowMs?: number;
|
|
8
8
|
/** Max requests allowed per key within the window. Defaults to 60. */
|
|
9
9
|
max?: number;
|
|
10
|
+
/**
|
|
11
|
+
* Trust `X-Forwarded-For` / `X-Real-IP` headers when deriving the default key.
|
|
12
|
+
* Off by default because untrusted clients can spoof those headers; enable
|
|
13
|
+
* only when running behind a reverse proxy that sets/overwrites them.
|
|
14
|
+
*/
|
|
15
|
+
trustProxy?: boolean;
|
|
10
16
|
/** How to derive the bucket key from a request. Defaults to the caller's IP. */
|
|
11
17
|
keyGenerator?: (req: Request) => string;
|
|
12
18
|
}
|
|
@@ -22,7 +28,8 @@ const DEFAULT_MAX = 60;
|
|
|
22
28
|
*/
|
|
23
29
|
export function rateLimit(options: RateLimitOptions = {}) {
|
|
24
30
|
const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
|
|
25
|
-
const
|
|
31
|
+
const trustProxy = options.trustProxy ?? false;
|
|
32
|
+
const keyGenerator = options.keyGenerator ?? ((req) => defaultKey(req, trustProxy));
|
|
26
33
|
|
|
27
34
|
return function rateLimitMiddleware(req: Request, res: Response, next: NextFunction) {
|
|
28
35
|
const result = limiter.check(keyGenerator(req));
|
|
@@ -35,6 +42,10 @@ export function rateLimit(options: RateLimitOptions = {}) {
|
|
|
35
42
|
};
|
|
36
43
|
}
|
|
37
44
|
|
|
38
|
-
function defaultKey(req: Request): string {
|
|
39
|
-
|
|
45
|
+
function defaultKey(req: Request, trustProxy: boolean): string {
|
|
46
|
+
if (trustProxy) {
|
|
47
|
+
const forwarded = extractForwardedIp(req.header("x-forwarded-for"), req.header("x-real-ip"));
|
|
48
|
+
if (forwarded) return forwarded;
|
|
49
|
+
}
|
|
50
|
+
return req.ip || "unknown";
|
|
40
51
|
}
|
|
@@ -1,25 +1,22 @@
|
|
|
1
1
|
import type { Request, Response, NextFunction } from "express";
|
|
2
2
|
import { AppError } from "../error";
|
|
3
|
-
import {
|
|
3
|
+
import { extractAuthToken, verifyJwt, type VerifyJwtOptions } from "../auth-core";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
* Express equivalent of the Hono requireAuth: verifies a bearer
|
|
7
|
-
* stashes the decoded payload on res.locals.auth
|
|
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 =
|
|
11
|
+
const token = await extractAuthToken(req.header("authorization"), req.header("cookie"), options);
|
|
21
12
|
if (!token) {
|
|
22
|
-
next(
|
|
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
|
|
|
@@ -57,8 +57,12 @@ export function trackRoutes<T extends object>(target: T): T & TrackedRouter {
|
|
|
57
57
|
if (typeof originalUse === "function") {
|
|
58
58
|
const boundUse = originalUse.bind(tracked);
|
|
59
59
|
(tracked as Record<string, unknown>).use = (...args: unknown[]) => {
|
|
60
|
-
|
|
61
|
-
|
|
60
|
+
const prefix = typeof args[0] === "string" ? args[0] : "";
|
|
61
|
+
const candidates = typeof args[0] === "string" ? args.slice(1) : args;
|
|
62
|
+
for (const candidate of candidates) {
|
|
63
|
+
if (isTracked(candidate)) {
|
|
64
|
+
tracked.__backonEntries.push({ type: "mount", prefix, target: candidate });
|
|
65
|
+
}
|
|
62
66
|
}
|
|
63
67
|
return boundUse(...args);
|
|
64
68
|
};
|