barejs 0.1.45 → 0.1.48

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,68 +1,60 @@
1
- import {
2
- type Middleware,
3
- type Handler,
4
- type GroupCallback
5
- } from '../core/context';
6
-
7
- type HandlersChain = (Middleware | Handler)[];
8
-
9
- export class BareRouter {
10
- public routes: { method: string; path: string; handlers: any[] }[] = [];
11
-
12
- constructor(
13
- public prefix: string = "",
14
- public groupMiddleware: any[] = []
15
- ) { }
16
-
17
- private _add(method: string, path: string, handlers: HandlersChain) {
18
- const fullPath = (this.prefix + path).replace(/\/+/g, "/") || "/";
19
-
20
- this.routes.push({
21
- method: method.toUpperCase(),
22
- path: fullPath,
23
- handlers: [...this.groupMiddleware, ...handlers]
24
- });
25
- return this;
26
- }
27
-
28
- public get = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
29
- public post = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
30
- public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
31
- public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
32
- public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
33
-
34
- public group = (path: string, ...args: any[]) => {
35
- const callback = args.pop() as GroupCallback;
36
- const middleware = args;
37
-
38
- const subRouter = new BareRouter(
39
- (this.prefix + path).replace(/\/+/g, "/"),
40
- [...this.groupMiddleware, ...middleware]
41
- );
42
-
43
- callback(subRouter);
44
- this.routes.push(...subRouter.routes);
45
- return this;
46
- };
47
-
48
- /**
49
- * 🔗 Use: Mounts a router or middleware
50
- * Supports nested routers with automatic path prefixing
51
- */
52
- public use(mw: any) {
53
- if (mw && mw.routes && Array.isArray(mw.routes)) {
54
- // Merge routes from the sub-router
55
- const mergedRoutes = mw.routes.map((r: any) => ({
56
- ...r,
57
- // Prepend current router's prefix to the sub-router's path
58
- // e.g. v1 (/v1) using auth (/auth/login) -> /v1/auth/login
59
- path: (this.prefix + r.path).replace(/\/+/g, "/") || "/",
60
- handlers: [...this.groupMiddleware, ...r.handlers]
61
- }));
62
- this.routes.push(...mergedRoutes);
63
- } else {
64
- this.groupMiddleware.push(mw);
65
- }
66
- return this;
67
- }
68
- }
1
+ import {
2
+ type Middleware,
3
+ type Handler,
4
+ type GroupCallback
5
+ } from '../core/context';
6
+
7
+ type HandlersChain = (Middleware | Handler)[];
8
+
9
+ export class BareRouter {
10
+ public routes: any[] = [];
11
+
12
+ constructor(
13
+ public prefix: string = "",
14
+ public groupMiddleware: any[] = []
15
+ ) { }
16
+
17
+ private _add(method: string, path: string, handlers: HandlersChain) {
18
+ let fullPath = (this.prefix + "/" + path)
19
+ .replace(/\/+/g, "/")
20
+
21
+
22
+
23
+ if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
24
+
25
+ this.routes.push({
26
+ method: method.toUpperCase(),
27
+ path: fullPath || "",
28
+ handlers: [...this.groupMiddleware, ...handlers]
29
+ });
30
+ return this;
31
+ }
32
+
33
+ public get = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
34
+ public post = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
35
+ public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
36
+ public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
37
+ public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
38
+
39
+ public group = (path: string, ...args: any[]) => {
40
+ const callback = args.pop();
41
+ const middleware = args;
42
+
43
+
44
+ const newPrefix = (this.prefix + "/" + path).replace(/\/+/g, "/");
45
+ const subRouter = new BareRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
46
+
47
+ callback(subRouter);
48
+ this.routes.push(...subRouter.routes);
49
+ return this;
50
+ };
51
+
52
+ public use(mw: any) {
53
+ if (mw instanceof BareRouter || (mw && mw.routes)) {
54
+ this.routes.push(...mw.routes);
55
+ } else {
56
+ this.groupMiddleware.push(mw);
57
+ }
58
+ return this;
59
+ }
60
+ }
package/src/index.ts CHANGED
@@ -1,61 +1,61 @@
1
- /**
2
- * BareJS: The Metal of Web Frameworks
3
- * All comments must be in English [2026-01-06]
4
- * Built for Bun with Mechanical Sympathy
5
- * Optimized to outperform competitors by 55% [2026-01-05]
6
- */
7
-
8
- // --- 1. Core Engine ---
9
- export { BareJS } from './core/bare';
10
-
11
- /**
12
- * Plugin Interface for BareJS
13
- */
14
- export interface BarePlugin {
15
- install: (app: any) => void;
16
- }
17
-
18
- // --- 2. Context & Types ---
19
- export type {
20
- Middleware,
21
- Handler,
22
- Next,
23
- Context,
24
- Params,
25
- AuthUser
26
- } from './core/context';
27
-
28
- // --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
29
- import { Type } from "@sinclair/typebox";
30
- export { Type, Type as T, Type as TypeBox };
31
-
32
- // --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
33
- import { typebox, zod, native, validate, Z } from './security/validators';
34
- export {
35
- // TypeBox Engine
36
- typebox,
37
- typebox as t,
38
- // Zod Engine & Builder
39
- zod,
40
- zod as z,
41
- Z,
42
- Z as Zod,
43
- // Native Engine
44
- native,
45
- native as n,
46
- // Auto-Detect Engine
47
- validate,
48
- validate as v
49
- };
50
-
51
- // --- 5. Middlewares & Utilities ---
52
- export { logger } from './utils/logger';
53
- export { cors } from './security/cors';
54
- export { staticFile } from './utils/static';
55
- export { BareRouter } from './core/router';
56
-
57
- // --- 6. Authentication (Bun Native) ---
58
- // Always deploy using process.env [2026-01-06]
59
- export { bareAuth, createToken } from './security/auth';
60
- // --- 7. Hashing ---
1
+ /**
2
+ * BareJS: The Metal of Web Frameworks
3
+ * All comments must be in English [2026-01-06]
4
+ * Built for Bun with Mechanical Sympathy
5
+ * Optimized to outperform competitors by 55% [2026-01-05]
6
+ */
7
+
8
+ // --- 1. Core Engine ---
9
+ export { BareJS } from './core/bare';
10
+
11
+ /**
12
+ * Plugin Interface for BareJS
13
+ */
14
+ export interface BarePlugin {
15
+ install: (app: any) => void;
16
+ }
17
+
18
+ // --- 2. Context & Types ---
19
+ export type {
20
+ Middleware,
21
+ Handler,
22
+ Next,
23
+ Context,
24
+ Params,
25
+ AuthUser
26
+ } from './core/context';
27
+
28
+ // --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
29
+ import { Type } from "@sinclair/typebox";
30
+ export { Type, Type as T, Type as TypeBox };
31
+
32
+ // --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
33
+ import { typebox, zod, native, validate, Z } from './security/validators';
34
+ export {
35
+ // TypeBox Engine
36
+ typebox,
37
+ typebox as t,
38
+ // Zod Engine & Builder
39
+ zod,
40
+ zod as z,
41
+ Z,
42
+ Z as Zod,
43
+ // Native Engine
44
+ native,
45
+ native as n,
46
+ // Auto-Detect Engine
47
+ validate,
48
+ validate as v
49
+ };
50
+
51
+ // --- 5. Middlewares & Utilities ---
52
+ // export { logger } from './utils/logger';
53
+ export { cors } from './security/cors';
54
+ export { staticFile } from './utils/static';
55
+ export { BareRouter } from './core/router';
56
+
57
+ // --- 6. Authentication (Bun Native) ---
58
+ // Always deploy using process.env [2026-01-06]
59
+ export { bareAuth, createToken } from './security/auth';
60
+ // --- 7. Hashing ---
61
61
  export{Hash as Password, Hash} from './security/hash';
