barejs 0.1.60 → 0.1.62

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/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)**.
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 **Full Multi-Runtime Test Suite (425 tests / 6,255 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
4
4
 
5
5
  ## 1. Installation & Minimal App (Bun, Node.js, Deno)
6
6
  ```ts
@@ -121,7 +121,8 @@ app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://aut
121
121
  ```
122
122
 
123
123
  ## 6. Real-Time, RPC, OpenAPI & Client
124
- - **WebSocket**: `app.ws('/ws/chat', { open(ws){}, message(ws, msg){}, close(ws){}, drain(ws){} })`
124
+ - **WebSocket**: `app.ws('/ws/chat', { open(ws){}, message(ws, msg){}, close(ws){}, drain(ws){} })` (Native on Bun, built-in RFC 6455 or optional `ws` on Node.js, `Deno.upgradeWebSocket` on Deno)
125
+ - **SSE**: `ctx.sse(async (send, close) => { send(data, event?, id?); })` or `ctx.sse(asyncIterable)` (works across Bun, Node.js, Deno)
125
126
  - **JSON-RPC 2.0**: `app.rpc('/rpc', { add: ({ a, b }, ctx) => a + b })` (supports single, batch, notifications, and standard `-32700`/`-32600`/`-32601`/`-32603` error codes)
126
127
  - **OpenAPI 3.1 + Scalar UI**: `app.docs('/docs', { title: 'My API', version: '1.0.0' })` (serves `/docs` & `/docs/json` with full `params`, `query`, `headers`, `body`, `response`, and `detail`)
127
128
  - **Type-Safe Client (URL or Zero-Network In-Memory `app`)**:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.60",
3
+ "version": "0.1.62",
4
4
  "author": "xarhang",
5
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",
@@ -30,6 +30,8 @@
30
30
  },
31
31
  "scripts": {
32
32
  "test": "bun test",
33
+ "test:node": "NODE_OPTIONS=--expose-gc vitest run && node tests/node-smoke.mjs",
34
+ "test:deno": "deno test --allow-all --unstable-sloppy-imports --no-check --v8-flags=--expose-gc --config deno.test.json --ignore=tests/playwright.test.ts,tests/production-db.test.ts tests/ && deno run --allow-net --allow-read --allow-write --allow-env tests/deno-smoke.ts",
33
35
  "benchs": "bun run benchmarks/index.ts",
34
36
  "bench": "bun run benchmarks/head-to-head.ts",
35
37
  "dev": "bun --watch Example/index.ts",
@@ -67,7 +69,7 @@
67
69
  "zod": "^3.0.0",
68
70
  "ws": "^8.0.0",
69
71
  "@node-rs/argon2": "^2.0.0",
70
- "bcryptjs": "^2.4.3"
72
+ "bcryptjs": ""
71
73
  },
