barejs 0.1.48 → 0.1.49

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.
@@ -12,19 +12,58 @@ export class Context {
12
12
  public _headers?: Record<string, string> | undefined = undefined;
13
13
  public store = new Map<string, any>();
14
14
  public body: any = undefined;
15
- public query: Record<string, string> = {};
15
+ public _query: Record<string, string> | undefined = undefined;
16
16
  constructor() { }
17
17
 
18
+ public get query(): Record<string, string> {
19
+ if (this._query !== undefined) return this._query;
20
+ const result: Record<string, string> = {};
21
+ const url = this.req?.url;
22
+ if (url) {
23
+ const qIdx = url.indexOf('?');
24
+ if (qIdx !== -1) {
25
+ let start = qIdx + 1;
26
+ const len = url.length;
27
+ while (start < len) {
28
+ let amp = url.indexOf('&', start);
29
+ if (amp === -1) amp = len;
30
+ if (amp > start) {
31
+ const eq = url.indexOf('=', start);
32
+ let k: string;
33
+ let v: string;
34
+ if (eq !== -1 && eq < amp) {
35
+ k = url.slice(start, eq);
36
+ v = url.slice(eq + 1, amp);
37
+ } else {
38
+ k = url.slice(start, amp);
39
+ v = '';
40
+ }
41
+ try {
42
+ k = decodeURIComponent(k.replace(/\+/g, ' '));
43
+ v = decodeURIComponent(v.replace(/\+/g, ' '));
44
+ } catch { /* keep raw on malformed URI */ }
45
+ if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
46
+ result[k] = v;
47
+ }
48
+ }
49
+ start = amp + 1;
50
+ }
51
+ }
52
+ }
53
+ this._query = result;
54
+ return result;
55
+ }
18
56
 
