barejs 0.1.59 → 0.1.61

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/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # BareJS (`barejs`) — AI Quick Reference (`llms.txt`)
2
2
 
3
- > BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`), **Node.js** (`>= 20` via `barejs/node`), and **Deno** with built-in security (Argon2id, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits) and **100% Function & Line Test Coverage (423 tests / 6,249 assertions)**.
3
+ > BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`), **Node.js** (`>= 20` via `barejs/node`), and **Deno** with built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits) and **100% Function & Line Test Coverage (424 tests / 6,253 assertions)**.
4
4
 
5
5
  ## 1. Installation & Minimal App (Bun, Node.js, Deno)
6
6
  ```ts
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.59",
3
+ "version": "0.1.61",
4
4
  "author": "xarhang",
5
- "description": "Full-featured, batteries-included Bun web framework combining O(1) JIT routing and object pooling with built-in TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and zero-trust security.",
5
+ "description": "Batteries-included web framework for Bun, Node.js, and Deno with O(1) JIT routing, TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and built-in security.",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
8
8
  "types": "./dist/types/index.d.ts",
package/src/core/bare.ts CHANGED
@@ -10,7 +10,7 @@ import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../uti
10
10
  import type { RouteSchemas } from "../security/validators";
11
11
  import type { RouteSchema } from "../client/index";
12
12
  import { runtime, type ServerHandle } from "../runtime";
13
- import { type WebSocketRouteHandler } from "./ws-match";
13
+ import { matchWsRoute, type WebSocketRouteHandler } from "./ws-match";
14
14
 
15
15
  export type { WebSocketRouteHandler };
16
16
 
@@ -1119,7 +1119,36 @@ export class BareJS<
1119
1119
  };
1120
1120
  `;
1121
1121
 
1122
- this.hotFetch = new Function(...args, fnBody)(...values);
1122
+ const compiledFetch = new Function(...args, fnBody)(...values);
1123
+ const denoUpgrade = (globalThis as any).Deno?.upgradeWebSocket;
1124
+ if (this.wsRoutes.size > 0 && typeof denoUpgrade === 'function') {
1125
+ const wsRoutes = this.wsRoutes;
1126
+ this.hotFetch = (req: Request, peerIp?: string) => {
1127
+ if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
1128
+ const matched = matchWsRoute(wsRoutes, req.url);
1129
+ if (matched) {
1130
+ const { socket, response } = denoUpgrade(req);
1131
+ (socket as any).data = matched.params
1132
+ ? { ...matched.handler, params: matched.params }
1133
+ : matched.handler;
1134
+ if (matched.handler.open) socket.onopen = () => matched.handler.open!(socket);
1135
+ if (matched.handler.message) {
1136
+ socket.onmessage = (ev: MessageEvent) => {
1137
+ const payload = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : ev.data;
1138
+ matched.handler.message!(socket, payload as any);
1139
+ };
1140
+ }
1141
+ if (matched.handler.close) {
1142
+ socket.onclose = (ev: CloseEvent) => matched.handler.close!(socket, ev.code, ev.reason);
1143
+ }
1144
+ return response;
1145
+ }
1146
+ }
1147
+ return compiledFetch(req, peerIp);
1148
+ };
1149
+ } else {
1150
+ this.hotFetch = compiledFetch;
1151
+ }
1123
1152
  this.compiled = true;
1124
1153
  this.fetch = this.hotFetch!;
1125
1154
  }
@@ -1,3 +1,4 @@
1
+ import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
1
2
  import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
2
3
  import { createReadStream } from 'node:fs';
3
4
  import { extname } from 'node:path';
@@ -6,6 +7,45 @@ import { gzipSync } from 'node:zlib';
6
7
  import type { RuntimeDriver, RuntimeFileHandle, RuntimePasswordConfig, ServeOptions, ServerHandle } from './types';
7
8
  import { matchWsRoute } from '../core/ws-match';
8
9
 