72
74
  "peerDependenciesMeta": {
73
75
  "@sinclair/typebox": {
@@ -89,11 +91,14 @@
89
91
  "devDependencies": {
90
92
  "@sinclair/typebox": "^0.34.47",
91
93
  "@types/bun": "^1.3.5",
94
+ "bcryptjs": "^2.4.3",
92
95
  "elysia": "latest",
93
96
  "hono": "latest",
94
97
  "mitata": "^1.0.34",
95
98
  "playwright-core": "^1.65.1",
96
99
  "typescript": "latest",
100
+ "vitest": "^3.2.4",
101
+ "ws": "^8.0.0",
97
102
  "zod": "^3.25.76"
98
103
  },
99
104
  "files": [
@@ -1,9 +1,9 @@
1
- import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
1
+ import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
2
2
  import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
3
3
  import { createReadStream } from 'node:fs';
4
4
  import { extname } from 'node:path';
5
5
  import { Readable } from 'node:stream';
6
- import { gzipSync } from 'node:zlib';
6
+ import * as zlib from 'node:zlib';
7
7
  import type { RuntimeDriver, RuntimeFileHandle, RuntimePasswordConfig, ServeOptions, ServerHandle } from './types';
8
8
  import { matchWsRoute } from '../core/ws-match';
9
9
 
@@ -228,16 +228,189 @@ export const nodeDriver: RuntimeDriver = {
228
228
  const wsPkg = 'ws';
229
229
  wssPromise = import(wsPkg).then(
230
230
  (m: any) => new m.WebSocketServer({ noServer: true }),
231
- () => {
232
- throw new Error(
233
- '[BareJS] WebSocket on Node.js requires the optional peer dependency "ws". Install it with: npm install ws'
234
- );
235
- }
231
+ () => null
236
232
  );
237
233
  }
238
234
  return wssPromise;
239
235
  };
240
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
+
241
414
  server.on('upgrade', async (req, socket, head) => {
242
415
  const matched = matchWsRoute(wsCfg.routes, req.url || '/');
243
416
  if (!matched) {
@@ -246,8 +419,12 @@ export const nodeDriver: RuntimeDriver = {
246
419
  }
247
420
  try {
248
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
+ }
249
427
  wss.handleUpgrade(req, socket, head, (rawWs: any) => {
250
- const data = matched.params ? { ...matched.handler, params: matched.params } : matched.handler;
251
428
  rawWs.data = data;
252
429
  wsCfg.adapter.open(rawWs);
253
430
  rawWs.on('message', (msg: any, isBinary: boolean) => {
@@ -275,27 +452,47 @@ export const nodeDriver: RuntimeDriver = {
275
452
  }
276
453
  server.listen(listenOpts);
277
454
 
278
- const addr = server.address();
279
- const boundPort = typeof addr === 'object' && addr ? addr.port : opts.port;
455
+ const ready = new Promise<void>((resolve) => {
456
+ if (server.listening) resolve();
457
+ else server.once('listening', () => resolve());
458
+ });
459
+
460
+ const stopFn = (closeActiveConnections = false) =>
461
+ new Promise<void>((resolve) => {
462
+ if (closeActiveConnections && typeof (server as any).closeAllConnections === 'function') {
463
+ (server as any).closeAllConnections();
464
+ }
465
+ server.close(() => resolve());
466
+ });
467
+
468
+ Object.defineProperty(server, 'port', {
469
+ get() {
470
+ const a = server.address();
471
+ return typeof a === 'object' && a ? a.port : opts.port;
472
+ },
473
+ configurable: true
474
+ });
475
+ (server as any).stop = stopFn;
476
+ (server as any).ready = ready;
280
477
 
281
478
  return {
282
- stop(closeActiveConnections = false) {
283
- return new Promise<void>((resolve) => {
284
- if (closeActiveConnections && typeof (server as any).closeAllConnections === 'function') {
285
- (server as any).closeAllConnections();
286
- }
287
- server.close(() => resolve());
288
- });
479
+ stop: stopFn,
480
+ get port() {
481
+ const a = server.address();
482
+ return typeof a === 'object' && a ? a.port : opts.port;
289
483
  },
290
- port: boundPort,
291
484
  raw: server
292
485
  };
293
486
  },
294
487
 
295
488
  gzip(data: Uint8Array, level: number): Uint8Array {
296
- return new Uint8Array(gzipSync(data, { level }));
489
+ return new Uint8Array(zlib.gzipSync(data, { level }));
297
490
  },
298
491
 
492
+ zstd: typeof (zlib as any).zstdCompressSync === 'function'
493
+ ? (data: Uint8Array): Uint8Array => new Uint8Array((zlib as any).zstdCompressSync(data))
494
+ : undefined,
495
+
299
496
  openFile(path: string): RuntimeFileHandle {
300
497
  const ext = extname(path).toLowerCase();
301
498
  const mime = MIME_MAP[ext] || 'application/octet-stream';
@@ -4,6 +4,7 @@ import { runtime } from '../runtime';
4
4
 
5
5
  export const Hash = {
6
6
  make: (data: string): Promise<string> => {
7
+ if (!data) return Promise.reject(new Error('Password cannot be empty'));
7
8
  return runtime.password.hash(data, BARE_CONFIG.hash);
8
9
  },
9
10
 
@@ -25,6 +26,9 @@ export const Hash = {
25
26
  const expectedCost = Math.max(4, Math.min(31, timeCost));
26
27
  return !costMatch || Number(costMatch[1]) !== expectedCost;
27
28
  }
29
+ if (hash.startsWith('$scrypt$')) {
30
+ return !hash.startsWith('$scrypt$N=16384,r=8,p=1$');
31
+ }
28
32
  if (!hash.startsWith(`$${algorithm}$`)) return true;
29
33
  const mMatch = hash.match(/(?:^|[,$])m=(\d+)(?:[,$]|$)/);
30
34
  const tMatch = hash.match(/(?:^|[,$])t=(\d+)(?:[,$]|$)/);