barejs 0.1.55 → 0.1.56

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.
@@ -23,10 +23,11 @@ export let BARE_CONFIG = DEFAULT_CONFIG;
23
23
 
24
24
 
25
25
  export const initConfig = (userConfig: Partial<BareConfig> = {}) => {
26
+ const cfg = userConfig && typeof userConfig === 'object' && !Array.isArray(userConfig) ? userConfig : {};
26
27
  BARE_CONFIG = {
27
28
  ...DEFAULT_CONFIG,
28
- ...userConfig,
29
- hash: { ...DEFAULT_CONFIG.hash, ...userConfig.hash }
29
+ ...cfg,
30
+ hash: { ...DEFAULT_CONFIG.hash, ...(cfg.hash && typeof cfg.hash === 'object' && !Array.isArray(cfg.hash) ? cfg.hash : {}) }
30
31
  };
31
32
  return BARE_CONFIG;
32
33
  };
@@ -1,5 +1,25 @@
1
1
  import { createHmac, timingSafeEqual } from 'node:crypto';
2
2
 
3
+ let _userStreamsCreated = 0;
4
+ const _userStreams = new WeakSet<ReadableStream>();
5
+ if (typeof globalThis.ReadableStream === 'function' && !(globalThis.ReadableStream as any).__bareTracked) {
6
+ const OrigRS = globalThis.ReadableStream;
7
+ const ProxiedRS = new Proxy(OrigRS, {
8
+ construct(target, args, newTarget) {
9
+ const inst = Reflect.construct(target, args, newTarget);
10
+ if (args[0] && typeof args[0].pull === 'function') {
11
+ _userStreamsCreated++;
12
+ _userStreams.add(inst);
13
+ }
14
+ return inst;
15
+ }
16
+ });
17
+ (ProxiedRS as any).__bareTracked = true;
18
+ globalThis.ReadableStream = ProxiedRS;
19
+ }
20
+ const _sharedTextDecoder = new TextDecoder();
21
+
22
+
3
23
  export type Params = Record<string, string>;
4
24
  export type Next = () => Promise<any> | any;
5
25
  export type Middleware = (ctx: Context, next: Next) => Promise<any> | any;
@@ -108,6 +128,17 @@ export class Context {
108
128
  return result;
109
129
  }
110
130
 