10
+ const SCRYPT_N = 16384;
11
+ const SCRYPT_R = 8;
12
+ const SCRYPT_P = 1;
13
+ const SCRYPT_KEYLEN = 64;
14
+
15
+ function scryptAsync(password: string, salt: Buffer, keylen: number, opts: { N: number; r: number; p: number }): Promise<Buffer> {
16
+ return new Promise((resolve, reject) => {
17
+ scrypt(password, salt, keylen, opts, (err, derived) => {
18
+ if (err) reject(err);
19
+ else resolve(derived);
20
+ });
21
+ });
22
+ }
23
+
24
+ async function hashScrypt(data: string): Promise<string> {
25
+ const salt = randomBytes(16);
26
+ const derived = await scryptAsync(data, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
27
+ return `$scrypt$N=${SCRYPT_N},r=${SCRYPT_R},p=${SCRYPT_P}$${salt.toString('base64url')}$${derived.toString('base64url')}`;
28
+ }
29
+
30
+ async function verifyScrypt(data: string, hash: string): Promise<boolean> {
31
+ const parts = hash.split('$');
32
+ if (parts.length !== 5 || parts[1] !== 'scrypt') return false;
33
+ const params: Record<string, number> = {};
34
+ for (const kv of parts[2]!.split(',')) {
35
+ const [k, v] = kv.split('=');
36
+ if (k && v) params[k] = Number(v);
37
+ }
38
+ const N = params.N || SCRYPT_N;
39
+ const r = params.r || SCRYPT_R;
40
+ const p = params.p || SCRYPT_P;
41
+ if (!Number.isFinite(N) || !Number.isFinite(r) || !Number.isFinite(p)) return false;
42
+ const salt = Buffer.from(parts[3]!, 'base64url');
43
+ const expected = Buffer.from(parts[4]!, 'base64url');
44
+ if (salt.length === 0 || expected.length === 0) return false;
45
+ const derived = await scryptAsync(data, salt, expected.length, { N, r, p });
46
+ return derived.length === expected.length && timingSafeEqual(derived, expected);
47
+ }
48
+
9
49
  const MIME_MAP: Record<string, string> = {
10
50
  '.html': 'text/html; charset=utf-8',
11
51
  '.htm': 'text/html; charset=utf-8',
@@ -188,16 +228,189 @@ export const nodeDriver: RuntimeDriver = {
188
228
  const wsPkg = 'ws';
189
229
  wssPromise = import(wsPkg).then(
190
230
  (m: any) => new m.WebSocketServer({ noServer: true }),
191
- () => {
192
- throw new Error(
193
- '[BareJS] WebSocket on Node.js requires the optional peer dependency "ws". Install it with: npm install ws'
194
- );
195
- }
231
+ () => null
196
232
  );
197
233
  }
198
234
  return wssPromise;
199
235
  };
200
236
 
237
+ const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
238
+ const MAX_WS_FRAME = 16 * 1024 * 1024;
239
+
240
+ const buildWsFrame = (opcode: number, payload: Buffer): Buffer => {
241
+ const len = payload.length;
242
+ let header: Buffer;
243
+ if (len < 126) {
244
+ header = Buffer.allocUnsafe(2);
245
+ header[0] = 0x80 | opcode;
246
+ header[1] = len;
247
+ } else if (len < 65536) {
248
+ header = Buffer.allocUnsafe(4);
249
+ header[0] = 0x80 | opcode;
250
+ header[1] = 126;
251
+ header.writeUInt16BE(len, 2);
252
+ } else {
253
+ header = Buffer.allocUnsafe(10);
254
+ header[0] = 0x80 | opcode;
255
+ header[1] = 127;
256
+ header.writeBigUInt64BE(BigInt(len), 2);
257
+ }
258
+ return Buffer.concat([header, payload]);
259
+ };
260
+
261
+ const handleNativeWsUpgrade = (req: IncomingMessage, socket: any, head: Buffer, data: any) => {
262
+ const key = req.headers['sec-websocket-key'];
263
+ if (!key || Array.isArray(key)) {
264
+ socket.write('HTTP/1.1 400 Bad Request\r\n\r\n');
265
+ socket.destroy();
266
+ return;
267
+ }
268
+ const accept = createHash('sha1').update(key.trim() + WS_GUID).digest('base64');
269
+ socket.write(
270
+ 'HTTP/1.1 101 Switching Protocols\r\n' +
271
+ 'Upgrade: websocket\r\n' +
272
+ 'Connection: Upgrade\r\n' +
273
+ `Sec-WebSocket-Accept: ${accept}\r\n\r\n`
274
+ );
275
+
276
+ let closed = false;
277
+ const wsWrapper: any = {
278
+ data,
279
+ send(msg: string | Uint8Array | Buffer) {
280
+ if (closed || socket.destroyed) return;
281
+ if (typeof msg === 'string') {
282
+ socket.write(buildWsFrame(0x1, Buffer.from(msg, 'utf8')));
283
+ } else {
284
+ const buf = Buffer.isBuffer(msg) ? msg : Buffer.from(msg.buffer, msg.byteOffset, msg.byteLength);
285
+ socket.write(buildWsFrame(0x2, buf));
286
+ }
287
+ },
288
+ close(code = 1000, reason = '') {
289
+ if (closed || socket.destroyed) return;
290
+ closed = true;
291
+ const reasonBuf = Buffer.from(reason, 'utf8');
292
+ const payload = Buffer.allocUnsafe(2 + reasonBuf.length);
293
+ payload.writeUInt16BE(code, 0);
294
+ reasonBuf.copy(payload, 2);
295
+ socket.end(buildWsFrame(0x8, payload));
296
+ wsCfg.adapter.close(wsWrapper, code, reason);
297
+ }
298
+ };
299
+
300
+ wsCfg.adapter.open(wsWrapper);
301
+
302
+ let buf: Buffer = head && head.length > 0 ? Buffer.from(head) : Buffer.alloc(0);
303
+ let fragOpcode = 0;
304
+ let fragChunks: Buffer[] = [];
305
+ let fragTotal = 0;
306
+
307
+ const processFrames = () => {
308
+ while (buf.length >= 2) {
309
+ const b0 = buf[0]!;
310
+ const b1 = buf[1]!;
311
+ const fin = (b0 & 0x80) !== 0;
312
+ const opcode = b0 & 0x0f;
313
+ const masked = (b1 & 0x80) !== 0;
314
+ let payloadLen = b1 & 0x7f;
315
+ let offset = 2;
316
+
317
+ if (payloadLen === 126) {
318
+ if (buf.length < 4) return;
319
+ payloadLen = buf.readUInt16BE(2);
320
+ offset = 4;
321
+ } else if (payloadLen === 127) {
322
+ if (buf.length < 10) return;
323
+ const bigLen = buf.readBigUInt64BE(2);
324
+ if (bigLen > BigInt(MAX_WS_FRAME)) {
325
+ wsWrapper.close(1009, 'Message too big');
326
+ socket.destroy();
327
+ return;
328
+ }
329
+ payloadLen = Number(bigLen);
330
+ offset = 10;
331
+ }
332
+
333
+ if (payloadLen > MAX_WS_FRAME) {
334
+ wsWrapper.close(1009, 'Message too big');
335
+ socket.destroy();
336
+ return;
337
+ }
338
+
339
+ const maskLen = masked ? 4 : 0;
340
+ if (buf.length < offset + maskLen + payloadLen) return;
341
+
342
+ let payload = buf.subarray(offset + maskLen, offset + maskLen + payloadLen);
343
+ if (masked) {
344
+ const mask = buf.subarray(offset, offset + 4);
345
+ const unmasked = Buffer.allocUnsafe(payloadLen);
346
+ for (let i = 0; i < payloadLen; i++) {
347
+ unmasked[i] = payload[i]! ^ mask[i & 3]!;
348
+ }
349
+ payload = unmasked;
350
+ } else {
351
+ payload = Buffer.from(payload);
352
+ }
353
+
354
+ buf = buf.subarray(offset + maskLen + payloadLen);
355
+
356
+ if (opcode === 0x8) {
357
+ const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1000;
358
+ const reason = payload.length > 2 ? payload.subarray(2).toString('utf8') : '';
359
+ wsWrapper.close(code, reason);
360
+ return;
361
+ }
362
+ if (opcode === 0x9) {
363
+ if (!closed && !socket.destroyed) socket.write(buildWsFrame(0xA, payload));
364
+ continue;
365
+ }
366
+ if (opcode === 0xA) continue;
367
+
368
+ if (opcode !== 0x0) {
369
+ if (fin) {
370
+ wsCfg.adapter.message(wsWrapper, opcode === 0x1 ? payload.toString('utf8') : payload);
371
+ } else {
372
+ fragOpcode = opcode;
373
+ fragChunks = [payload];
374
+ fragTotal = payload.length;
375
+ }
376
+ } else {
377
+ fragTotal += payload.length;
378
+ if (fragTotal > MAX_WS_FRAME) {
379
+ wsWrapper.close(1009, 'Message too big');
380
+ socket.destroy();
381
+ return;
382
+ }
383
+ fragChunks.push(payload);
384
+ if (fin) {
385
+ const full = Buffer.concat(fragChunks);
386
+ fragChunks = [];
387
+ fragTotal = 0;
388
+ wsCfg.adapter.message(wsWrapper, fragOpcode === 0x1 ? full.toString('utf8') : full);
389
+ }
390
+ }
391
+ }
392
+ };
393
+
394
+ if (buf.length > 0) processFrames();
395
+
396
+ socket.on('data', (chunk: Buffer) => {
397
+ buf = buf.length === 0 ? chunk : Buffer.concat([buf, chunk]);
398
+ processFrames();
399
+ });
400
+ socket.on('close', () => {
401
+ if (!closed) {
402
+ closed = true;
403
+ wsCfg.adapter.close(wsWrapper, 1006, '');
404
+ }
405
+ });
406
+ socket.on('error', () => {
407
+ if (!closed) {
408
+ closed = true;
409
+ wsCfg.adapter.close(wsWrapper, 1006, '');
410
+ }
411
+ });
412
+ };
413
+
201
414
  server.on('upgrade', async (req, socket, head) => {
202
415
  const matched = matchWsRoute(wsCfg.routes, req.url || '/');
203
416
  if (!matched) {
@@ -206,8 +419,12 @@ export const nodeDriver: RuntimeDriver = {
206
419
  }
207
420
  try {
208
421
  const wss = await getWss();
422
+ const data = matched.params ? { ...matched.handler, params: matched.params } : matched.handler;
423
+ if (!wss) {
424
+ handleNativeWsUpgrade(req, socket, head, data);
425
+ return;
426
+ }
209
427
  wss.handleUpgrade(req, socket, head, (rawWs: any) => {
210
- const data = matched.params ? { ...matched.handler, params: matched.params } : matched.handler;
211
428
  rawWs.data = data;
212
429
  wsCfg.adapter.open(rawWs);
213
430
  rawWs.on('message', (msg: any, isBinary: boolean) => {
@@ -291,9 +508,7 @@ export const nodeDriver: RuntimeDriver = {
291
508
  const pkg = '@node-rs/argon2';
292
509
  argon2 = await import(pkg);
293
510
  } catch {
294
- throw new Error(
295
- '[BareJS] Argon2id hashing on Node.js requires optional peer dependency "@node-rs/argon2". Install it with: npm install @node-rs/argon2'
296
- );
511
+ return hashScrypt(data);
297
512
  }
298
513
  const fn = argon2.hash ?? argon2.default?.hash;
299
514
  return fn(data, {
@@ -305,6 +520,9 @@ export const nodeDriver: RuntimeDriver = {
305
520
 
306
521
  async verify(data: string, hash: string): Promise<boolean> {
307
522
  if (!hash || typeof hash !== 'string') return false;
523
+ if (hash.startsWith('$scrypt$')) {
524
+ return verifyScrypt(data, hash);
525
+ }
308
526
  if (/^\$2[aby]\$/.test(hash)) {
309
527
  let bcrypt: any;
310
528
  try {