barejs 0.1.49 → 0.1.50

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.
@@ -1,3 +1,5 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+
1
3
  export type Params = Record<string, string>;
2
4
  export type Next = () => Promise<any> | any;
3
5
  export type Middleware = (ctx: Context, next: Next) => Promise<any> | any;
@@ -5,6 +7,40 @@ export type Handler = (ctx: Context) => Promise<any> | any;
5
7
  export type GroupCallback = (router: any) => void;
6
8
  export type AuthUser = Record<string, any>;
7
9
 
10
+ export interface CookieOptions {
11
+ httpOnly?: boolean;
12
+ secure?: boolean;
13
+ sameSite?: 'Strict' | 'Lax' | 'None';
14
+ path?: string;
15
+ domain?: string;
16
+ maxAge?: number;
17
+ expires?: Date;
18
+ secret?: string;
19
+ }
20
+
21
+ export interface UploadOptions {
22
+ /** Max size per file in bytes (default: 5MB) */
23
+ maxFileSize?: number;
24
+ /** Max number of uploaded files (default: 10) */
25
+ maxFiles?: number;
26
+ /** Allowed MIME types (e.g. ['image/png', 'image/jpeg', 'application/pdf']) */
27
+ allowedTypes?: string[];
28
+ }
29
+
30
+ export interface UploadedFile {
31
+ fieldName: string;
32
+ filename: string;
33
+ safeName: string;
34
+ type: string;
35
+ size: number;
36
+ file: File;
37
+ }
38
+
39
+ export interface UploadResult {
40
+ fields: Record<string, string>;
41
+ files: UploadedFile[];
42
+ }
43
+
8
44
  export class Context {
9
45
  public req!: Request;
10
46
  public params: Params = {};
@@ -13,6 +49,9 @@ export class Context {
13
49
  public store = new Map<string, any>();
14
50
  public body: any = undefined;
15
51
  public _query: Record<string, string> | undefined = undefined;
52
+ public _cookies: Record<string, string> | undefined = undefined;
53
+ public _setCookies: string[] | undefined = undefined;
54
+ public _requestId: string | undefined = undefined;
16
55
  constructor() { }
17
56
 
18
57
  public get query(): Record<string, string> {
@@ -38,10 +77,14 @@ export class Context {
38
77
  k = url.slice(start, amp);
39
78
  v = '';
40
79
  }
41
- try {
42
- k = decodeURIComponent(k.replace(/\+/g, ' '));
43
- v = decodeURIComponent(v.replace(/\+/g, ' '));
44
- } catch { /* keep raw on malformed URI */ }
80
+ if (k.indexOf('+') !== -1) k = k.replaceAll('+', ' ');
81
+ if (k.indexOf('%') !== -1) {
82
+ try { k = decodeURIComponent(k); } catch { /* keep raw */ }
83
+ }
84
+ if (v.indexOf('+') !== -1) v = v.replaceAll('+', ' ');
85
+ if (v.indexOf('%') !== -1) {
86
+ try { v = decodeURIComponent(v); } catch { /* keep raw */ }
87
+ }
45
88
  if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
46
89
  result[k] = v;
47
90
  }
@@ -58,14 +101,106 @@ export class Context {
58
101
  return this.query[key];
59
102
  }
60
103
 
61
- public async jsonBody(): Promise<any> {
104
+ public get cookies(): Record<string, string> {
105
+ if (this._cookies !== undefined) return this._cookies;
106
+ const result: Record<string, string> = {};
107
+ const header = this.req?.headers?.get('cookie');
108
+ if (header) {
109
+ let start = 0;
110
+ const len = header.length;
111
+ while (start < len) {
112
+ let semi = header.indexOf(';', start);
113
+ if (semi === -1) semi = len;
114
+ const eq = header.indexOf('=', start);
115
+ if (eq !== -1 && eq < semi) {
116
+ const k = header.slice(start, eq).trim();
117
+ let v = header.slice(eq + 1, semi).trim();
118
+ try {
119
+ v = decodeURIComponent(v);
120
+ } catch { /* keep raw */ }
121
+ if (k && k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
122
+ result[k] = v;
123
+ }
124
+ }
125
+ start = semi + 1;
126
+ }
127
+ }
128
+ this._cookies = result;
129
+ return result;
130
+ }
131
+
132
+ public setCookie(name: string, value: string, options: CookieOptions = {}): this {
133
+ let finalVal = value;
134
+ if (options.secret) {
135
+ const sig = createHmac('sha256', options.secret).update(value).digest('base64url');
136
+ finalVal = `${value}.${sig}`;
137
+ }
138
+ let cookieStr = `${name}=${encodeURIComponent(finalVal)}`;
139
+ cookieStr += `; Path=${options.path ?? '/'}`;
140
+ if (options.domain) cookieStr += `; Domain=${options.domain}`;
141
+ if (options.maxAge !== undefined) cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
142
+ if (options.expires) cookieStr += `; Expires=${options.expires.toUTCString()}`;
143
+ if (options.httpOnly !== false) cookieStr += '; HttpOnly';
144
+ if (options.secure) cookieStr += '; Secure';
145
+ cookieStr += `; SameSite=${options.sameSite ?? 'Lax'}`;
146
+
147
+ if (!this._setCookies) this._setCookies = [];
148
+ this._setCookies.push(cookieStr);
149
+ return this;
150
+ }
151
+
152
+ public getSignedCookie(name: string, secret: string): string | null {
153
+ const raw = this.cookies[name];
154
+ if (!raw) return null;
155
+ const dotIdx = raw.lastIndexOf('.');
156
+ if (dotIdx <= 0) return null;
157
+ const value = raw.slice(0, dotIdx);
158
+ const sigB64 = raw.slice(dotIdx + 1);
159
+ const expected = createHmac('sha256', secret).update(value).digest();
160
+ const actual = Buffer.from(sigB64, 'base64url');
161
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
162
+ return null;
163
+ }
164
+ return value;
165
+ }
166
+
167
+ public deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain'> = {}): this {
168
+ return this.setCookie(name, '', {
169
+ ...options,
170
+ maxAge: 0,
171
+ expires: new Date(0)
172
+ });
173
+ }
174
+
175
+ public async jsonBody(maxBytes: number = 1048576): Promise<any> {
62
176
  if (this.body !== undefined) return this.body;
63
177
 
64
178
  const contentType = this.req.headers.get("content-type");
65
179
  if (contentType && contentType.includes("application/json")) {
180
+ const lenHeader = this.req.headers.get("content-length");
181
+ if (lenHeader !== null) {
182
+ const lenNum = Number(lenHeader);
183
+ if (lenNum > maxBytes) {
184
+ const err: any = new Error("Payload Too Large");
185
+ err.status = 413;
186
+ throw err;
187
+ }
188
+ try {
189
+ return this.body = await this.req.json();
190
+ } catch {
191
+ return this.body = null;
192
+ }
193
+ }
66
194
  try {
67
- return this.body = await this.req.json();
68
- } catch {
195
+ const text = await this.req.text();
196
+ if (Buffer.byteLength(text, 'utf-8') > maxBytes) {
197
+ const err: any = new Error("Payload Too Large");
198
+ err.status = 413;
199
+ throw err;
200
+ }
201
+ return this.body = JSON.parse(text);
202
+ } catch (e: any) {
203
+ if (e?.status === 413) throw e;
69
204
  return this.body = null;
70
205
  }
71
206
  }
@@ -79,6 +214,8 @@ export class Context {
79
214
  if (this.store.size > 0) this.store.clear();
80
215
  this.params = {};
81
216
  this._query = undefined;
217
+ this._cookies = undefined;
218
+ this._setCookies = undefined;
82
219
  this.body = undefined;
83
220
  return this;
84
221
  }
@@ -88,38 +225,28 @@ export class Context {
88
225
  return this;
89
226
  }
90
227
 
91
- // public json(data: any): Response {
92
- // if (this._headers !== undefined) {
93
- // if (this._headers["content-type"] === undefined) {
94
- // this._headers["content-type"] = "application/json";
95
- // }
96
- // return Response.json(data, {
97
- // status: this._status,
98
- // headers: this._headers
99
- // });
100
- // }
101
- // if (this._status === 200) {
102
- // return Response.json(data);
103
- // }
104
- // return Response.json(data, { status: this._status });
105
- // }
106
228
  public json(data: any): Response {
107
229
  const status = this._status || 200;
230
+ let res: Response;
108
231
 
109
- // No custom headers
110
232
  if (!this._headers) {
111
- return Response.json(data, { status });
233
+ res = Response.json(data, { status });
234
+ } else {
235
+ if (this._headers["content-type"] === undefined) {
236
+ this._headers["content-type"] = "application/json";
237
+ }
238
+ res = Response.json(data, {
239
+ status,
240
+ headers: this._headers as any
241
+ });
112
242
  }
113
243
 
114
- // Ensure Content-Type is set to application/json
115
- if (this._headers["content-type"] === undefined) {
116
- this._headers["content-type"] = "application/json";
244
+ if (this._setCookies) {
245
+ for (let i = 0; i < this._setCookies.length; i++) {
246
+ res.headers.append('Set-Cookie', this._setCookies[i]!);
247
+ }
117
248
  }
118
-
119
- return Response.json(data, {
120
- status,
121
- headers: this._headers as any // ⚠️ FIX TS18046: Cast to 'any' to allow assignment to 'unknown' headers
122
- });
249
+ return res;
123
250
  }
124
251
 
125
252
  public set(key: string, value: any): this {
@@ -133,9 +260,14 @@ export class Context {
133
260
 
134
261
  public setHeader(name: string, value: string): this {
135
262
  if (!this._headers) this._headers = {};
263
+ else if (Object.isFrozen(this._headers)) this._headers = { ...this._headers };
136
264
  this._headers[name.toLowerCase()] = value;
137
265
  return this;
138
266
  }
267
+
268
+ public get user(): AuthUser | undefined {
269
+ return this.store.get('user');
270
+ }
139
271
 
140
272
 
141
273
  public send(message: string, extra: Record<string, any> = {}): Response {
@@ -148,6 +280,30 @@ export class Context {
148
280
  });
149
281
  }
150
282
 
283
+ public html(content: string, status?: number): Response {
284
+ const headers: Record<string, string> = {
285
+ 'content-type': 'text/html; charset=utf-8',
286
+ ...(this._headers || {})
287
+ };
288
+ return new Response(content, { status: status ?? this._status, headers });
289
+ }
290
+
291
+ public text(content: string, status?: number): Response {
292
+ const headers: Record<string, string> = {
293
+ 'content-type': 'text/plain; charset=utf-8',
294
+ ...(this._headers || {})
295
+ };
296
+ return new Response(content, { status: status ?? this._status, headers });
297
+ }
298
+
299
+ public redirect(url: string, status: number = 302): Response {
300
+ const headers: Record<string, string> = {
301
+ 'location': url,
302
+ ...(this._headers || {})
303
+ };
304
+ return new Response(null, { status, headers });
305
+ }
306
+
151
307
  public sse(
152
308
  source:
153
309
  | AsyncIterable<string | { event?: string; data: any; id?: string; retry?: number }>
@@ -203,4 +359,77 @@ export class Context {
203
359
  };
204
360
  return new Response(stream, { status: this._status || 200, headers });
205
361
  }
362
+
363
+ public get requestId(): string {
364
+ if (this._requestId !== undefined) return this._requestId;
365
+ const hdr = this.req?.headers?.get('x-request-id');
366
+ this._requestId = hdr && hdr.length > 0 && hdr.length <= 128 ? hdr : crypto.randomUUID();
367
+ return this._requestId;
368
+ }
369
+
370
+ public get ip(): string {
371
+ const xff = this.req?.headers?.get('x-forwarded-for');
372
+ if (xff) return xff.split(',')[0]!.trim();
373
+ return (
374
+ this.req?.headers?.get('x-real-ip') ||
375
+ this.req?.headers?.get('cf-connecting-ip') ||
376
+ '127.0.0.1'
377
+ );
378
+ }
379
+
380
+ public async upload(options: UploadOptions = {}): Promise<UploadResult> {
381
+ const maxFileSize = options.maxFileSize ?? 5 * 1024 * 1024;
382
+ const maxFiles = options.maxFiles ?? 10;
383
+ const allowed = options.allowedTypes ? new Set(options.allowedTypes) : null;
384
+
385
+ const ct = this.req?.headers?.get('content-type') || '';
386
+ if (!ct.includes('multipart/form-data')) {
387
+ throw Object.assign(new Error('Expected multipart/form-data'), { status: 400 });
388
+ }
389
+
390
+ const contentLen = Number(this.req?.headers?.get('content-length') || 0);
391
+ if (contentLen > maxFileSize * maxFiles + 65536) {
392
+ throw Object.assign(new Error('Payload Too Large'), { status: 413 });
393
+ }
394
+
395
+ const form = await this.req.formData();
396
+ const fields: Record<string, string> = {};
397
+ const files: UploadedFile[] = [];
398
+
399
+ for (const [fieldName, value] of form.entries()) {
400
+ if (typeof value === 'string') {
401
+ if (fieldName !== '__proto__' && fieldName !== 'constructor' && fieldName !== 'prototype') {
402
+ fields[fieldName] = value;
403
+ }
404
+ continue;
405
+ }
406
+
407
+ const fileObj = value as unknown as File;
408
+ if (files.length >= maxFiles) {
409
+ throw Object.assign(new Error(`Too many files (max ${maxFiles})`), { status: 413 });
410
+ }
411
+ if (fileObj.size > maxFileSize) {
412
+ throw Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
413
+ }
414
+ const mime = (fileObj.type || '').split(';')[0]!.trim().toLowerCase();
415
+ if (allowed && !allowed.has(mime)) {
416
+ throw Object.assign(new Error(`Unsupported file type: ${fileObj.type || 'unknown'}`), { status: 415 });
417
+ }
418
+
419
+ const rawName = fileObj.name || 'file';
420
+ const baseName = rawName.split(/[\\/]/).pop() || 'file';
421
+ const safeName = baseName.replace(/[^a-zA-Z0-9._-]/g, '_').replace(/^\.+/, '') || 'file';
422
+
423
+ files.push({
424
+ fieldName,
425
+ filename: rawName,
426
+ safeName,
427
+ type: fileObj.type,
428
+ size: fileObj.size,
429
+ file: fileObj
430
+ });
431
+ }
432
+
433
+ return { fields, files };
434
+ }
206
435
  }
package/src/core/radix.ts CHANGED
@@ -5,13 +5,18 @@ export class RadixNode {
5
5
  public staticKeys: string[] = [];
6
6
  public paramNode: RadixNode | null = null;
7
7
  public paramName: string | null = null;
8
+ public wildcardNode: RadixNode | null = null;
8
9
  public handlers: Record<string, Function> = {};
9
10
 
10
11
  public insert(path: string, method: string, handler: Function) {
11
12
  let node: RadixNode = this;
12
13
  const parts = path.split('/').filter(Boolean);
13
14
  for (const part of parts) {
14
- if (part.startsWith(':')) {
15
+ if (part === '*') {
16
+ if (!node.wildcardNode) node.wildcardNode = new RadixNode();
17
+ node = node.wildcardNode;
18
+ break;
19
+ } else if (part.startsWith(':')) {
15
20
  if (!node.paramNode) node.paramNode = new RadixNode();
16
21
  node.paramName = part.slice(1);
17
22
  node = node.paramNode;
@@ -69,6 +74,9 @@ export class RadixNode {
69
74
  if (node.paramNode) {
70
75
  ctx.params[node.paramName!] = url.slice(i, j);
71
76
  node = node.paramNode;
77
+ } else if (node.wildcardNode) {
78
+ ctx.params['*'] = url.slice(i);
79
+ return node.wildcardNode.handlers[method] || null;
72
80
  } else return null;
73
81
  }
74
82
  i = j + 1;
@@ -125,8 +133,19 @@ export class RadixNode {
125
133
  code += `${indent} }\n`;
126
134
  code += `${indent}}\n`;
127
135
 
136
+ } else if (this.staticKeys.length > 4) {
137
+ code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
138
+ code += `${indent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
139
+ code += `${indent}switch (${pathPrefix}.slice(${idxPrefix}, slash${level})) {\n`;
140
+ for (const key of this.staticKeys) {
141
+ code += `${indent} case ${JSON.stringify(key)}: {\n`;
142
+ const child = this.children[key]!;
143
+ code += child.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, paramAccumulator);
144
+ code += `${indent} break;\n`;
145
+ code += `${indent} }\n`;
146
+ }
147
+ code += `${indent}}\n`;
128
148
  } else {
129
-
130
149
  code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
131
150
  code += `${indent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
132
151
  code += `${indent}const len${level} = slash${level} - (${idxPrefix});\n\n`;
@@ -165,7 +184,7 @@ export class RadixNode {
165
184
  // 2. Param Node Logic (Fallback)
166
185
  if (this.paramNode) {
167
186
  const pNode = this.paramNode;
168
- if (this.staticKeys.length === 0) {
187
+ if (this.staticKeys.length <= 1) {
169
188
  code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
170
189
  code += `${indent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
171
190
  }
@@ -177,6 +196,21 @@ export class RadixNode {
177
196
  code += pNode.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, newAccumulator);
178
197
  }
179
198
 
199
+ // 3. Wildcard Node Logic (Catch-All *)
200
+ if (this.wildcardNode && Object.keys(this.wildcardNode.handlers).length > 0) {
201
+ const wVar = `wL${level}`;
202
+ code += `${indent}const ${wVar} = ${pathPrefix}.slice(${idxPrefix}, urlLen);\n`;
203
+ const wAcc = [...paramAccumulator, { name: '*', varName: wVar }];
204
+ const props = wAcc.map((p: any) => `${JSON.stringify(p.name)}: ${p.varName}`).join(', ');
205
+ code += `${indent}ctx.params = { ${props} };\n`;
206
+ code += `${indent}switch(method) {\n`;
207
+ for (const [m, h] of Object.entries(this.wildcardNode.handlers)) {
208
+ const hName = register(h as Function);
209
+ code += `${indent} case ${JSON.stringify(m)}: return ${hName}(ctx);\n`;
210
+ }
211
+ code += `${indent}}\n`;
212
+ }
213
+
180
214
  return code;
181
215
  }
182
216
 
@@ -3,8 +3,9 @@ import {
3
3
  type Handler,
4
4
  type GroupCallback
5
5
  } from '../core/context';
6
+ import { schemaValidator, type RouteSchemas } from '../security/validators';
6
7
 
7
- type HandlersChain = (Middleware | Handler)[];
8
+ type HandlersChain = (Middleware | Handler | RouteSchemas)[];
8
9
 
9
10
  export class BareRouter {
10
11
  public routes: any[] = [];
@@ -16,16 +17,24 @@ export class BareRouter {
16
17
 
17
18
  private _add(method: string, path: string, handlers: HandlersChain) {
18
19
  let fullPath = (this.prefix + "/" + path)
19
- .replace(/\/+/g, "/")
20
-
21
-
20
+ .replace(/\/+/g, "/");
22
21
 
23
22
  if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
24
23
 
24
+ const resolvedHandlers: any[] = [];
25
+ for (let i = 0; i < handlers.length; i++) {
26
+ const h = handlers[i];
27
+ if (typeof h === 'function') {
28
+ resolvedHandlers.push(h);
29
+ } else if (h && typeof h === 'object') {
30
+ resolvedHandlers.push(schemaValidator(h as RouteSchemas));
31
+ }
32
+ }
33
+
25
34
  this.routes.push({
26
35
  method: method.toUpperCase(),
27
36
  path: fullPath || "",
28
- handlers: [...this.groupMiddleware, ...handlers]
37
+ handlers: [...this.groupMiddleware, ...resolvedHandlers]
29
38
  });
30
39
  return this;
31
40
  }
@@ -53,6 +62,8 @@ export class BareRouter {
53
62
  public use(mw: any) {
54
63
  if (mw instanceof BareRouter || (mw && mw.routes)) {
55
64
  this.routes.push(...mw.routes);
65
+ } else if (mw && typeof mw.install === 'function') {
66
+ mw.install(this);
56
67
  } else {
57
68
  this.groupMiddleware.push(mw);
58
69
  }
package/src/index.ts CHANGED
@@ -16,13 +16,17 @@ export interface BarePlugin {
16
16
  }
17
17
 
18
18
  // --- 2. Context & Types ---
19
+ export { Context } from './core/context';
19
20
  export type {
20
21
  Middleware,
21
22
  Handler,
22
23
  Next,
23
- Context,
24
24
  Params,
25
- AuthUser
25
+ AuthUser,
26
+ CookieOptions,
27
+ UploadOptions,
28
+ UploadedFile,
29
+ UploadResult
26
30
  } from './core/context';
27
31
 
28
32
  // --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
@@ -30,7 +34,7 @@ import { Type } from "@sinclair/typebox";
30
34
  export { Type, Type as T, Type as TypeBox };
31
35
 
32
36
  // --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
33
- import { typebox, zod, native, validate, Z } from './security/validators';
37
+ import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
34
38
  export {
35
39
  // TypeBox Engine
36
40
  typebox,
@@ -45,15 +49,23 @@ export {
45
49
  native as n,
46
50
  // Auto-Detect Engine
47
51
  validate,
48
- validate as v
52
+ validate as v,
53
+ // Unified Route Schema Engine (body, query, params, headers, response, detail, maxBodySize)
54
+ schemaValidator,
55
+ createResponseFilter,
56
+ type RouteSchemas,
57
+ type RouteDetail
49
58
  };
50
59
 
51
60
  // --- 5. Middlewares & Utilities ---
52
61
  // export { logger } from './utils/logger';
53
62
  export { cors } from './security/cors';
63
+ export { csrf, type CsrfOptions } from './security/csrf';
64
+ export { timeout, type TimeoutOptions } from './security/timeout';
54
65
  export { rateLimit, type RateLimitOptions } from './security/rateLimit';
66
+ export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
55
67
  export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
56
- export { staticFile } from './utils/static';
68
+ export { staticFile, type StaticOptions } from './utils/static';
57
69
  export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
58
70
  export { BareRouter } from './core/router';
59
71
 
@@ -58,7 +58,8 @@ export const createToken = async (payload: object, secret: string): Promise<stri
58
58
  * 1. BARE TOKEN AUTH (Standard JWT Middleware)
59
59
  * High-performance, constant-time JWT middleware for BareJS
60
60
  */
61
- export const bareAuth = (secret: string) => {
61
+ export const bareAuth = (secretOrOpts: string | { secret: string }) => {
62
+ const secret = typeof secretOrOpts === 'string' ? secretOrOpts : secretOrOpts.secret;
62
63
  return (ctx: any, next: any) => {
63
64
  const authHeader = ctx.req.headers.get('Authorization');
64
65