@@ -1,158 +1,175 @@
1
- import type { AuthUser, Next } from '../core/context';
2
- // import { timingSafeEqual } from 'node:crypto';
3
-
4
- /**
5
- * UTILS: Internal Crypto Helpers using Native Web Crypto
6
- * Optimized for Bun performance and type safety.
7
- */
8
- const encoder = new TextEncoder();
9
-
10
- // ⚡ Base64Url Helpers (RFC 4648)
11
- const base64Url = (input: Uint8Array | string): string => {
12
- let base64 = typeof input === 'string'
13
- ? Buffer.from(input).toString('base64')
14
- : Buffer.from(input).toString('base64');
15
- return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
16
- };
17
-
18
- const fromBase64Url = (str: string): string => {
19
- str = str.replace(/-/g, '+').replace(/_/g, '/');
20
- while (str.length % 4) str += '=';
21
- return Buffer.from(str, 'base64').toString();
22
- };
23
-
24
- // ⚡ PERF: Cache CryptoKeys to avoid repeated async importKey calls
25
- const keyCache = new Map<string, CryptoKey>();
26
-
27
- const importKey = async (secret: string): Promise<CryptoKey> => {
28
- if (keyCache.has(secret)) return keyCache.get(secret)!;
29
-
30
- const key = await crypto.subtle.importKey(
31
- "raw",
32
- encoder.encode(secret),
33
- { name: "HMAC", hash: "SHA-256" },
34
- false,
35
- ["sign", "verify"]
36
- );
37
-
38
- keyCache.set(secret, key);
39
- return key;
40
- };
41
-
42
- /**
43
- * 4. TOKEN GENERATOR (Standard JWT)
44
- */
45
- export const createToken = async (payload: object, secret: string): Promise<string> => {
46
- const header = JSON.stringify({ alg: "HS256", typ: "JWT" });
47
- const body = JSON.stringify(payload);
48
-
49
- const encodedHeader = base64Url(header);
50
- const encodedBody = base64Url(body);
51
- const data = `${encodedHeader}.${encodedBody}`;
52
-
53
- const key = await importKey(secret);
54
- const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
55
- const encodedSig = base64Url(new Uint8Array(signature));
56
-
57
- return `${data}.${encodedSig}`;
58
- };
59
-
60
- /**
61
- * 1. BARE TOKEN AUTH (Standard JWT Middleware)
62
- * High-performance JWT alternative for BareJS
63
- */
64
- export const bareAuth = (secret: string) => {
65
- return async (ctx: any, next: any) => {
66
- const authHeader = ctx.req.headers.get('Authorization');
67
- if (!authHeader?.startsWith('Bearer ')) {
68
- return ctx.status(401).json({ message: "Bearer token required" });
69
- }
70
-
71
- const token = authHeader.slice(7);
72
- const parts = token.split('.');
73
-
74
- if (parts.length !== 3) {
75
- return ctx.status(401).json({ message: 'Malformed JWT token' });
76
- }
77
-
78
- const [header, payload, signature] = parts;
79
- const data = `${header}.${payload}`;
80
-
81
- try {
82
- const key = await importKey(secret);
83
-
84
- // Verify Signature
85
- const expectedSig = await crypto.subtle.sign(
86
- "HMAC",
87
- key,
88
- encoder.encode(data)
89
- );
90
-
91
- const validSig = base64Url(new Uint8Array(expectedSig));
92
-
93
- if (signature !== validSig) {
94
- return ctx.status(401).json({ message: 'Invalid signature' });
95
- }
96
-
97
- // Decode Payload
98
- const decoded = JSON.parse(fromBase64Url(payload!));
99
- ctx.set('user', decoded);
100
-
101
- if (Array.isArray(next)) {
102
- if (next.length === 0) return;
103
- const [current, ...rest] = next;
104
- return current(ctx, rest);
105
- }
106
-
107
- if (typeof next === 'function') {
108
- return next();
109
- }
110
- return;
111
-
112
- } catch (e) {
113
- console.error("[Auth] Error:", e);
114
- return ctx.status(401).json({ message: 'Token verification failed' });
115
- }
116
- };
117
- };
118
-
119
- /**
120
- * 2. BASIC AUTH
121
- * Useful for internal tools and simple admin panels
122
- */
123
- export const basicAuth = (credentials: { user: string; pass: string }) => {
124
- return async (ctx: any, next: Next) => {
125
- const authHeader = ctx.req.headers.get('Authorization');
126
- if (!authHeader?.startsWith('Basic ')) {
127
- return ctx.status(401).json({ status: 'error', message: 'Basic Auth required' });
128
- }
129
-
130
- const token = authHeader.split(' ')[1];
131
- if (!token) return ctx.status(401).json({ status: 'error', message: 'Missing credentials' });
132
-
133
- const decoded = Buffer.from(token, 'base64').toString();
134
- const [user, pass] = decoded.split(':');
135
-
136
- if (user === credentials.user && pass === credentials.pass) {
137
- return next();
138
- }
139
-
140
- return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
141
- };
142
- };
143
-
144
-
145
-
146
- /**
147
- * 5. ROLE AUTHORIZATION (Bonus Max Function)
148
- * Ensures user has specific permissions after bareAuth
149
- */
150
- export const hasRole = (role: string) => {
151
- return async (ctx: any, next: Next) => {
152
- const user = ctx.get('user');
153
- if (!user || user.role !== role) {
154
- return ctx.status(403).json({ status: 'error', message: `Required role: ${role}` });
155
- }
156
- return next();
157
- };
1
+ import type { Next } from '../core/context';
2
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
3
+
4
+ /**
5
+ * UTILS: Internal Crypto Helpers using Native Web Crypto & Node Crypto
6
+ * Optimized for Bun performance and constant-time security.
7
+ */
8
+ const encoder = new TextEncoder();
9
+
10
+ // Base64Url Helpers (RFC 4648) using native C++ Buffer encoding
11
+ const base64Url = (input: Uint8Array | string): string => {
12
+ return typeof input === 'string'
13
+ ? Buffer.from(input).toString('base64url')
14
+ : Buffer.from(input).toString('base64url');
15
+ };
16
+
17
+ const fromBase64Url = (str: string): string => {
18
+ return Buffer.from(str, 'base64url').toString('utf-8');
19
+ };
20
+
21
+ // PERF: Cache CryptoKeys to avoid repeated async importKey calls for createToken
22
+ const keyCache = new Map<string, CryptoKey>();
23
+
24
+ const importKey = async (secret: string): Promise<CryptoKey> => {
25
+ if (keyCache.has(secret)) return keyCache.get(secret)!;
26
+
27
+ const key = await crypto.subtle.importKey(
28
+ "raw",
29
+ encoder.encode(secret),
30
+ { name: "HMAC", hash: "SHA-256" },
31
+ false,
32
+ ["sign", "verify"]
33
+ );
34
+
35
+ keyCache.set(secret, key);
36
+ return key;
37
+ };
38
+
39
+ /**
40
+ * 4. TOKEN GENERATOR (Standard JWT)
41
+ */
42
+ export const createToken = async (payload: object, secret: string): Promise<string> => {
43
+ const header = JSON.stringify({ alg: "HS256", typ: "JWT" });
44
+ const body = JSON.stringify(payload);
45
+
46
+ const encodedHeader = base64Url(header);
47
+ const encodedBody = base64Url(body);
48
+ const data = `${encodedHeader}.${encodedBody}`;
49
+
50
+ const key = await importKey(secret);
51
+ const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
52
+ const encodedSig = base64Url(new Uint8Array(signature));
53
+
54
+ return `${data}.${encodedSig}`;
55
+ };
56
+
57
+ /**
58
+ * 1. BARE TOKEN AUTH (Standard JWT Middleware)
59
+ * High-performance, constant-time JWT middleware for BareJS
60
+ */
61
+ export const bareAuth = (secret: string) => {
62
+ return (ctx: any, next: any) => {
63
+ const authHeader = ctx.req.headers.get('Authorization');
64
+
65
+ if (!authHeader?.startsWith('Bearer ')) {
66
+ return ctx.status(401).send("Bearer token required");
67
+ }
68
+
69
+ const token = authHeader.slice(7);
70
+ const firstDot = token.indexOf('.');
71
+ const secondDot = firstDot === -1 ? -1 : token.indexOf('.', firstDot + 1);
72
+ if (firstDot === -1 || secondDot === -1 || token.indexOf('.', secondDot + 1) !== -1) {
73
+ return ctx.status(401).send("Malformed JWT token");
74
+ }
75
+
76
+ const headerB64 = token.slice(0, firstDot);
77
+ const payloadB64 = token.slice(firstDot + 1, secondDot);
78
+ const sigB64 = token.slice(secondDot + 1);
79
+ const data = token.slice(0, secondDot);
80
+
81
+ try {
82
+ const expectedSig = createHmac('sha256', secret).update(data).digest();
83
+ const actualSig = Buffer.from(sigB64, 'base64url');
84
+
85
+ if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
86
+ return ctx.status(401).send("Invalid signature");
87
+ }
88
+
89
+ const headerObj = JSON.parse(fromBase64Url(headerB64));
90
+ if (!headerObj || headerObj.alg !== 'HS256') {
91
+ return ctx.status(401).send("Unsupported token algorithm");
92
+ }
93
+
94
+ const decoded = JSON.parse(fromBase64Url(payloadB64));
95
+ const nowSec = Date.now() * 0.001;
96
+ if (typeof decoded.exp === 'number' && nowSec >= decoded.exp) {
97
+ return ctx.status(401).send("Token expired");
98
+ }
99
+ if (typeof decoded.nbf === 'number' && nowSec < decoded.nbf) {
100
+ return ctx.status(401).send("Token not active");
101
+ }
102
+
103
+ ctx.set('user', decoded);
104
+
105
+ if (Array.isArray(next)) {
106
+ if (next.length === 0) return;
107
+ const [current, ...rest] = next;
108
+ return current(ctx, rest);
109
+ }
110
+
111
+ if (typeof next === 'function') {
112
+ return next();
113
+ }
114
+
115
+ return;
116
+ } catch {
117
+ return ctx.status(401).send("Token verification failed");
118
+ }
119
+ };
120
+ };
121
+
122
+ const sha256 = (value: string): Buffer => createHash('sha256').update(value).digest();
123
+
124
+ /**
125
+ * 2. BASIC AUTH
126
+ * Useful for internal tools and simple admin panels
127
+ */
128
+ export const basicAuth = (credentials: { user: string; pass: string }) => {
129
+ const expectedUserHash = sha256(credentials.user);
130
+ const expectedPassHash = sha256(credentials.pass);
131
+
132
+ return async (ctx: any, next: Next) => {
133
+ const authHeader = ctx.req.headers.get('Authorization');
134
+ if (!authHeader?.startsWith('Basic ')) {
135
+ return ctx.status(401).json({ status: 'error', message: 'Basic Auth required' });
136
+ }
137
+
138
+ const token = authHeader.slice(6).trim();
139
+ if (!token) return ctx.status(401).json({ status: 'error', message: 'Missing credentials' });
140
+
141
+ const decoded = Buffer.from(token, 'base64').toString('utf-8');
142
+ const colonIdx = decoded.indexOf(':');
143
+ if (colonIdx === -1) {
144
+ return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
145
+ }
146
+
147
+ const user = decoded.slice(0, colonIdx);
148
+ const pass = decoded.slice(colonIdx + 1);
149
+
150
+ const userMatch = timingSafeEqual(sha256(user), expectedUserHash);
151
+ const passMatch = timingSafeEqual(sha256(pass), expectedPassHash);
152
+
153
+ if (userMatch && passMatch) {
154
+ return next();
155
+ }
156
+
157
+ return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
158
+ };
159
+ };
160
+
161
+
162
+
163
+ /**
164
+ * 5. ROLE AUTHORIZATION (Bonus Max Function)
165
+ * Ensures user has specific permissions after bareAuth
166
+ */
167
+ export const hasRole = (role: string) => {
168
+ return async (ctx: any, next: Next) => {
169
+ const user = ctx.get('user');
170
+ if (!user || user.role !== role) {
171
+ return ctx.status(403).json({ status: 'error', message: `Required role: ${role}` });
172
+ }
173
+ return next();
174
+ };
158
175
  };
