barejs 0.1.63 → 0.2.3
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/README.md +8 -8
- package/dist/index.js +145 -143
- package/dist/node.js +145 -143
- package/dist/types/core/bare.d.ts +34 -4
- package/dist/types/core/context.d.ts +3 -2
- package/dist/types/runtime/types.d.ts +2 -0
- package/dist/types/runtime/uws.d.ts +13 -0
- package/dist/types/utils/openapi.d.ts +3 -1
- package/dist/types/utils/static.d.ts +4 -0
- package/llms.txt +1 -1
- package/package.json +1 -1
- package/src/core/bare.ts +232 -13
- package/src/core/context.ts +36 -3
- package/src/runtime/bun.ts +39 -31
- package/src/runtime/node.ts +27 -3
- package/src/runtime/types.ts +2 -0
- package/src/runtime/uws.ts +655 -0
- package/src/security/auth.ts +11 -6
- package/src/utils/openapi.ts +19 -2
- package/src/utils/static.ts +37 -3
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import type { ServeOptions, ServerHandle } from './types';
|
|
4
|
+
import { matchWsRoute, type WebSocketRouteHandler } from '../core/ws-match';
|
|
5
|
+
|
|
6
|
+
export interface UwsRouteEntry {
|
|
7
|
+
method: string;
|
|
8
|
+
path: string;
|
|
9
|
+
paramNames: string[];
|
|
10
|
+
rawHandler: Function;
|
|
11
|
+
isPureStaticString: boolean;
|
|
12
|
+
isTrulyZeroArg: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const HTTP_STATUS_TEXT: Record<number, string> = {
|
|
16
|
+
200: '200 OK',
|
|
17
|
+
201: '201 Created',
|
|
18
|
+
202: '202 Accepted',
|
|
19
|
+
204: '204 No Content',
|
|
20
|
+
206: '206 Partial Content',
|
|
21
|
+
301: '301 Moved Permanently',
|
|
22
|
+
302: '302 Found',
|
|
23
|
+
304: '304 Not Modified',
|
|
24
|
+
400: '400 Bad Request',
|
|
25
|
+
401: '401 Unauthorized',
|
|
26
|
+
403: '403 Forbidden',
|
|
27
|
+
404: '404 Not Found',
|
|
28
|
+
405: '405 Method Not Allowed',
|
|
29
|
+
409: '409 Conflict',
|
|
30
|
+
413: '413 Payload Too Large',
|
|
31
|
+
415: '415 Unsupported Media Type',
|
|
32
|
+
422: '422 Unprocessable Entity',
|
|
33
|
+
429: '429 Too Many Requests',
|
|
34
|
+
500: '500 Internal Server Error',
|
|
35
|
+
502: '502 Bad Gateway',
|
|
36
|
+
503: '503 Service Unavailable'
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function statusLine(code: number): string {
|
|
40
|
+
return HTTP_STATUS_TEXT[code] || `${code}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function tryLoadUws(): any | null {
|
|
44
|
+
if (typeof (globalThis as any).Bun !== 'undefined' || typeof (globalThis as any).Deno !== 'undefined') {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
return createRequire(join(process.cwd(), 'package.json'))('uWebSockets.js');
|
|
49
|
+
} catch {
|
|
50
|
+
try {
|
|
51
|
+
return createRequire(import.meta.url)('uWebSockets.js');
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
class UwsContext {
|
|
59
|
+
public res: any = null;
|
|
60
|
+
public params: Record<string, string> = {};
|
|
61
|
+
public store: Map<string, any> = new Map();
|
|
62
|
+
public _status: number = 200;
|
|
63
|
+
public _headers: Record<string, string> | undefined = undefined;
|
|
64
|
+
public _setCookies: string[] | undefined = undefined;
|
|
65
|
+
public _queryStr: string = '';
|
|
66
|
+
public _query: Record<string, any> | undefined = undefined;
|
|
67
|
+
public _url: string = '/';
|
|
68
|
+
public _method: string = 'GET';
|
|
69
|
+
public _reqHeaders: Record<string, string> | undefined = undefined;
|
|
70
|
+
public _req: Request | undefined = undefined;
|
|
71
|
+
public _peerIp: string | undefined = undefined;
|
|
72
|
+
public _responded: boolean = false;
|
|
73
|
+
public _inSync: boolean = false;
|
|
74
|
+
public _aborted: boolean = false;
|
|
75
|
+
|
|
76
|
+
public reset(): void {
|
|
77
|
+
this.res = null;
|
|
78
|
+
this.params = {};
|
|
79
|
+
if (this.store.size > 0) this.store.clear();
|
|
80
|
+
this._status = 200;
|
|
81
|
+
this._headers = undefined;
|
|
82
|
+
this._setCookies = undefined;
|
|
83
|
+
this._queryStr = '';
|
|
84
|
+
this._query = undefined;
|
|
85
|
+
this._url = '/';
|
|
86
|
+
this._method = 'GET';
|
|
87
|
+
this._reqHeaders = undefined;
|
|
88
|
+
this._req = undefined;
|
|
89
|
+
this._peerIp = undefined;
|
|
90
|
+
this._responded = false;
|
|
91
|
+
this._inSync = false;
|
|
92
|
+
this._aborted = false;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
get req(): Request {
|
|
96
|
+
if (!this._req) {
|
|
97
|
+
const qs = this._queryStr ? `?${this._queryStr}` : '';
|
|
98
|
+
const host = this._reqHeaders?.host || 'localhost';
|
|
99
|
+
this._req = new Request(`http://${host}${this._url}${qs}`, {
|
|
100
|
+
method: this._method,
|
|
101
|
+
headers: this._reqHeaders
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return this._req;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
get query(): Record<string, any> {
|
|
108
|
+
if (!this._query) {
|
|
109
|
+
const q: Record<string, any> = {};
|
|
110
|
+
if (this._queryStr) {
|
|
111
|
+
const sp = new URLSearchParams(this._queryStr);
|
|
112
|
+
for (const [k, v] of sp) {
|
|
113
|
+
if (k in q) {
|
|
114
|
+
if (Array.isArray(q[k])) q[k].push(v);
|
|
115
|
+
else q[k] = [q[k], v];
|
|
116
|
+
} else {
|
|
117
|
+
q[k] = v;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
this._query = q;
|
|
122
|
+
}
|
|
123
|
+
return this._query;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
get ip(): string {
|
|
127
|
+
const xff = this._reqHeaders?.['x-forwarded-for'];
|
|
128
|
+
if (xff) {
|
|
129
|
+
const comma = xff.indexOf(',');
|
|
130
|
+
return (comma === -1 ? xff : xff.slice(0, comma)).trim();
|
|
131
|
+
}
|
|
132
|
+
return this._reqHeaders?.['x-real-ip'] || this._reqHeaders?.['cf-connecting-ip'] || this._peerIp || '127.0.0.1';
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
public status(code: number): this {
|
|
136
|
+
this._status = code;
|
|
137
|
+
return this;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
public setHeader(key: string, val: string): this {
|
|
141
|
+
if (!this._headers) this._headers = {};
|
|
142
|
+
this._headers[key.toLowerCase()] = val;
|
|
143
|
+
return this;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
public getHeader(key: string): string | undefined {
|
|
147
|
+
return this._reqHeaders?.[key.toLowerCase()];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
public header(key: string): string | undefined {
|
|
151
|
+
return this.getHeader(key);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
public set(key: string, val: any): this {
|
|
155
|
+
this.store.set(key, val);
|
|
156
|
+
return this;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
public get<T = any>(key: string): T | undefined {
|
|
160
|
+
return this.store.get(key);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private _flushJson(res: any, payload: string): void {
|
|
164
|
+
if (this._status !== 200) res.writeStatus(statusLine(this._status));
|
|
165
|
+
res.writeHeader('content-type', 'application/json');
|
|
166
|
+
if (this._headers) {
|
|
167
|
+
for (const k in this._headers) {
|
|
168
|
+
if (k !== 'content-type') res.writeHeader(k, this._headers[k]);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (this._setCookies) {
|
|
172
|
+
for (let i = 0; i < this._setCookies.length; i++) {
|
|
173
|
+
res.writeHeader('set-cookie', this._setCookies[i]);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
res.end(payload);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
public json(data: any): undefined {
|
|
180
|
+
const res = this.res;
|
|
181
|
+
if (!res || this._responded || this._aborted) return undefined;
|
|
182
|
+
this._responded = true;
|
|
183
|
+
const payload = JSON.stringify(data);
|
|
184
|
+
if (this._inSync) {
|
|
185
|
+
this._flushJson(res, payload);
|
|
186
|
+
} else {
|
|
187
|
+
res.cork(() => this._flushJson(res, payload));
|
|
188
|
+
}
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
private _flushText(res: any, data: string, code: number): void {
|
|
193
|
+
if (code !== 200) res.writeStatus(statusLine(code));
|
|
194
|
+
if (this._headers) {
|
|
195
|
+
for (const k in this._headers) res.writeHeader(k, this._headers[k]);
|
|
196
|
+
}
|
|
197
|
+
if (this._setCookies) {
|
|
198
|
+
for (let i = 0; i < this._setCookies.length; i++) {
|
|
199
|
+
res.writeHeader('set-cookie', this._setCookies[i]);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
res.end(data);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
public text(data: string, status?: number): undefined {
|
|
206
|
+
const res = this.res;
|
|
207
|
+
if (!res || this._responded || this._aborted) return undefined;
|
|
208
|
+
this._responded = true;
|
|
209
|
+
const code = status ?? this._status;
|
|
210
|
+
if (this._inSync) {
|
|
211
|
+
this._flushText(res, data, code);
|
|
212
|
+
} else {
|
|
213
|
+
res.cork(() => this._flushText(res, data, code));
|
|
214
|
+
}
|
|
215
|
+
return undefined;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
public html(data: string, status?: number): undefined {
|
|
219
|
+
this.setHeader('content-type', 'text/html; charset=utf-8');
|
|
220
|
+
return this.text(data, status);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
public redirect(url: string, status: number = 302): undefined {
|
|
224
|
+
this.setHeader('location', url);
|
|
225
|
+
return this.text('', status);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function writeUwsHeaders(res: any, webRes: Response): void {
|
|
230
|
+
const status = webRes.status;
|
|
231
|
+
if (status !== 200) res.writeStatus(statusLine(status));
|
|
232
|
+
webRes.headers.forEach((value, key) => {
|
|
233
|
+
res.writeHeader(key, value);
|
|
234
|
+
});
|
|
235
|
+
const anyHeaders = webRes.headers as any;
|
|
236
|
+
if (typeof anyHeaders.getSetCookie === 'function') {
|
|
237
|
+
const cookies: string[] = anyHeaders.getSetCookie();
|
|
238
|
+
for (let i = 0; i < cookies.length; i++) {
|
|
239
|
+
res.writeHeader('set-cookie', cookies[i]!);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function writeWebResponseToUws(res: any, webRes: Response, isAborted?: () => boolean): void {
|
|
245
|
+
if (!webRes.body) {
|
|
246
|
+
if (isAborted?.()) return;
|
|
247
|
+
res.cork(() => {
|
|
248
|
+
writeUwsHeaders(res, webRes);
|
|
249
|
+
res.end();
|
|
250
|
+
});
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const reader = webRes.body.getReader();
|
|
255
|
+
let headersSent = false;
|
|
256
|
+
|
|
257
|
+
const pump = (): void => {
|
|
258
|
+
reader.read().then(
|
|
259
|
+
({ value, done }) => {
|
|
260
|
+
if (isAborted?.()) {
|
|
261
|
+
try { reader.cancel(); } catch {}
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (done) {
|
|
265
|
+
res.cork(() => {
|
|
266
|
+
if (!headersSent) {
|
|
267
|
+
writeUwsHeaders(res, webRes);
|
|
268
|
+
headersSent = true;
|
|
269
|
+
}
|
|
270
|
+
res.end();
|
|
271
|
+
});
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (value && value.byteLength > 0) {
|
|
275
|
+
const chunk = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
276
|
+
let ok = true;
|
|
277
|
+
res.cork(() => {
|
|
278
|
+
if (!headersSent) {
|
|
279
|
+
writeUwsHeaders(res, webRes);
|
|
280
|
+
headersSent = true;
|
|
281
|
+
}
|
|
282
|
+
ok = res.write(chunk);
|
|
283
|
+
});
|
|
284
|
+
if (!ok && typeof res.onWritable === 'function') {
|
|
285
|
+
res.onWritable(() => {
|
|
286
|
+
pump();
|
|
287
|
+
return true;
|
|
288
|
+
});
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
pump();
|
|
293
|
+
},
|
|
294
|
+
() => {
|
|
295
|
+
if (!isAborted?.()) {
|
|
296
|
+
try { res.close(); } catch {}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
);
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
pump();
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function writeOutToUws(res: any, ctx: UwsContext | null, out: any): void {
|
|
306
|
+
if (ctx?._responded) return;
|
|
307
|
+
if (out instanceof Response) {
|
|
308
|
+
writeWebResponseToUws(res, out);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (typeof out === 'string') {
|
|
312
|
+
if (ctx) {
|
|
313
|
+
ctx.text(out);
|
|
314
|
+
} else {
|
|
315
|
+
res.end(out);
|
|
316
|
+
}
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
if (ctx) {
|
|
320
|
+
ctx.json(out ?? null);
|
|
321
|
+
} else {
|
|
322
|
+
res.writeHeader('content-type', 'application/json');
|
|
323
|
+
res.end(JSON.stringify(out ?? null));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function writeUwsError(res: any, err: any): void {
|
|
328
|
+
const code = err?.status >= 400 && err?.status < 500 ? err.status : 500;
|
|
329
|
+
res.writeStatus(statusLine(code));
|
|
330
|
+
res.writeHeader('content-type', 'application/json');
|
|
331
|
+
const msg =
|
|
332
|
+
code === 500
|
|
333
|
+
? (process.env.NODE_ENV === 'development' ? (err?.message || 'Internal Server Error') : 'Internal Server Error')
|
|
334
|
+
: (err?.message || 'Bad Request');
|
|
335
|
+
res.end(JSON.stringify({ status: code, message: msg }));
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const UWS_METHOD_MAP: Record<string, string> = {
|
|
339
|
+
GET: 'get',
|
|
340
|
+
HEAD: 'head',
|
|
341
|
+
DELETE: 'del',
|
|
342
|
+
OPTIONS: 'options'
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
export function serveUws(
|
|
346
|
+
opts: ServeOptions & { uwsRoutes?: UwsRouteEntry[] },
|
|
347
|
+
uwsMod: any
|
|
348
|
+
): ServerHandle {
|
|
349
|
+
const app = uwsMod.App();
|
|
350
|
+
const isProd = process.env.NODE_ENV === 'production';
|
|
351
|
+
const pool: UwsContext[] = [];
|
|
352
|
+
const maxPool = 4096;
|
|
353
|
+
let inFlight = 0;
|
|
354
|
+
|
|
355
|
+
// Tier 1: Direct uWS fast-path for bodyless methods (GET, HEAD, DELETE, OPTIONS)
|
|
356
|
+
if (opts.uwsRoutes) {
|
|
357
|
+
for (const r of opts.uwsRoutes) {
|
|
358
|
+
const uwsMethod = UWS_METHOD_MAP[r.method];
|
|
359
|
+
if (!uwsMethod) continue;
|
|
360
|
+
|
|
361
|
+
if (isProd && r.isPureStaticString) {
|
|
362
|
+
const buf = Buffer.from(r.rawHandler());
|
|
363
|
+
app[uwsMethod](r.path, (res: any) => {
|
|
364
|
+
res.end(buf);
|
|
365
|
+
});
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (isProd && r.isTrulyZeroArg) {
|
|
370
|
+
const fn = r.rawHandler;
|
|
371
|
+
app[uwsMethod](r.path, (res: any) => {
|
|
372
|
+
try {
|
|
373
|
+
const out = fn();
|
|
374
|
+
if (out && typeof out.then === 'function') {
|
|
375
|
+
let aborted = false;
|
|
376
|
+
res.onAborted(() => { aborted = true; });
|
|
377
|
+
out.then(
|
|
378
|
+
(v: any) => {
|
|
379
|
+
if (!aborted) res.cork(() => writeOutToUws(res, null, v));
|
|
380
|
+
},
|
|
381
|
+
(e: any) => {
|
|
382
|
+
if (!aborted) res.cork(() => writeUwsError(res, e));
|
|
383
|
+
}
|
|
384
|
+
);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
writeOutToUws(res, null, out);
|
|
388
|
+
} catch (e) {
|
|
389
|
+
writeUwsError(res, e);
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const fn = r.rawHandler;
|
|
396
|
+
const paramNames = r.paramNames;
|
|
397
|
+
const pLen = paramNames.length;
|
|
398
|
+
const fnSrc = fn.toString();
|
|
399
|
+
const needsHeaders = /\b(?:getHeader|header|ip|req)\b/.test(fnSrc);
|
|
400
|
+
const needsQuery = /\b(?:query|req)\b/.test(fnSrc);
|
|
401
|
+
|
|
402
|
+
app[uwsMethod](r.path, (res: any, req: any) => {
|
|
403
|
+
const ctx = pool.length > 0 ? pool.pop()! : new UwsContext();
|
|
404
|
+
ctx.res = res;
|
|
405
|
+
if (pLen > 0) {
|
|
406
|
+
const p: Record<string, string> = {};
|
|
407
|
+
for (let i = 0; i < pLen; i++) {
|
|
408
|
+
p[paramNames[i]] = req.getParameter(i);
|
|
409
|
+
}
|
|
410
|
+
ctx.params = p;
|
|
411
|
+
}
|
|
412
|
+
if (needsQuery) {
|
|
413
|
+
ctx._queryStr = req.getQuery();
|
|
414
|
+
ctx._url = req.getUrl();
|
|
415
|
+
ctx._method = r.method;
|
|
416
|
+
}
|
|
417
|
+
if (needsHeaders) {
|
|
418
|
+
const h: Record<string, string> = {};
|
|
419
|
+
req.forEach((k: string, v: string) => {
|
|
420
|
+
h[k] = v;
|
|
421
|
+
});
|
|
422
|
+
ctx._reqHeaders = h;
|
|
423
|
+
ctx._url = req.getUrl();
|
|
424
|
+
ctx._method = r.method;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
ctx._inSync = true;
|
|
428
|
+
try {
|
|
429
|
+
const out = fn(ctx);
|
|
430
|
+
ctx._inSync = false;
|
|
431
|
+
if (out && typeof out.then === 'function') {
|
|
432
|
+
res.onAborted(() => { ctx._aborted = true; });
|
|
433
|
+
out.then(
|
|
434
|
+
(v: any) => {
|
|
435
|
+
if (!ctx._aborted && !ctx._responded) {
|
|
436
|
+
res.cork(() => writeOutToUws(res, ctx, v));
|
|
437
|
+
}
|
|
438
|
+
ctx.reset();
|
|
439
|
+
if (pool.length < maxPool) pool.push(ctx);
|
|
440
|
+
},
|
|
441
|
+
(e: any) => {
|
|
442
|
+
if (!ctx._aborted && !ctx._responded) {
|
|
443
|
+
res.cork(() => writeUwsError(res, e));
|
|
444
|
+
}
|
|
445
|
+
ctx.reset();
|
|
446
|
+
if (pool.length < maxPool) pool.push(ctx);
|
|
447
|
+
}
|
|
448
|
+
);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
if (!ctx._responded) writeOutToUws(res, ctx, out);
|
|
452
|
+
ctx.reset();
|
|
453
|
+
if (pool.length < maxPool) pool.push(ctx);
|
|
454
|
+
} catch (e) {
|
|
455
|
+
ctx._inSync = false;
|
|
456
|
+
if (!ctx._responded) writeUwsError(res, e);
|
|
457
|
+
ctx.reset();
|
|
458
|
+
if (pool.length < maxPool) pool.push(ctx);
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// Tier 2: Full Web-Standard Request/Response fallback for POST/PUT/PATCH, middlewares, 404, etc.
|
|
465
|
+
app.any('/*', (res: any, req: any) => {
|
|
466
|
+
let aborted = false;
|
|
467
|
+
res.onAborted(() => { aborted = true; });
|
|
468
|
+
|
|
469
|
+
const method = req.getMethod().toUpperCase();
|
|
470
|
+
const urlPath = req.getUrl();
|
|
471
|
+
const queryStr = req.getQuery();
|
|
472
|
+
const headers = new Headers();
|
|
473
|
+
let host = 'localhost';
|
|
474
|
+
req.forEach((k: string, v: string) => {
|
|
475
|
+
if (k === 'host') host = v;
|
|
476
|
+
headers.append(k, v);
|
|
477
|
+
});
|
|
478
|
+
const fullUrl = `http://${host}${urlPath}${queryStr ? `?${queryStr}` : ''}`;
|
|
479
|
+
let peerIp = '127.0.0.1';
|
|
480
|
+
try {
|
|
481
|
+
peerIp = Buffer.from(res.getRemoteAddressAsText()).toString() || '127.0.0.1';
|
|
482
|
+
} catch {}
|
|
483
|
+
|
|
484
|
+
const dispatchFetch = (bodyBuf?: Buffer) => {
|
|
485
|
+
if (aborted) return;
|
|
486
|
+
inFlight++;
|
|
487
|
+
const webReq = new Request(fullUrl, {
|
|
488
|
+
method,
|
|
489
|
+
headers,
|
|
490
|
+
body: bodyBuf && bodyBuf.length > 0 ? (bodyBuf as any) : undefined
|
|
491
|
+
});
|
|
492
|
+
Promise.resolve(opts.fetch(webReq, peerIp)).then(
|
|
493
|
+
(webRes) => {
|
|
494
|
+
inFlight = Math.max(0, inFlight - 1);
|
|
495
|
+
if (aborted) return;
|
|
496
|
+
writeWebResponseToUws(res, webRes, () => aborted);
|
|
497
|
+
},
|
|
498
|
+
(e) => {
|
|
499
|
+
inFlight = Math.max(0, inFlight - 1);
|
|
500
|
+
if (!aborted) res.cork(() => writeUwsError(res, e));
|
|
501
|
+
}
|
|
502
|
+
);
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
506
|
+
dispatchFetch();
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const chunks: Buffer[] = [];
|
|
511
|
+
let totalLen = 0;
|
|
512
|
+
const maxBody = opts.maxRequestBodySize || 10 * 1024 * 1024;
|
|
513
|
+
let rejected = false;
|
|
514
|
+
|
|
515
|
+
res.onData((ab: ArrayBuffer, isLast: boolean) => {
|
|
516
|
+
if (aborted || rejected) return;
|
|
517
|
+
const chunk = Buffer.from(ab);
|
|
518
|
+
totalLen += chunk.length;
|
|
519
|
+
if (totalLen > maxBody) {
|
|
520
|
+
rejected = true;
|
|
521
|
+
res.cork(() => {
|
|
522
|
+
res.writeStatus('413 Payload Too Large');
|
|
523
|
+
res.writeHeader('content-type', 'application/json');
|
|
524
|
+
res.end(JSON.stringify({ status: 413, message: 'Payload Too Large' }));
|
|
525
|
+
});
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
if (chunk.length > 0) chunks.push(chunk);
|
|
529
|
+
if (isLast) {
|
|
530
|
+
dispatchFetch(chunks.length === 0 ? undefined : chunks.length === 1 ? chunks[0] : Buffer.concat(chunks));
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
if (opts.ws) {
|
|
536
|
+
const wsCfg = opts.ws;
|
|
537
|
+
const getWrapped = (ws: any) => {
|
|
538
|
+
const ud = ws.getUserData();
|
|
539
|
+
if (!ud.wrapped) {
|
|
540
|
+
ud.wrapped = {
|
|
541
|
+
data: ud.handler,
|
|
542
|
+
send(data: any, isBinary?: boolean) {
|
|
543
|
+
return ws.send(data, isBinary ?? (typeof data !== 'string'));
|
|
544
|
+
},
|
|
545
|
+
subscribe(topic: string) {
|
|
546
|
+
return typeof ws.subscribe === 'function' ? ws.subscribe(topic) : false;
|
|
547
|
+
},
|
|
548
|
+
unsubscribe(topic: string) {
|
|
549
|
+
return typeof ws.unsubscribe === 'function' ? ws.unsubscribe(topic) : false;
|
|
550
|
+
},
|
|
551
|
+
publish(topic: string, data: any, isBinary?: boolean) {
|
|
552
|
+
return typeof ws.publish === 'function' ? ws.publish(topic, data, isBinary ?? (typeof data !== 'string')) : false;
|
|
553
|
+
},
|
|
554
|
+
close(code?: number, reason?: string) {
|
|
555
|
+
if (typeof ws.end === 'function') ws.end(code, reason);
|
|
556
|
+
else if (typeof ws.close === 'function') ws.close();
|
|
557
|
+
},
|
|
558
|
+
raw: ws
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
return ud.wrapped;
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
app.ws('/*', {
|
|
565
|
+
upgrade(res: any, req: any, context: any) {
|
|
566
|
+
const urlPath = req.getUrl();
|
|
567
|
+
const queryStr = req.getQuery();
|
|
568
|
+
const fullUrl = `http://localhost${urlPath}${queryStr ? `?${queryStr}` : ''}`;
|
|
569
|
+
const matched = matchWsRoute(wsCfg.routes, fullUrl);
|
|
570
|
+
if (!matched) {
|
|
571
|
+
res.writeStatus('404 Not Found').end();
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
const handler: any = matched.params
|
|
575
|
+
? { ...matched.handler, params: matched.params }
|
|
576
|
+
: matched.handler;
|
|
577
|
+
res.upgrade(
|
|
578
|
+
{ handler, wrapped: null },
|
|
579
|
+
req.getHeader('sec-websocket-key'),
|
|
580
|
+
req.getHeader('sec-websocket-protocol'),
|
|
581
|
+
req.getHeader('sec-websocket-extensions'),
|
|
582
|
+
context
|
|
583
|
+
);
|
|
584
|
+
},
|
|
585
|
+
open(ws: any) {
|
|
586
|
+
wsCfg.adapter.open(getWrapped(ws));
|
|
587
|
+
},
|
|
588
|
+
message(ws: any, msg: ArrayBuffer, isBinary: boolean) {
|
|
589
|
+
const payload = isBinary ? new Uint8Array(msg) : Buffer.from(msg).toString('utf8');
|
|
590
|
+
wsCfg.adapter.message(getWrapped(ws), payload);
|
|
591
|
+
},
|
|
592
|
+
drain(ws: any) {
|
|
593
|
+
wsCfg.adapter.drain(getWrapped(ws));
|
|
594
|
+
},
|
|
595
|
+
close(ws: any, code: number, message: ArrayBuffer) {
|
|
596
|
+
const reason = message && message.byteLength > 0 ? Buffer.from(message).toString('utf8') : '';
|
|
597
|
+
wsCfg.adapter.close(getWrapped(ws), code, reason);
|
|
598
|
+
}
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
let listenSocket: any = null;
|
|
603
|
+
let boundPort = opts.port;
|
|
604
|
+
|
|
605
|
+
const ready = new Promise<void>((resolve, reject) => {
|
|
606
|
+
app.listen(opts.hostname, opts.port, (token: any) => {
|
|
607
|
+
if (!token) {
|
|
608
|
+
reject(new Error(`[BareJS] uWebSockets.js failed to listen on ${opts.hostname}:${opts.port}`));
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
listenSocket = token;
|
|
612
|
+
try {
|
|
613
|
+
boundPort = uwsMod.us_socket_local_port(token) || opts.port;
|
|
614
|
+
} catch {
|
|
615
|
+
boundPort = opts.port;
|
|
616
|
+
}
|
|
617
|
+
resolve();
|
|
618
|
+
});
|
|
619
|
+
});
|
|
620
|
+
|
|
621
|
+
const stopFn = () => {
|
|
622
|
+
if (listenSocket) {
|
|
623
|
+
try {
|
|
624
|
+
uwsMod.us_listen_socket_close(listenSocket);
|
|
625
|
+
} catch {}
|
|
626
|
+
listenSocket = null;
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
|
|
630
|
+
const drainFn = async (timeoutMs: number = 5000) => {
|
|
631
|
+
stopFn();
|
|
632
|
+
const deadline = Date.now() + timeoutMs;
|
|
633
|
+
while (inFlight > 0 && Date.now() < deadline) {
|
|
634
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
|
|
638
|
+
Object.defineProperty(app, 'port', {
|
|
639
|
+
get: () => boundPort,
|
|
640
|
+
configurable: true
|
|
641
|
+
});
|
|
642
|
+
app.stop = stopFn;
|
|
643
|
+
app.drain = drainFn;
|
|
644
|
+
app.ready = ready;
|
|
645
|
+
|
|
646
|
+
return {
|
|
647
|
+
get port() {
|
|
648
|
+
return boundPort;
|
|
649
|
+
},
|
|
650
|
+
stop: stopFn,
|
|
651
|
+
drain: drainFn,
|
|
652
|
+
raw: app,
|
|
653
|
+
ready
|
|
654
|
+
} as ServerHandle & { ready: Promise<void>; drain: (timeoutMs?: number) => Promise<void> };
|
|
655
|
+
}
|
package/src/security/auth.ts
CHANGED
|
@@ -351,10 +351,11 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
351
351
|
return checkClaimsAndRevocation(ctx, decoded, token, next);
|
|
352
352
|
};
|
|
353
353
|
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
354
|
+
const mw = customRevoked || revocationStore
|
|
355
|
+
? async (ctx: any, next: any) => verifySync(ctx, next)
|
|
356
|
+
: verifySync;
|
|
357
|
+
(mw as any).__isBareAuth = true;
|
|
358
|
+
return mw;
|
|
358
359
|
}
|
|
359
360
|
|
|
360
361
|
// Asymmetric (RS256 / ES256) and/or JWKS verification path
|
|
@@ -426,7 +427,7 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
426
427
|
return imported;
|
|
427
428
|
};
|
|
428
429
|
|
|
429
|
-
|
|
430
|
+
const mw = async (ctx: any, next: any) => {
|
|
430
431
|
const authHeader = ctx.req.headers.get('Authorization');
|
|
431
432
|
if (!authHeader?.startsWith('Bearer ')) {
|
|
432
433
|
return ctx.status(401).send("Bearer token required");
|
|
@@ -498,6 +499,8 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
498
499
|
}
|
|
499
500
|
return checkClaimsAndRevocation(ctx, decoded, token, next);
|
|
500
501
|
};
|
|
502
|
+
(mw as any).__isBareAuth = true;
|
|
503
|
+
return mw;
|
|
501
504
|
};
|
|
502
505
|
|
|
503
506
|
const sha256 = (value: string): Buffer => createHash('sha256').update(value).digest();
|
|
@@ -510,7 +513,7 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
|
510
513
|
const expectedUserHash = sha256(credentials.user);
|
|
511
514
|
const expectedPassHash = sha256(credentials.pass);
|
|
512
515
|
|
|
513
|
-
|
|
516
|
+
const mw = async (ctx: any, next: Next) => {
|
|
514
517
|
const authHeader = ctx.req.headers.get('Authorization');
|
|
515
518
|
if (!authHeader?.startsWith('Basic ')) {
|
|
516
519
|
return ctx.status(401).json({ status: 'error', message: 'Basic Auth required' });
|
|
@@ -537,6 +540,8 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
|
537
540
|
|
|
538
541
|
return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
539
542
|
};
|
|
543
|
+
(mw as any).__isBasicAuth = true;
|
|
544
|
+
return mw;
|
|
540
545
|
};
|
|
541
546
|
|
|
542
547
|
/**
|