131
+ /** All values for a (possibly repeated) query key, in order. */
132
+ public queryAll(key: string): string[] {
133
+ const url = this.req?.url;
134
+ const qIdx = url ? url.indexOf('?') : -1;
135
+ if (qIdx === -1) return [];
136
+ const out: string[] = [];
137
+ const sp = new URLSearchParams(url!.slice(qIdx + 1));
138
+ for (const [k, v] of sp) if (k === key) out.push(v);
139
+ return out;
140
+ }
141
+
111
142
  public getQuery(key: string): string | undefined {
112
143
  const q = this.query;
113
144
  return Object.hasOwn(q, key) ? q[key] : undefined;
@@ -115,7 +146,7 @@ export class Context {
115
146
 
116
147
  public get cookies(): Record<string, string> {
117
148
  if (this._cookies !== undefined) return this._cookies;
118
- const result: Record<string, string> = {};
149
+ const result: Record<string, string> = Object.create(null);
119
150
  const header = this.req?.headers?.get('cookie');
120
151
  if (header) {
121
152
  let start = 0;
@@ -152,6 +183,10 @@ export class Context {
152
183
  if (options.domain && /[\r\n;]/.test(options.domain)) {
153
184
  throw new Error('Invalid cookie domain');
154
185
  }
186
+ const sameSite = options.sameSite ?? 'Lax';
187
+ if (sameSite !== 'Strict' && sameSite !== 'Lax' && sameSite !== 'None') {
188
+ throw new Error('Invalid cookie sameSite');
189
+ }
155
190
  let finalVal = value;
156
191
  if (options.secret) {
157
192
  const sig = createHmac('sha256', options.secret).update(value).digest('base64url');
@@ -160,11 +195,15 @@ export class Context {
160
195
  let cookieStr = `${name}=${encodeURIComponent(finalVal)}`;
161
196
  cookieStr += `; Path=${path}`;
162
197
  if (options.domain) cookieStr += `; Domain=${options.domain}`;
163
- if (options.maxAge !== undefined) cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
164
- if (options.expires) cookieStr += `; Expires=${options.expires.toUTCString()}`;
198
+ if (options.maxAge !== undefined && Number.isFinite(options.maxAge)) {
199
+ cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
200
+ }
201
+ if (options.expires && !Number.isNaN(options.expires.getTime())) {
202
+ cookieStr += `; Expires=${options.expires.toUTCString()}`;
203
+ }
165
204
  if (options.httpOnly !== false) cookieStr += '; HttpOnly';
166
205
  if (options.secure) cookieStr += '; Secure';
167
- cookieStr += `; SameSite=${options.sameSite ?? 'Lax'}`;
206
+ cookieStr += `; SameSite=${sameSite}`;
168
207
 
169
208
  if (!this._setCookies) this._setCookies = [];
170
209
  this._setCookies.push(cookieStr);
@@ -172,12 +211,15 @@ export class Context {
172
211
  }
173
212
 
174
213
  public getSignedCookie(name: string, secret: string): string | null {
175
- const raw = this.cookies[name];
176
- if (!raw) return null;
214
+ const cookies = this.cookies;
215
+ if (!Object.hasOwn(cookies, name)) return null;
216
+ const raw = cookies[name];
217
+ if (typeof raw !== 'string' || !raw) return null;
177
218
  const dotIdx = raw.lastIndexOf('.');
178
- if (dotIdx <= 0) return null;
219
+ if (dotIdx < 0) return null;
179
220
  const value = raw.slice(0, dotIdx);
180
221
  const sigB64 = raw.slice(dotIdx + 1);
222
+ if (!/^[A-Za-z0-9_-]{43}$/.test(sigB64)) return null;
181
223
  const expected = createHmac('sha256', secret).update(value).digest();
182
224
  const actual = Buffer.from(sigB64, 'base64url');
183
225
  if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
@@ -194,12 +236,74 @@ export class Context {
194
236
  });
195
237
  }
196
238
 
197
- public async jsonBody(maxBytes: number = 1048576): Promise<any> {
239
+ private async readBodyWithLimit(maxBytes: number): Promise<Uint8Array> {
240
+ const reader = this.req.body!.getReader();
241
+ const chunks: Uint8Array[] = [];
242
+ let received = 0;
243
+ while (true) {
244
+ const { done, value } = await reader.read();
245
+ if (done) break;
246
+ if (value) {
247
+ received += value.byteLength;
248
+ if (received > maxBytes) {
249
+ try { await reader.cancel(); } catch {}
250
+ throw Object.assign(new Error("Payload Too Large"), { status: 413 });
251
+ }
252
+ chunks.push(value);
253
+ }
254
+ }
255
+ const combined = new Uint8Array(received);
256
+ let offset = 0;
257
+ for (let i = 0; i < chunks.length; i++) {
258
+ combined.set(chunks[i]!, offset);
259
+ offset += chunks[i]!.byteLength;
260
+ }
261
+ return combined;
262
+ }
263
+
264
+ private _parseAndSanitizeJson(text: string, maxBytes: number): any {
265
+ if (text.length > maxBytes || (text.length * 3 > maxBytes && Buffer.byteLength(text, 'utf-8') > maxBytes)) {
266
+ const err: any = new Error("Payload Too Large");
267
+ err.status = 413;
268
+ throw err;
269
+ }
270
+ const parsed = JSON.parse(text);
271
+ if (
272
+ text.indexOf('__proto__') !== -1 ||
273
+ text.indexOf('constructor') !== -1 ||
274
+ text.indexOf('prototype') !== -1 ||
275
+ text.indexOf('\\u') !== -1
276
+ ) {
277
+ const stack: any[] = [parsed];
278
+ while (stack.length > 0) {
279
+ const cur = stack.pop();
280
+ if (!cur || typeof cur !== 'object') continue;
281
+ if (Array.isArray(cur)) {
282
+ for (let i = 0; i < cur.length; i++) stack.push(cur[i]);
283
+ } else {
284
+ if (Object.hasOwn(cur, '__proto__')) delete cur['__proto__'];
285
+ if (Object.hasOwn(cur, 'constructor')) delete cur['constructor'];
286
+ if (Object.hasOwn(cur, 'prototype')) delete cur['prototype'];
287
+ const keys = Object.keys(cur);
288
+ for (let i = 0; i < keys.length; i++) stack.push(cur[keys[i]!]);
289
+ }
290
+ }
291
+ }
292
+ return this.body = parsed;
293
+ }
294
+
295
+ public jsonBodySyncOrAsync(maxBytes: number = 1048576): any {
198
296
  if (this.body !== undefined) return this.body;
199
297
 
200
- const contentType = this.req.headers.get("content-type");
201
- if (contentType && contentType.toLowerCase().includes("application/json")) {
202
- const lenHeader = this.req.headers.get("content-length");
298
+ const headers = this.req.headers;
299
+ const contentType = headers.get("content-type");
300
+ if (
301
+ contentType &&
302
+ (contentType === "application/json" ||
303
+ contentType.startsWith("application/json;") ||
304
+ contentType.toLowerCase().includes("application/json"))
305
+ ) {
306
+ const lenHeader = headers.get("content-length");
203
307
  if (lenHeader !== null) {
204
308
  const trimmed = lenHeader.trim();
205
309
  const lenNum = trimmed.length > 0 ? Number(trimmed) : NaN;
@@ -209,20 +313,55 @@ export class Context {
209
313
  throw err;
210
314
  }
211
315
  }
212
- try {
213
- const text = await this.req.text();
214
- if (Buffer.byteLength(text, 'utf-8') > maxBytes) {
215
- const err: any = new Error("Payload Too Large");
216
- err.status = 413;
217
- throw err;
316
+ if (
317
+ (lenHeader === null && headers.get("transfer-encoding") !== null) ||
318
+ (_userStreamsCreated > 0 && this.req.body && _userStreams.has(this.req.body))
319
+ ) {
320
+ return this.readBodyWithLimit(maxBytes).then(
321
+ (bytes) => {
322
+ try {
323
+ return this._parseAndSanitizeJson(_sharedTextDecoder.decode(bytes), maxBytes);
324
+ } catch (e: any) {
325
+ if (e?.status === 413) throw e;
326
+ return (this.body = null);
327
+ }
328
+ },
329
+ (e: any) => {
330
+ if (e?.status === 413) throw e;
331
+ return (this.body = null);
332
+ }
333
+ );
334
+ }
335
+ const tp = this.req.text();
336
+ const peeked = Bun.peek(tp);
337
+ if (typeof peeked === "string") {
338
+ try {
339
+ return this._parseAndSanitizeJson(peeked, maxBytes);
340
+ } catch (e: any) {
341
+ if (e?.status === 413) throw e;
342
+ return (this.body = null);
218
343
  }
219
- return this.body = JSON.parse(text);
220
- } catch (e: any) {
221
- if (e?.status === 413) throw e;
222
- return this.body = null;
223
344
  }
345
+ return tp.then(
346
+ (text) => {
347
+ try {
348
+ return this._parseAndSanitizeJson(text, maxBytes);
349
+ } catch (e: any) {
350
+ if (e?.status === 413) throw e;
351
+ return (this.body = null);
352
+ }
353
+ },
354
+ (e: any) => {
355
+ if (e?.status === 413) throw e;
356
+ return (this.body = null);
357
+ }
358
+ );
224
359
  }
225
- return this.body = null;
360
+ return (this.body = null);
361
+ }
362
+
363
+ public async jsonBody(maxBytes: number = 1048576): Promise<any> {
364
+ return this.jsonBodySyncOrAsync(maxBytes);
226
365
  }
227
366
 
228
367
  public reset(req: Request): this {
@@ -235,7 +374,9 @@ export class Context {
235
374
  this._cookies = undefined;
236
375
  this._setCookies = undefined;
237
376
  this.body = undefined;
377
+ this._requestId = undefined;
238
378
  this._peerIp = undefined;
379
+ this._detached = false;
239
380
  return this;
240
381
  }
241
382
 
@@ -263,14 +404,9 @@ export class Context {
263
404
  ? Response.json(data)
264
405
  : Response.json(data, { status });
265
406
  } else {
266
- let headers = this._headers;
267
- if (headers["content-type"] === undefined) {
268
- if (Object.isFrozen(headers)) {
269
- headers = { ...headers };
270
- this._headers = headers;
271
- }
272
- headers["content-type"] = "application/json";
273
- }
407
+ const headers = this._headers["content-type"] === undefined
408
+ ? { ...this._headers, "content-type": "application/json" }
409
+ : this._headers;
274
410
  res = Response.json(data, {
275
411
  status,
276
412
  headers: headers as any
@@ -292,7 +428,15 @@ export class Context {
292
428
  public setHeader(name: string, value: string): this {
293
429
  if (!this._headers) this._headers = {};
294
430
  else if (Object.isFrozen(this._headers)) this._headers = { ...this._headers };
295
- this._headers[name.toLowerCase()] = value;
431
+ const lower = name.toLowerCase();
432
+ if (lower === 'vary' && this._headers['vary']) {
433
+ const existing = this._headers['vary'];
434
+ const parts = existing.toLowerCase().split(',').map((s) => s.trim());
435
+ const toAdd = value.split(',').map((s) => s.trim()).filter((s) => s && !parts.includes(s.toLowerCase()));
436
+ this._headers['vary'] = toAdd.length > 0 ? `${existing}, ${toAdd.join(', ')}` : existing;
437
+ } else {
438
+ this._headers[lower] = value;
439
+ }
296
440
  return this;
297
441
  }
298
442
 
@@ -313,24 +457,27 @@ export class Context {
313
457
 
314
458
  public html(content: string, status?: number): Response {
315
459
  const headers: Record<string, string> = {
316
- 'content-type': 'text/html; charset=utf-8',
317
- ...(this._headers || {})
460
+ ...(this._headers || {}),
461
+ 'content-type': 'text/html; charset=utf-8'
318
462
  };
319
463
  return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
320
464
  }
321
465
 
322
466
  public text(content: string, status?: number): Response {
323
467
  const headers: Record<string, string> = {
324
- 'content-type': 'text/plain; charset=utf-8',
325
- ...(this._headers || {})
468
+ ...(this._headers || {}),
469
+ 'content-type': 'text/plain; charset=utf-8'
326
470
  };
327
471
  return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
328
472
  }
329
473
 
330
474
  public redirect(url: string, status: number = 302): Response {
475
+ if (/[\r\n]/.test(url)) {
476
+ throw new Error('Invalid redirect URL');
477
+ }
331
478
  const headers: Record<string, string> = {
332
- 'location': url,
333
- ...(this._headers || {})
479
+ ...(this._headers || {}),
480
+ 'location': url
334
481
  };
335
482
  return this._applyCookies(new Response(null, { status, headers }));
336
483
  }
@@ -342,7 +489,7 @@ export class Context {
342
489
  ): Response {
343
490
  const encoder = new TextEncoder();
344
491
  const formatDataLines = (raw: string): string =>
345
- raw.split(/\r?\n/).map((line) => `data: ${line}`).join('\n') + '\n\n';
492
+ raw.split(/\r\n|\r|\n/).map((line) => `data: ${line}`).join('\n') + '\n\n';
346
493
  const formatChunk = (chunk: string | { event?: string; data: any; id?: string; retry?: number }): Uint8Array => {
347
494
  if (typeof chunk === 'string') {
348
495
  return encoder.encode(formatDataLines(chunk));
@@ -351,36 +498,50 @@ export class Context {
351
498
  if (chunk.id !== undefined) out += `id: ${String(chunk.id).replace(/[\r\n]/g, '')}\n`;
352
499
  if (chunk.event !== undefined) out += `event: ${String(chunk.event).replace(/[\r\n]/g, '')}\n`;
353
500
  if (chunk.retry !== undefined && Number.isFinite(chunk.retry)) out += `retry: ${Math.max(0, Math.floor(chunk.retry))}\n`;
354
- const payload = typeof chunk.data === 'string' ? chunk.data : JSON.stringify(chunk.data);
501
+ const payload = chunk.data === undefined
502
+ ? ''
503
+ : (typeof chunk.data === 'string' ? chunk.data : JSON.stringify(chunk.data));
355
504
  out += formatDataLines(payload);
356
505
  return encoder.encode(out);
357
506
  };
358
507
 
508
+ let closed = false;
359
509
  const stream = new ReadableStream<Uint8Array>({
360
510
  async start(controller) {
511
+ const safeClose = () => {
512
+ if (!closed) {
513
+ closed = true;
514
+ try { controller.close(); } catch { /* already closed */ }
515
+ }
516
+ };
361
517
  try {
362
518
  if (typeof source === 'function') {
363
- let closed = false;
364
519
  const send = (data: any, event?: string, id?: string) => {
365
- if (!closed) controller.enqueue(formatChunk({ data, event, id }));
366
- };
367
- const close = () => {
368
520
  if (!closed) {
369
- closed = true;
370
- controller.close();
521
+ try { controller.enqueue(formatChunk({ data, event, id })); } catch { closed = true; }
371
522
  }
372
523
  };
373
- await source(send, close);
374
- close();
524
+ const maybePromise = source(send, safeClose);
525
+ if (maybePromise && typeof (maybePromise as any).then === 'function') {
526
+ await maybePromise;
527
+ safeClose();
528
+ }
375
529
  } else {
376
530
  for await (const item of source) {
377
- controller.enqueue(formatChunk(item));
531
+ if (closed) break;
532
+ try { controller.enqueue(formatChunk(item)); } catch { closed = true; break; }
378
533
  }
379
- controller.close();
534
+ safeClose();
380
535
  }
381
536
  } catch (err) {
382
- controller.error(err);
537
+ if (!closed) {
538
+ closed = true;
539
+ try { controller.error(err); } catch { /* already closed */ }
540
+ }
383
541
  }
542
+ },
543
+ cancel() {
544
+ closed = true;
384
545
  }
385
546
  });
386
547
 
@@ -395,8 +556,9 @@ export class Context {
395
556
 
396
557
  public get requestId(): string {
397
558
  if (this._requestId !== undefined) return this._requestId;
398
- const hdr = this.req?.headers?.get('x-request-id');
399
- this._requestId = hdr && hdr.length > 0 && hdr.length <= 128 ? hdr : crypto.randomUUID();
559
+ const raw = this.req?.headers?.get('x-request-id');
560
+ const hdr = raw ? raw.replace(/[\x00-\x1f\x7f]/g, '') : '';
561
+ this._requestId = hdr.length > 0 && hdr.length <= 128 ? hdr : crypto.randomUUID();
400
562
  return this._requestId;
401
563
  }
402
564
 
@@ -428,18 +590,34 @@ export class Context {
428
590
  }
429
591
 
430
592
  const maxTotalBytes = maxFileSize * maxFiles;
593
+ const maxRawBytes = maxTotalBytes + 65536;
431
594
  const contentLen = Number(this.req?.headers?.get('content-length') || 0);
432
- if (Number.isFinite(contentLen) && contentLen > maxTotalBytes + 65536) {
595
+ if (Number.isFinite(contentLen) && contentLen > maxRawBytes) {
433
596
  throw Object.assign(new Error('Payload Too Large'), { status: 413 });
434
597
  }
435
598
 
436
- const form = await this.req.formData();
599
+ let form: Awaited<ReturnType<Request['formData']>>;
600
+ try {
601
+ if (this.req.body) {
602
+ const combined = await this.readBodyWithLimit(maxRawBytes);
603
+ form = await new Response(combined, { headers: this.req.headers }).formData();
604
+ } else {
605
+ form = await this.req.formData();
606
+ }
607
+ } catch (e: any) {
608
+ if (e?.status === 413) throw e;
609
+ throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
610
+ }
437
611
  const fields: Record<string, string> = {};
438
612
  const files: UploadedFile[] = [];
439
613
  let totalBytes = 0;
440
614
 
441
615
  for (const [fieldName, value] of form.entries()) {
442
616
  if (typeof value === 'string') {
617
+ totalBytes += Buffer.byteLength(value, 'utf-8');
618
+ if (totalBytes > maxTotalBytes) {
619
+ throw Object.assign(new Error(`Total upload size exceeds ${maxTotalBytes} bytes`), { status: 413 });
620
+ }
443
621
  if (fieldName !== '__proto__' && fieldName !== 'constructor' && fieldName !== 'prototype') {
444
622
  fields[fieldName] = value;
445
623
  }
@@ -1,13 +1,23 @@
1
1
  // src/core/loader.ts
2
+ import { existsSync } from "node:fs";
3
+ import { createRequire } from "node:module";
2
4
  import { join } from "node:path";
3
5
  import { initConfig } from "./config";
4
6
 
7
+ const req = createRequire(import.meta.url);
8
+
5
9
  export async function bootstrapConfig() {
6
10
  const configPath = join(process.cwd(), "bare.config.ts");
11
+ if (!existsSync(configPath)) {
12
+ return initConfig();
13
+ }
7
14
  try {
8
- const userModule = await import(configPath);
9
- return initConfig(userModule.default);
10
- } catch {
15
+ const resolved = req.resolve(configPath);
16
+ delete req.cache[resolved];
17
+ const userModule = req(resolved);
18
+ return initConfig(userModule?.default ?? userModule);
19
+ } catch (err: any) {
20
+ console.warn(`[BareJS] Failed to load bare.config.ts:`, err?.message || err);
11
21
  return initConfig();
12
22
  }
13
23
  }