barejs 0.1.59 → 0.1.60

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.60",
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 { 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',
@@ -291,9 +331,7 @@ export const nodeDriver: RuntimeDriver = {
291
331
  const pkg = '@node-rs/argon2';
292
332
  argon2 = await import(pkg);
293
333
  } 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
- );
334
+ return hashScrypt(data);
297
335
  }
298
336
  const fn = argon2.hash ?? argon2.default?.hash;
299
337
  return fn(data, {
@@ -305,6 +343,9 @@ export const nodeDriver: RuntimeDriver = {
305
343
 
306
344
  async verify(data: string, hash: string): Promise<boolean> {
307
345
  if (!hash || typeof hash !== 'string') return false;
346
+ if (hash.startsWith('$scrypt$')) {
347
+ return verifyScrypt(data, hash);
348
+ }
308
349
  if (/^\$2[aby]\$/.test(hash)) {
309
350
  let bcrypt: any;
310
351
  try {