19
- public async jsonBody(): Promise<any> {
57
+ public getQuery(key: string): string | undefined {
58
+ return this.query[key];
59
+ }
20
60
 
61
+ public async jsonBody(): Promise<any> {
21
62
  if (this.body !== undefined) return this.body;
22
63
 
23
-
24
64
  const contentType = this.req.headers.get("content-type");
25
65
  if (contentType && contentType.includes("application/json")) {
26
66
  try {
27
-
28
67
  return this.body = await this.req.json();
29
68
  } catch {
30
69
  return this.body = null;
@@ -33,14 +72,13 @@ export class Context {
33
72
  return this.body = null;
34
73
  }
35
74
 
36
-
37
75
  public reset(req: Request): this {
38
76
  this.req = req;
39
77
  this._status = 200;
40
78
  this._headers = undefined;
41
79
  if (this.store.size > 0) this.store.clear();
42
80
  this.params = {};
43
- this.query = {};
81
+ this._query = undefined;
44
82
  this.body = undefined;
45
83
  return this;
46
84
  }
@@ -109,4 +147,60 @@ export class Context {
109
147
  ...extra
110
148
  });
111
149
  }
150
+
151
+ public sse(
152
+ source:
153
+ | AsyncIterable<string | { event?: string; data: any; id?: string; retry?: number }>
154
+ | ((send: (data: any, event?: string, id?: string) => void, close: () => void) => Promise<void> | void)
155
+ ): Response {
156
+ const encoder = new TextEncoder();
157
+ const formatChunk = (chunk: string | { event?: string; data: any; id?: string; retry?: number }): Uint8Array => {
158
+ if (typeof chunk === 'string') {
159
+ return encoder.encode(`data: ${chunk}\n\n`);
160
+ }
161
+ let out = '';
162
+ if (chunk.id !== undefined) out += `id: ${chunk.id}\n`;
163
+ if (chunk.event !== undefined) out += `event: ${chunk.event}\n`;
164
+ if (chunk.retry !== undefined) out += `retry: ${chunk.retry}\n`;
165
+ const payload = typeof chunk.data === 'string' ? chunk.data : JSON.stringify(chunk.data);
166
+ out += `data: ${payload}\n\n`;
167
+ return encoder.encode(out);
168
+ };
169
+
170
+ const stream = new ReadableStream<Uint8Array>({
171
+ async start(controller) {
172
+ try {
173
+ if (typeof source === 'function') {
174
+ let closed = false;
175
+ const send = (data: any, event?: string, id?: string) => {
176
+ if (!closed) controller.enqueue(formatChunk({ data, event, id }));
177
+ };
178
+ const close = () => {
179
+ if (!closed) {
180
+ closed = true;
181
+ controller.close();
182
+ }
183
+ };
184
+ await source(send, close);
185
+ close();
186
+ } else {
187
+ for await (const item of source) {
188
+ controller.enqueue(formatChunk(item));
189
+ }
190
+ controller.close();
191
+ }
192
+ } catch (err) {
193
+ controller.error(err);
194
+ }
195
+ }
196
+ });
197
+
198
+ const headers: Record<string, string> = {
199
+ 'content-type': 'text/event-stream; charset=utf-8',
200
+ 'cache-control': 'no-cache, no-transform',
201
+ 'connection': 'keep-alive',
202
+ ...(this._headers || {})
203
+ };
204
+ return new Response(stream, { status: this._status || 200, headers });
205
+ }
112
206
  }
@@ -35,6 +35,7 @@ export class BareRouter {
35
35
  public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
36
36
  public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
37
37
  public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
38
+ public options = (path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h);
38
39
 
39
40
  public group = (path: string, ...args: any[]) => {
40
41
  const callback = args.pop();
package/src/index.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
 
8
8
  // --- 1. Core Engine ---
9
- export { BareJS } from './core/bare';
9
+ export { BareJS, type WebSocketRouteHandler } from './core/bare';
10
10
 
11
11
  /**
12
12
  * Plugin Interface for BareJS
@@ -51,11 +51,23 @@ export {
51
51
  // --- 5. Middlewares & Utilities ---
52
52
  // export { logger } from './utils/logger';
53
53
  export { cors } from './security/cors';
54
+ export { rateLimit, type RateLimitOptions } from './security/rateLimit';
55
+ export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
54
56
  export { staticFile } from './utils/static';
57
+ export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
55
58
  export { BareRouter } from './core/router';
56
59
 
57
60
  // --- 6. Authentication (Bun Native) ---
58
61
  // Always deploy using process.env [2026-01-06]
59
- export { bareAuth, createToken } from './security/auth';
62
+ export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
60
63
  // --- 7. Hashing ---
61
- export{Hash as Password, Hash} from './security/hash';
64
+ export { Hash as Password, Hash } from './security/hash';
65
+
66
+ // --- 8. Type-Safe RPC Client ---
67
+ export {
68
+ bareClient,
69
+ type BareClient,
70
+ type BareClientOptions,
71
+ type ClientRequestOptions,
72
+ type RouteSchema
73
+ } from './client/index';
@@ -0,0 +1,59 @@
1
+ import type { Middleware } from '../core/context';
2
+
3
+ export interface SecurityHeadersOptions {
4
+ contentSecurityPolicy?: string | false;
5
+ frameOptions?: 'DENY' | 'SAMEORIGIN' | false;
6
+ hsts?: string | false;
7
+ referrerPolicy?: string | false;
8
+ noSniff?: boolean;
9
+ }
10
+
11
+ export const securityHeaders = (options: SecurityHeadersOptions = {}): Middleware => {
12
+ const headersToSet: [string, string][] = [];
13
+
14
+ if (options.noSniff !== false) {
15
+ headersToSet.push(['X-Content-Type-Options', 'nosniff']);
16
+ }
17
+ if (options.frameOptions !== false) {
18
+ headersToSet.push(['X-Frame-Options', options.frameOptions ?? 'DENY']);
19
+ }
20
+ if (options.referrerPolicy !== false) {
21
+ headersToSet.push(['Referrer-Policy', options.referrerPolicy ?? 'strict-origin-when-cross-origin']);
22
+ }
23
+ if (options.hsts !== false) {
24
+ headersToSet.push(['Strict-Transport-Security', options.hsts ?? 'max-age=31536000; includeSubDomains']);
25
+ }
26
+ if (options.contentSecurityPolicy) {
27
+ headersToSet.push(['Content-Security-Policy', options.contentSecurityPolicy]);
28
+ }
29
+ headersToSet.push(['X-XSS-Protection', '0']);
30
+
31
+ const len = headersToSet.length;
32
+
33
+ return (ctx, next) => {
34
+ for (let i = 0; i < len; i++) {
35
+ const pair = headersToSet[i]!;
36
+ ctx.setHeader(pair[0], pair[1]);
37
+ }
38
+
39
+ const res = next?.();
40
+ if (res && typeof (res as any).then === 'function') {
41
+ return (res as Promise<any>).then((r) => {
42
+ if (r instanceof Response) {
43
+ for (let i = 0; i < len; i++) {
44
+ const pair = headersToSet[i]!;
45
+ if (!r.headers.has(pair[0])) r.headers.set(pair[0], pair[1]);
46
+ }
47
+ }
48
+ return r;
49
+ });
50
+ }
51
+ if (res instanceof Response) {
52
+ for (let i = 0; i < len; i++) {
53
+ const pair = headersToSet[i]!;
54
+ if (!res.headers.has(pair[0])) res.headers.set(pair[0], pair[1]);
55
+ }
56
+ }
57
+ return res;
58
+ };
59
+ };
@@ -0,0 +1,76 @@
1
+ import type { Context, Middleware } from '../core/context';
2
+
3
+ export interface RateLimitOptions {
4
+ windowMs?: number;
5
+ max?: number;
6
+ message?: string;
7
+ keyGenerator?: (ctx: Context) => string;
8
+ maxEntries?: number;
9
+ }
10
+
11
+ interface RateBucket {
12
+ count: number;
13
+ resetAt: number;
14
+ }
15
+
16
+ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
17
+ const windowMs = options.windowMs ?? 60_000;
18
+ const max = options.max ?? 100;
19
+ const message = options.message ?? 'Too many requests, please try again later.';
20
+ const maxEntries = options.maxEntries ?? 10_000;
21
+ const keyGenerator =
22
+ options.keyGenerator ??
23
+ ((ctx: Context) =>
24
+ ctx.req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
25
+ ctx.req.headers.get('x-real-ip') ||
26
+ 'global');
27
+
28
+ const buckets = new Map<string, RateBucket>();
29
+
30
+ return (ctx, next) => {
31
+ const now = Date.now();
32
+ const key = keyGenerator(ctx);
33
+ let bucket = buckets.get(key);
34
+
35
+ if (!bucket || now >= bucket.resetAt) {
36
+ // Prevent unbounded memory growth under key-flooding DoS
37
+ if (buckets.size >= maxEntries) {
38
+ for (const [k, v] of buckets) {
39
+ if (now >= v.resetAt) buckets.delete(k);
40
+ if (buckets.size < maxEntries) break;
41
+ }
42
+ if (buckets.size >= maxEntries) {
43
+ const firstKey = buckets.keys().next().value;
44
+ if (firstKey !== undefined) buckets.delete(firstKey);
45
+ }
46
+ }
47
+ bucket = { count: 1, resetAt: now + windowMs };
48
+ buckets.set(key, bucket);
49
+ } else {
50
+ bucket.count++;
51
+ }
52
+
53
+ const remaining = Math.max(0, max - bucket.count);
54
+ ctx.setHeader('X-RateLimit-Limit', String(max));
55
+ ctx.setHeader('X-RateLimit-Remaining', String(remaining));
56
+ ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(bucket.resetAt / 1000)));
57
+
58
+ if (bucket.count > max) {
59
+ const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000));
60
+ return Response.json(
61
+ { status: 'error', code: 'RATE_LIMITED', message },
62
+ {
63
+ status: 429,
64
+ headers: {
65
+ 'Retry-After': String(retryAfter),
66
+ 'X-RateLimit-Limit': String(max),
67
+ 'X-RateLimit-Remaining': '0',
68
+ 'X-RateLimit-Reset': String(Math.ceil(bucket.resetAt / 1000))
69
+ }
70
+ }
71
+ );
72
+ }
73
+
74
+ return next?.();
75
+ };
76
+ };
@@ -30,9 +30,8 @@ const errorJSON = (data: any, status = 400) =>
30
30
  export const typebox = (schema: any): Middleware => {
31
31
  const check = Compiler.TypeCompiler.Compile(schema);
32
32
 
33
- return async (ctx: Context, next?: Next) => {
33
+ const mw: Middleware = async (ctx: Context, next?: Next) => {
34
34
  try {
35
- // const body = await ctx.req.json();
36
35
  const body = await ctx.jsonBody();
37
36
 
38
37
  if (!check.Check(body)) {
@@ -45,13 +44,14 @@ export const typebox = (schema: any): Middleware => {
45
44
  });
46
45
  }
47
46
 
48
- // ✅ FIX TS18046: Cast to 'any' to allow assignment to 'unknown' body
49
47
  (ctx as any).body = body;
50
48
  return next ? next() : undefined;
51
49
  } catch {
52
50
  return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
53
51
  }
54
52
  };
53
+ (mw as any).__schema = schema;
54
+ return mw;
55
55
  };
56
56
 
57
57
  /**
@@ -62,7 +62,7 @@ export const native = (schema: any): Middleware => {
62
62
  const keys = Object.keys(props);
63
63
  const kLen = keys.length;
64
64
 
65
- return async (ctx: any, next?: any) => {
65
+ const mw: Middleware = async (ctx: any, next?: any) => {
66
66
  try {
67
67
  const isCtx = ctx instanceof Object && 'req' in ctx;
68
68
  const body = isCtx ? await ctx.jsonBody() : await ctx.json();
@@ -90,13 +90,15 @@ export const native = (schema: any): Middleware => {
90
90
  return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
91
91
  }
92
92
  };
93
+ (mw as any).__schema = schema;
94
+ return mw;
93
95
  };
94
96
 
95
97
  /**
96
98
  * Zod Engine (z)
97
99
  */
98
100
  export const zod = (schema: z.ZodSchema): Middleware => {
99
- return async (ctx: any, next?: any) => {
101
+ const mw: Middleware = async (ctx: any, next?: any) => {
100
102
  try {
101
103
  const isCtx = ctx instanceof Object && 'req' in ctx;
102
104
  const body = isCtx ? await ctx.jsonBody() : await ctx.json();
@@ -118,6 +120,8 @@ export const zod = (schema: z.ZodSchema): Middleware => {
118
120
  return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
119
121
  }
120
122
  };
123
+ (mw as any).__schema = schema;
124
+ return mw;
121
125
  };
122
126
 
123
127
  /**
@@ -0,0 +1,116 @@
1
+ export interface OpenAPIOptions {
2
+ title?: string;
3
+ version?: string;
4
+ description?: string;
5
+ }
6
+
7
+ const zodToJsonSchema = (schema: any): Record<string, any> => {
8
+ if (!schema || !schema._def) return { type: 'object' };
9
+ const def = schema._def;
10
+ const typeName = def.typeName;
11
+
12
+ if (typeName === 'ZodObject') {
13
+ const shape = typeof def.shape === 'function' ? def.shape() : def.shape;
14
+ const properties: Record<string, any> = {};
15
+ const required: string[] = [];
16
+ for (const [k, v] of Object.entries(shape || {})) {
17
+ const child = v as any;
18
+ properties[k] = zodToJsonSchema(child);
19
+ if (child?._def?.typeName !== 'ZodOptional' && child?._def?.typeName !== 'ZodDefault') {
20
+ required.push(k);
21
+ }
22
+ }
23
+ return { type: 'object', properties, ...(required.length ? { required } : {}) };
24
+ }
25
+ if (typeName === 'ZodString') return { type: 'string' };
26
+ if (typeName === 'ZodNumber') return { type: 'number' };
27
+ if (typeName === 'ZodBoolean') return { type: 'boolean' };
28
+ if (typeName === 'ZodArray') return { type: 'array', items: zodToJsonSchema(def.type) };
29
+ if (typeName === 'ZodOptional' || typeName === 'ZodDefault') return zodToJsonSchema(def.innerType);
30
+ if (typeName === 'ZodEnum') return { type: 'string', enum: def.values };
31
+ return { type: 'object' };
32
+ };
33
+
34
+ const extractSchema = (schema: any): Record<string, any> => {
35
+ if (!schema) return { type: 'object' };
36
+ if ('_def' in schema) return zodToJsonSchema(schema);
37
+ // TypeBox or plain JSON Schema
38
+ return JSON.parse(JSON.stringify(schema));
39
+ };
40
+
41
+ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {}) => {
42
+ const paths: Record<string, Record<string, any>> = {};
43
+
44
+ for (const route of routes) {
45
+ if (route.path === '/docs' || route.path === '/docs/json') continue;
46
+
47
+ const openApiPath = ('/' + route.path)
48
+ .replace(/\/+/g, '/')
49
+ .replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
50
+
51
+ if (!paths[openApiPath]) paths[openApiPath] = {};
52
+
53
+ const method = route.method.toLowerCase();
54
+ const params: any[] = [];
55
+ const paramMatches = route.path.matchAll(/:([a-zA-Z0-9_]+)/g);
56
+ for (const m of paramMatches) {
57
+ params.push({
58
+ name: m[1],
59
+ in: 'path',
60
+ required: true,
61
+ schema: { type: 'string' }
62
+ });
63
+ }
64
+
65
+ let requestBody: any = undefined;
66
+ for (const h of route.handlers) {
67
+ if (h && (h as any).__schema) {
68
+ requestBody = {
69
+ required: true,
70
+ content: {
71
+ 'application/json': {
72
+ schema: extractSchema((h as any).__schema)
73
+ }
74
+ }
75
+ };
76
+ break;
77
+ }
78
+ }
79
+
80
+ paths[openApiPath][method] = {
81
+ summary: `${route.method} ${openApiPath}`,
82
+ ...(params.length ? { parameters: params } : {}),
83
+ ...(requestBody ? { requestBody } : {}),
84
+ responses: {
85
+ '200': { description: 'Success' }
86
+ }
87
+ };
88
+ }
89
+
90
+ return {
91
+ openapi: '3.1.0',
92
+ info: {
93
+ title: options.title || 'BareJS API',
94
+ version: options.version || '1.0.0',
95
+ ...(options.description ? { description: options.description } : {})
96
+ },
97
+ paths
98
+ };
99
+ };
100
+
101
+ export const renderDocsHTML = (specUrl: string, title: string = 'BareJS API Docs'): string => {
102
+ const safeTitle = title.replace(/[<>&"]/g, '');
103
+ const safeSpecUrl = JSON.stringify(specUrl);
104
+ return `<!doctype html>
105
+ <html>
106
+ <head>
107
+ <title>${safeTitle}</title>
108
+ <meta charset="utf-8" />
109
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
110
+ </head>
111
+ <body>
112
+ <script id="api-reference" data-url=${safeSpecUrl}></script>
113
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
114
+ </body>
115
+ </html>`;
116
+ };