@mednours/backon 0.7.0 → 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.
- 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 +118 -17
- 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/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 +120 -15
- 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.map +1 -1
- 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/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 +17 -17
- package/src/auth-core.ts +106 -6
- package/src/cache-control-core.ts +32 -0
- package/src/cache-control.ts +18 -0
- package/src/create-app.ts +9 -0
- package/src/define-route.ts +7 -5
- package/src/express/cache-control.ts +18 -0
- package/src/express/create-app.ts +11 -1
- package/src/express/define-route.ts +4 -4
- package/src/express/index.ts +5 -1
- package/src/express/openapi.ts +4 -4
- package/src/express/require-auth.ts +11 -14
- package/src/index.ts +6 -1
- package/src/openapi-core.ts +8 -5
- package/src/openapi.ts +5 -2
- package/src/require-auth.ts +10 -17
package/dist/index.js
CHANGED
|
@@ -58,7 +58,8 @@ function createApp(options = {}) {
|
|
|
58
58
|
app.use(
|
|
59
59
|
"*",
|
|
60
60
|
cors({
|
|
61
|
-
origin: resolveAllowedOrigins(options)
|
|
61
|
+
origin: resolveAllowedOrigins(options),
|
|
62
|
+
credentials: options.credentials ?? false
|
|
62
63
|
})
|
|
63
64
|
);
|
|
64
65
|
app.use("*", compress());
|
|
@@ -119,16 +120,19 @@ async function serveOnNode(app, port) {
|
|
|
119
120
|
}
|
|
120
121
|
|
|
121
122
|
// src/define-route.ts
|
|
123
|
+
import { z } from "zod";
|
|
122
124
|
function defineRoute(schema, handler) {
|
|
123
125
|
const wrapped = async (c) => {
|
|
124
126
|
let body = void 0;
|
|
125
127
|
let query = void 0;
|
|
126
128
|
let params = void 0;
|
|
127
129
|
if (schema.body) {
|
|
128
|
-
const
|
|
130
|
+
const contentLength = c.req.header("content-length");
|
|
131
|
+
const hasBody = c.req.raw.body !== null && contentLength !== "0";
|
|
132
|
+
const raw = hasBody ? await c.req.json().catch(() => ({})) : {};
|
|
129
133
|
const parsed = schema.body.safeParse(raw);
|
|
130
134
|
if (!parsed.success) {
|
|
131
|
-
throw new AppError(400, "invalid_body", "Request body failed validation", parsed.error
|
|
135
|
+
throw new AppError(400, "invalid_body", "Request body failed validation", z.flattenError(parsed.error));
|
|
132
136
|
}
|
|
133
137
|
body = parsed.data;
|
|
134
138
|
}
|
|
@@ -136,7 +140,7 @@ function defineRoute(schema, handler) {
|
|
|
136
140
|
const raw = c.req.query();
|
|
137
141
|
const parsed = schema.query.safeParse(raw);
|
|
138
142
|
if (!parsed.success) {
|
|
139
|
-
throw new AppError(400, "invalid_query", "Query params failed validation", parsed.error
|
|
143
|
+
throw new AppError(400, "invalid_query", "Query params failed validation", z.flattenError(parsed.error));
|
|
140
144
|
}
|
|
141
145
|
query = parsed.data;
|
|
142
146
|
}
|
|
@@ -144,7 +148,7 @@ function defineRoute(schema, handler) {
|
|
|
144
148
|
const raw = c.req.param();
|
|
145
149
|
const parsed = schema.params.safeParse(raw);
|
|
146
150
|
if (!parsed.success) {
|
|
147
|
-
throw new AppError(400, "invalid_params", "Route params failed validation", parsed.error
|
|
151
|
+
throw new AppError(400, "invalid_params", "Route params failed validation", z.flattenError(parsed.error));
|
|
148
152
|
}
|
|
149
153
|
params = parsed.data;
|
|
150
154
|
}
|
|
@@ -166,8 +170,13 @@ ${issues}`);
|
|
|
166
170
|
}
|
|
167
171
|
|
|
168
172
|
// src/auth-core.ts
|
|
169
|
-
import { verify } from "hono/jwt";
|
|
173
|
+
import { sign, verify } from "hono/jwt";
|
|
170
174
|
var DEFAULT_ALG = "HS256";
|
|
175
|
+
var textEncoder = new TextEncoder();
|
|
176
|
+
function signJwt(payload, options) {
|
|
177
|
+
const finalPayload = options.expiresInSeconds !== void 0 && payload.exp === void 0 ? { ...payload, exp: Math.floor(Date.now() / 1e3) + options.expiresInSeconds } : payload;
|
|
178
|
+
return sign(finalPayload, options.secret, options.alg ?? DEFAULT_ALG);
|
|
179
|
+
}
|
|
171
180
|
function verifyJwt(token, options) {
|
|
172
181
|
return verify(token, options.secret, options.alg ?? DEFAULT_ALG);
|
|
173
182
|
}
|
|
@@ -177,13 +186,68 @@ function extractBearerToken(header) {
|
|
|
177
186
|
if (scheme?.toLowerCase() !== "bearer" || !token) return void 0;
|
|
178
187
|
return token;
|
|
179
188
|
}
|
|
189
|
+
function parseCookieHeader(cookieHeader, name) {
|
|
190
|
+
if (!cookieHeader) return void 0;
|
|
191
|
+
for (const part of cookieHeader.split(";")) {
|
|
192
|
+
const eq = part.indexOf("=");
|
|
193
|
+
if (eq === -1) continue;
|
|
194
|
+
const key = part.slice(0, eq).trim();
|
|
195
|
+
if (key !== name) continue;
|
|
196
|
+
const raw = part.slice(eq + 1).trim();
|
|
197
|
+
try {
|
|
198
|
+
return decodeURIComponent(raw);
|
|
199
|
+
} catch {
|
|
200
|
+
return raw;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return void 0;
|
|
204
|
+
}
|
|
205
|
+
async function verifySignedCookieValue(signedValue, secret) {
|
|
206
|
+
const dot = signedValue.lastIndexOf(".");
|
|
207
|
+
if (dot <= 0) return void 0;
|
|
208
|
+
const value = signedValue.slice(0, dot);
|
|
209
|
+
const sigB64 = signedValue.slice(dot + 1);
|
|
210
|
+
if (sigB64.length !== 44 || !sigB64.endsWith("=")) return void 0;
|
|
211
|
+
let sigBytes;
|
|
212
|
+
try {
|
|
213
|
+
const binary = atob(sigB64);
|
|
214
|
+
sigBytes = new Uint8Array(new ArrayBuffer(binary.length));
|
|
215
|
+
for (let i = 0; i < binary.length; i++) sigBytes[i] = binary.charCodeAt(i);
|
|
216
|
+
} catch {
|
|
217
|
+
return void 0;
|
|
218
|
+
}
|
|
219
|
+
const key = await crypto.subtle.importKey(
|
|
220
|
+
"raw",
|
|
221
|
+
textEncoder.encode(secret),
|
|
222
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
223
|
+
false,
|
|
224
|
+
["verify"]
|
|
225
|
+
);
|
|
226
|
+
const valid = await crypto.subtle.verify("HMAC", key, sigBytes, textEncoder.encode(value));
|
|
227
|
+
return valid ? value : void 0;
|
|
228
|
+
}
|
|
229
|
+
async function extractAuthToken(authHeader, cookieHeader, options) {
|
|
230
|
+
const bearer = extractBearerToken(authHeader);
|
|
231
|
+
if (bearer) return bearer;
|
|
232
|
+
if (!options.cookieName) return void 0;
|
|
233
|
+
const rawCookie = parseCookieHeader(cookieHeader, options.cookieName);
|
|
234
|
+
if (!rawCookie) return void 0;
|
|
235
|
+
if (options.cookieSecret) {
|
|
236
|
+
return verifySignedCookieValue(rawCookie, options.cookieSecret);
|
|
237
|
+
}
|
|
238
|
+
return rawCookie;
|
|
239
|
+
}
|
|
180
240
|
|
|
181
241
|
// src/require-auth.ts
|
|
182
242
|
function requireAuth(options) {
|
|
183
243
|
return async function requireAuthMiddleware(c, next) {
|
|
184
|
-
const token =
|
|
244
|
+
const token = await extractAuthToken(c.req.header("authorization"), c.req.header("cookie"), options);
|
|
185
245
|
if (!token) {
|
|
186
|
-
throw new AppError(
|
|
246
|
+
throw new AppError(
|
|
247
|
+
401,
|
|
248
|
+
"unauthorized",
|
|
249
|
+
options.cookieName ? "Missing authentication token" : "Missing or malformed Authorization header"
|
|
250
|
+
);
|
|
187
251
|
}
|
|
188
252
|
try {
|
|
189
253
|
const payload = await verifyJwt(token, options);
|
|
@@ -195,6 +259,33 @@ function requireAuth(options) {
|
|
|
195
259
|
};
|
|
196
260
|
}
|
|
197
261
|
|
|
262
|
+
// src/cache-control-core.ts
|
|
263
|
+
function buildCacheControlHeader(options) {
|
|
264
|
+
if (options.noStore) return "no-store";
|
|
265
|
+
const directives = [options.private ? "private" : "public"];
|
|
266
|
+
const maxAge = options.maxAge ?? (options.sMaxAge !== void 0 ? 0 : void 0);
|
|
267
|
+
if (maxAge !== void 0) directives.push(`max-age=${Math.max(0, Math.floor(maxAge))}`);
|
|
268
|
+
if (!options.private && options.sMaxAge !== void 0) {
|
|
269
|
+
directives.push(`s-maxage=${Math.max(0, Math.floor(options.sMaxAge))}`);
|
|
270
|
+
}
|
|
271
|
+
if (options.staleWhileRevalidate !== void 0) {
|
|
272
|
+
directives.push(`stale-while-revalidate=${Math.max(0, Math.floor(options.staleWhileRevalidate))}`);
|
|
273
|
+
}
|
|
274
|
+
if (options.immutable) directives.push("immutable");
|
|
275
|
+
return directives.join(", ");
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// src/cache-control.ts
|
|
279
|
+
function cacheControl(options) {
|
|
280
|
+
const headerValue = buildCacheControlHeader(options);
|
|
281
|
+
return async function cacheControlMiddleware(c, next) {
|
|
282
|
+
await next();
|
|
283
|
+
if (!c.res.headers.has("cache-control")) {
|
|
284
|
+
c.header("Cache-Control", headerValue);
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
198
289
|
// src/rate-limit-core.ts
|
|
199
290
|
var RateLimiter = class {
|
|
200
291
|
constructor(windowMs, max) {
|
|
@@ -310,18 +401,21 @@ function defineUpload(options, handler) {
|
|
|
310
401
|
}
|
|
311
402
|
|
|
312
403
|
// src/openapi-core.ts
|
|
313
|
-
import {
|
|
404
|
+
import { z as z2 } from "zod";
|
|
314
405
|
function toOpenApiPath(path) {
|
|
315
406
|
return path.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
316
407
|
}
|
|
317
408
|
function paramNames(path) {
|
|
318
409
|
return [...path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]).filter((name) => name !== void 0);
|
|
319
410
|
}
|
|
411
|
+
function toOpenApiSchema(schema) {
|
|
412
|
+
return z2.toJSONSchema(schema, { target: "openapi-3.0", unrepresentable: "any" });
|
|
413
|
+
}
|
|
320
414
|
function buildOperation(path, schema) {
|
|
321
415
|
const operation = { responses: { "200": { description: "Success" } } };
|
|
322
416
|
const parameters = [];
|
|
323
417
|
if (schema.params) {
|
|
324
|
-
const jsonSchema =
|
|
418
|
+
const jsonSchema = toOpenApiSchema(schema.params);
|
|
325
419
|
for (const name of paramNames(path)) {
|
|
326
420
|
parameters.push({
|
|
327
421
|
name,
|
|
@@ -332,7 +426,7 @@ function buildOperation(path, schema) {
|
|
|
332
426
|
}
|
|
333
427
|
}
|
|
334
428
|
if (schema.query) {
|
|
335
|
-
const jsonSchema =
|
|
429
|
+
const jsonSchema = toOpenApiSchema(schema.query);
|
|
336
430
|
const required = new Set(jsonSchema.required ?? []);
|
|
337
431
|
for (const [name, propSchema] of Object.entries(jsonSchema.properties ?? {})) {
|
|
338
432
|
parameters.push({ name, in: "query", required: required.has(name), schema: propSchema });
|
|
@@ -342,7 +436,7 @@ function buildOperation(path, schema) {
|
|
|
342
436
|
if (schema.body) {
|
|
343
437
|
operation.requestBody = {
|
|
344
438
|
required: true,
|
|
345
|
-
content: { "application/json": { schema:
|
|
439
|
+
content: { "application/json": { schema: toOpenApiSchema(schema.body) } }
|
|
346
440
|
};
|
|
347
441
|
}
|
|
348
442
|
return operation;
|
|
@@ -403,27 +497,38 @@ function generateOpenApiSpec(app, options = {}) {
|
|
|
403
497
|
}
|
|
404
498
|
function serveApiDocs(app, path = "/docs", options = {}) {
|
|
405
499
|
const specPath = `${path}/openapi.json`;
|
|
406
|
-
|
|
407
|
-
|
|
500
|
+
const spec = generateOpenApiSpec(app, options);
|
|
501
|
+
const specJson = JSON.stringify(spec);
|
|
502
|
+
const html = apiReferenceHtmlInline(spec, options.title);
|
|
503
|
+
app.get(specPath, (c) => c.body(specJson, 200, { "Content-Type": "application/json; charset=UTF-8" }));
|
|
504
|
+
app.get(path, (c) => c.html(html));
|
|
408
505
|
}
|
|
409
506
|
|
|
410
507
|
// src/index.ts
|
|
411
508
|
import { Hono as Hono2 } from "hono";
|
|
509
|
+
import { setCookie, getCookie, deleteCookie, setSignedCookie, getSignedCookie } from "hono/cookie";
|
|
412
510
|
export {
|
|
413
511
|
AppError,
|
|
414
512
|
Hono2 as Hono,
|
|
415
513
|
apiReferenceHtml,
|
|
416
514
|
apiReferenceHtmlInline,
|
|
515
|
+
cacheControl,
|
|
417
516
|
createApp,
|
|
418
517
|
defineRoute,
|
|
419
518
|
defineStream,
|
|
420
519
|
defineUpload,
|
|
421
520
|
defineWebSocket,
|
|
521
|
+
deleteCookie,
|
|
422
522
|
generateOpenApiSpec,
|
|
523
|
+
getCookie,
|
|
524
|
+
getSignedCookie,
|
|
423
525
|
logger,
|
|
424
526
|
rateLimit,
|
|
425
527
|
requireAuth,
|
|
426
528
|
requireEnv,
|
|
427
529
|
serve,
|
|
428
|
-
serveApiDocs
|
|
530
|
+
serveApiDocs,
|
|
531
|
+
setCookie,
|
|
532
|
+
setSignedCookie,
|
|
533
|
+
signJwt
|
|
429
534
|
};
|
package/dist/openapi-core.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi-core.d.ts","sourceRoot":"","sources":["../src/openapi-core.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"openapi-core.d.ts","sourceRoot":"","sources":["../src/openapi-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAK,KAAK,OAAO,EAAE,MAAM,KAAK,CAAC;AAEtC,MAAM,WAAW,cAAc;IAC7B,yBAAyB;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,2BAA2B;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACxB,KAAK,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACzB,MAAM,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3B;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,eAAe,CAAC;CAC1B;AAED,qGAAqG;AACrG,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAgDD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,EAAE,OAAO,EAAE,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAmB/G;AA0BD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,SAAkB,GAAG,MAAM,CAEjF;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,SAAkB,GAAG,MAAM,CAErG"}
|
package/dist/openapi.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../src/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAgD,KAAK,cAAc,EAAuB,MAAM,gBAAgB,CAAC;AAGxH,YAAY,EAAE,cAAc,EAAE,CAAC;AAI/B;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAUzG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,
|
|
1
|
+
{"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../src/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAgD,KAAK,cAAc,EAAuB,MAAM,gBAAgB,CAAC;AAGxH,YAAY,EAAE,cAAc,EAAE,CAAC;AAI/B;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAUzG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,CAO/F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limit-core.d.ts","sourceRoot":"","sources":["../src/rate-limit-core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,0FAA0F;IAC1F,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,qBAAa,WAAW;IAKpB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,GAAG;IALtB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA6B;IACrD,OAAO,CAAC,gBAAgB,CAAK;
|
|
1
|
+
{"version":3,"file":"rate-limit-core.d.ts","sourceRoot":"","sources":["../src/rate-limit-core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,0FAA0F;IAC1F,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,qBAAa,WAAW;IAKpB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,GAAG;IALtB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA6B;IACrD,OAAO,CAAC,gBAAgB,CAAK;IAE7B,YACmB,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,MAAM,EAC1B;IAEJ,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,MAAmB,GAAG,oBAAoB,CAejE;IAED,0GAA0G;IAC1G,OAAO,CAAC,UAAU;CASnB"}
|
package/dist/rate-limit.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAInC,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,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC;CAC5C;AAKD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,
|
|
1
|
+
{"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAInC,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,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC;CAC5C;AAKD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,OAIT,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,mBAUtE"}
|
package/dist/require-auth.d.ts
CHANGED
|
@@ -2,20 +2,9 @@ import type { Context, Next } from "hono";
|
|
|
2
2
|
import type { Env } from "./types";
|
|
3
3
|
import { type VerifyJwtOptions } from "./auth-core";
|
|
4
4
|
/**
|
|
5
|
-
* Verifies a bearer JWT and stashes the decoded payload
|
|
6
|
-
* `auth`, retrievable in any handler downstream via
|
|
7
|
-
* AppError(401, "unauthorized") if
|
|
8
|
-
* token fails verification (bad signature, expired, wrong algorithm) —
|
|
9
|
-
* createApp()'s error handler turns that into the standard error JSON shape,
|
|
10
|
-
* same as any other AppError.
|
|
11
|
-
*
|
|
12
|
-
* This is verification only: issuing tokens (login, signup, refresh
|
|
13
|
-
* rotation, revocation) is left to the consuming project, since that's
|
|
14
|
-
* genuinely different per project and baking in an opinion there risks
|
|
15
|
-
* being wrong for whatever project actually uses it. Apply it per-route or
|
|
16
|
-
* per-group, not globally:
|
|
17
|
-
*
|
|
18
|
-
* protectedRoutes.use("*", requireAuth({ secret: process.env.JWT_SECRET! }));
|
|
5
|
+
* Verifies a bearer (or optional cookie) JWT and stashes the decoded payload
|
|
6
|
+
* on the context as `auth`, retrievable in any handler downstream via
|
|
7
|
+
* `c.get("auth")`. Throws AppError(401, "unauthorized") if missing or invalid.
|
|
19
8
|
*/
|
|
20
9
|
export declare function requireAuth(options: VerifyJwtOptions): (c: Context<Env>, next: Next) => Promise<void>;
|
|
21
10
|
//# sourceMappingURL=require-auth.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"require-auth.d.ts","sourceRoot":"","sources":["../src/require-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,OAAO,
|
|
1
|
+
{"version":3,"file":"require-auth.d.ts","sourceRoot":"","sources":["../src/require-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,OAAO,EAA+B,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEjF;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,gBAAgB,OACJ,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,mBAmBxE"}
|
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.8.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"
|
|
@@ -23,39 +23,39 @@
|
|
|
23
23
|
"types": "dist/index.d.ts",
|
|
24
24
|
"exports": {
|
|
25
25
|
".": {
|
|
26
|
-
"bun": "./src/index.ts",
|
|
27
26
|
"types": "./dist/index.d.ts",
|
|
28
27
|
"default": "./dist/index.js"
|
|
29
28
|
},
|
|
30
29
|
"./express": {
|
|
31
|
-
"bun": "./src/express/index.ts",
|
|
32
30
|
"types": "./dist/express/index.d.ts",
|
|
33
31
|
"default": "./dist/express/index.js"
|
|
34
32
|
}
|
|
35
33
|
},
|
|
36
|
-
"files": [
|
|
34
|
+
"files": [
|
|
35
|
+
"src",
|
|
36
|
+
"dist"
|
|
37
|
+
],
|
|
37
38
|
"scripts": {
|
|
38
39
|
"dev": "bun run --watch examples/dev-server.ts",
|
|
39
40
|
"dev:express": "bun run --watch examples/dev-server-express.ts",
|
|
40
41
|
"test": "bun test",
|
|
41
42
|
"typecheck": "tsc --noEmit",
|
|
42
43
|
"build": "rm -rf dist && tsc -p tsconfig.build.json && bun run build:js",
|
|
43
|
-
"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",
|
|
44
45
|
"prepublishOnly": "bun run typecheck && bun run test && bun run build"
|
|
45
46
|
},
|
|
46
47
|
"dependencies": {
|
|
47
|
-
"hono": "^4.
|
|
48
|
-
"pino": "^
|
|
49
|
-
"zod": "^
|
|
50
|
-
"zod-to-json-schema": "^3.25.2"
|
|
48
|
+
"hono": "^4.13.23",
|
|
49
|
+
"pino": "^10",
|
|
50
|
+
"zod": "^4"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
|
-
"express": "^
|
|
53
|
+
"express": "^5.0.0",
|
|
54
54
|
"cors": "^2.8.5",
|
|
55
55
|
"helmet": "^8.0.0",
|
|
56
56
|
"compression": "^1.7.5",
|
|
57
57
|
"ws": "^8.18.0",
|
|
58
|
-
"multer": "^
|
|
58
|
+
"multer": "^2.0.0",
|
|
59
59
|
"@hono/node-server": "^2.0.0"
|
|
60
60
|
},
|
|
61
61
|
"peerDependenciesMeta": {
|
|
@@ -86,18 +86,18 @@
|
|
|
86
86
|
"@types/bun": "latest",
|
|
87
87
|
"@types/compression": "^1.7.5",
|
|
88
88
|
"@types/cors": "^2.8.17",
|
|
89
|
-
"@types/express": "^
|
|
90
|
-
"@types/multer": "^
|
|
89
|
+
"@types/express": "^5",
|
|
90
|
+
"@types/multer": "^2",
|
|
91
91
|
"@types/supertest": "^6.0.2",
|
|
92
92
|
"@types/ws": "^8.5.13",
|
|
93
93
|
"compression": "^1.7.5",
|
|
94
94
|
"cors": "^2.8.5",
|
|
95
95
|
"esbuild": "^0.28.2",
|
|
96
|
-
"express": "^
|
|
96
|
+
"express": "^5",
|
|
97
97
|
"helmet": "^8.0.0",
|
|
98
|
-
"multer": "^
|
|
98
|
+
"multer": "^2",
|
|
99
99
|
"supertest": "^7.0.0",
|
|
100
|
-
"typescript": "^
|
|
100
|
+
"typescript": "^7",
|
|
101
101
|
"ws": "^8.18.0"
|
|
102
102
|
}
|
|
103
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> {
|
|
@@ -35,3 +65,73 @@ export function extractBearerToken(header: string | undefined): string | undefin
|
|
|
35
65
|
if (scheme?.toLowerCase() !== "bearer" || !token) return undefined;
|
|
36
66
|
return token;
|
|
37
67
|
}
|
|
68
|
+
|
|
69
|
+
/** Parses one named cookie from a raw `Cookie` request header, decoding percent-encoding. */
|
|
70
|
+
export function parseCookieHeader(cookieHeader: string | undefined, name: string): string | undefined {
|
|
71
|
+
if (!cookieHeader) return undefined;
|
|
72
|
+
for (const part of cookieHeader.split(";")) {
|
|
73
|
+
const eq = part.indexOf("=");
|
|
74
|
+
if (eq === -1) continue;
|
|
75
|
+
const key = part.slice(0, eq).trim();
|
|
76
|
+
if (key !== name) continue;
|
|
77
|
+
const raw = part.slice(eq + 1).trim();
|
|
78
|
+
try {
|
|
79
|
+
return decodeURIComponent(raw);
|
|
80
|
+
} catch {
|
|
81
|
+
return raw;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Verifies a Hono-compatible signed cookie (`<value>.<base64-hmac-sha256>`) using Web Crypto. */
|
|
88
|
+
export async function verifySignedCookieValue(signedValue: string, secret: string): Promise<string | undefined> {
|
|
89
|
+
const dot = signedValue.lastIndexOf(".");
|
|
90
|
+
if (dot <= 0) return undefined;
|
|
91
|
+
|
|
92
|
+
const value = signedValue.slice(0, dot);
|
|
93
|
+
const sigB64 = signedValue.slice(dot + 1);
|
|
94
|
+
if (sigB64.length !== 44 || !sigB64.endsWith("=")) return undefined;
|
|
95
|
+
|
|
96
|
+
let sigBytes: Uint8Array<ArrayBuffer>;
|
|
97
|
+
try {
|
|
98
|
+
const binary = atob(sigB64);
|
|
99
|
+
sigBytes = new Uint8Array(new ArrayBuffer(binary.length));
|
|
100
|
+
for (let i = 0; i < binary.length; i++) sigBytes[i] = binary.charCodeAt(i);
|
|
101
|
+
} catch {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const key = await crypto.subtle.importKey(
|
|
106
|
+
"raw",
|
|
107
|
+
textEncoder.encode(secret),
|
|
108
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
109
|
+
false,
|
|
110
|
+
["verify"]
|
|
111
|
+
);
|
|
112
|
+
const valid = await crypto.subtle.verify("HMAC", key, sigBytes, textEncoder.encode(value));
|
|
113
|
+
return valid ? value : undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Extracts a JWT from `Authorization: Bearer <token>`, or falls back to
|
|
118
|
+
* `options.cookieName` (verifying its HMAC signature if `options.cookieSecret`
|
|
119
|
+
* is configured).
|
|
120
|
+
*/
|
|
121
|
+
export async function extractAuthToken(
|
|
122
|
+
authHeader: string | undefined,
|
|
123
|
+
cookieHeader: string | undefined,
|
|
124
|
+
options: VerifyJwtOptions
|
|
125
|
+
): Promise<string | undefined> {
|
|
126
|
+
const bearer = extractBearerToken(authHeader);
|
|
127
|
+
if (bearer) return bearer;
|
|
128
|
+
if (!options.cookieName) return undefined;
|
|
129
|
+
|
|
130
|
+
const rawCookie = parseCookieHeader(cookieHeader, options.cookieName);
|
|
131
|
+
if (!rawCookie) return undefined;
|
|
132
|
+
|
|
133
|
+
if (options.cookieSecret) {
|
|
134
|
+
return verifySignedCookieValue(rawCookie, options.cookieSecret);
|
|
135
|
+
}
|
|
136
|
+
return rawCookie;
|
|
137
|
+
}
|
|
@@ -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.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
|
|
@@ -45,6 +53,7 @@ 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());
|