@@ -1,27 +1,46 @@
1
- import type { Middleware } from '../core/context';
2
-
3
- export const cors = (options: { origin?: string; methods?: string } = {}) => {
4
- const origin = options.origin || '*';
5
- const methods = options.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
6
-
7
- const mw: Middleware = async (ctx, next) => {
8
- if (ctx.req.method === 'OPTIONS') {
9
- return new Response(null, {
10
- status: 204,
11
- headers: {
12
- 'Access-Control-Allow-Origin': origin,
13
- 'Access-Control-Allow-Methods': methods,
14
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization'
15
- }
16
- });
17
- }
18
-
19
- const res = await next?.();
20
- if (res instanceof Response) {
21
- res.headers.set('Access-Control-Allow-Origin', origin);
22
- res.headers.set('Access-Control-Allow-Methods', methods);
23
- }
24
- return res;
25
- };
26
- return mw;
1
+ import type { Middleware } from '../core/context';
2
+
3
+ export const cors = (options: { origin?: string; methods?: string } = {}) => {
4
+ const origin = options.origin || '*';
5
+ const methods = options.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
6
+ const preflightHeaders: Record<string, string> = {
7
+ 'Access-Control-Allow-Origin': origin,
8
+ 'Access-Control-Allow-Methods': methods,
9
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization'
10
+ };
11
+ if (origin !== '*') {
12
+ preflightHeaders['Vary'] = 'Origin';
13
+ }
14
+ const preflightInit = { status: 204, headers: preflightHeaders };
15
+
16
+ const mw: Middleware = (ctx, next) => {
17
+ if (ctx.req.method === 'OPTIONS') {
18
+ return new Response(null, preflightInit);
19
+ }
20
+
21
+ ctx.setHeader('Access-Control-Allow-Origin', origin);
22
+ ctx.setHeader('Access-Control-Allow-Methods', methods);
23
+ if (origin !== '*') {
24
+ ctx.setHeader('Vary', 'Origin');
25
+ }
26
+
27
+ const res = next?.();
28
+ if (res && typeof (res as any).then === 'function') {
29
+ return (res as Promise<any>).then((r) => {
30
+ if (r instanceof Response) {
31
+ r.headers.set('Access-Control-Allow-Origin', origin);
32
+ r.headers.set('Access-Control-Allow-Methods', methods);
33
+ if (origin !== '*') r.headers.set('Vary', 'Origin');
34
+ }
35
+ return r;
36
+ });
37
+ }
38
+ if (res instanceof Response) {
39
+ res.headers.set('Access-Control-Allow-Origin', origin);
40
+ res.headers.set('Access-Control-Allow-Methods', methods);
41
+ if (origin !== '*') res.headers.set('Vary', 'Origin');
42
+ }
43
+ return res;
44
+ };
45
+ return mw;
27
46
  };