-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathutils.ts
More file actions
245 lines (225 loc) · 8.38 KB
/
utils.ts
File metadata and controls
245 lines (225 loc) · 8.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { randomBytes, createHash } from 'node:crypto';
import { Readable } from 'node:stream';
import { performance } from 'node:perf_hooks';
import { ReadableStream, TransformStream } from 'node:stream/web';
import { Blob } from 'node:buffer';
import type { FixJSONCtlChars } from './Request.js';
import { SocketInfo } from './Response.js';
import symbols from './symbols.js';
import { IncomingHttpHeaders } from './IncomingHttpHeaders.js';
const JSONCtlCharsMap: Record<string, string> = {
'"': '\\"', // \u0022
'\\': '\\\\', // \u005c
'\b': '\\b', // \u0008
'\f': '\\f', // \u000c
'\n': '\\n', // \u000a
'\r': '\\r', // \u000d
'\t': '\\t', // \u0009
};
/* eslint no-control-regex: "off"*/
const JSONCtlCharsRE = /[\u0000-\u001F\u005C]/g;
function replaceOneChar(c: string) {
return JSONCtlCharsMap[c] || '\\u' + (c.charCodeAt(0) + 0x10000).toString(16).substring(1);
}
function replaceJSONCtlChars(value: string) {
return value.replace(JSONCtlCharsRE, replaceOneChar);
}
export function parseJSON(data: string, fixJSONCtlChars?: FixJSONCtlChars) {
if (typeof fixJSONCtlChars === 'function') {
data = fixJSONCtlChars(data);
} else if (fixJSONCtlChars) {
// https://github.com/node-modules/urllib/pull/77
// remote the control characters (U+0000 through U+001F)
data = replaceJSONCtlChars(data);
}
try {
data = JSON.parse(data);
} catch (err: any) {
if (err.name === 'SyntaxError') {
err.name = 'JSONResponseFormatError';
}
if (data.length > 1024) {
// show 0~512 ... -512~end data
err.message += ' (data json format: ' +
JSON.stringify(data.slice(0, 512)) + ' ...skip... ' + JSON.stringify(data.slice(data.length - 512)) + ')';
} else {
err.message += ' (data json format: ' + JSON.stringify(data) + ')';
}
throw err;
}
return data;
}
function md5(s: string) {
const sum = createHash('md5');
sum.update(s, 'utf8');
return sum.digest('hex');
}
const AUTH_KEY_VALUE_RE = /(\w{1,100})=["']?([^'"]+)["']?/;
let NC = 0;
const NC_PAD = '00000000';
export function digestAuthHeader(method: string, uri: string, wwwAuthenticate: string, userpass: string) {
// WWW-Authenticate: Digest realm="[email protected]",
// qop="auth,auth-int",
// nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
// opaque="5ccc069c403ebaf9f0171e9517f40e41"
// Authorization: Digest username="Mufasa",
// realm="[email protected]",
// nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
// uri="/dir/index.html",
// qop=auth,
// nc=00000001,
// cnonce="0a4f113b",
// response="6629fae49393a05397450978507c4ef1",
// opaque="5ccc069c403ebaf9f0171e9517f40e41"
// HA1 = MD5( "Mufasa:[email protected]:Circle Of Life" )
// = 939e7578ed9e3c518a452acee763bce9
//
// HA2 = MD5( "GET:/dir/index.html" )
// = 39aff3a2bab6126f332b942af96d3366
//
// Response = MD5( "939e7578ed9e3c518a452acee763bce9:\
// dcd98b7102dd2f0e8b11d0f600bfb0c093:\
// 00000001:0a4f113b:auth:\
// 39aff3a2bab6126f332b942af96d3366" )
// = 6629fae49393a05397450978507c4ef1
const parts = wwwAuthenticate.split(',');
const opts: Record<string, string> = {};
for (const part of parts) {
const m = part.match(AUTH_KEY_VALUE_RE);
if (m) {
opts[m[1]] = m[2].replace(/["']/g, '');
}
}
if (!opts.realm || !opts.nonce) {
return '';
}
let qop = opts.qop || '';
const index = userpass.indexOf(':');
const user = userpass.substring(0, index);
const pass = userpass.substring(index + 1);
let nc = String(++NC);
nc = `${NC_PAD.substring(nc.length)}${nc}`;
const cnonce = randomBytes(8).toString('hex');
const ha1 = md5(`${user}:${opts.realm}:${pass}`);
const ha2 = md5(`${method.toUpperCase()}:${uri}`);
let s = `${ha1}:${opts.nonce}`;
if (qop) {
qop = qop.split(',')[0];
s += `:${nc}:${cnonce}:${qop}`;
}
s += `:${ha2}`;
const response = md5(s);
let authstring = `Digest username="${user}", realm="${opts.realm}", nonce="${opts.nonce}", uri="${uri}", response="${response}"`;
if (opts.opaque) {
authstring += `, opaque="${opts.opaque}"`;
}
if (qop) {
authstring += `, qop=${qop}, nc=${nc}, cnonce="${cnonce}"`;
}
return authstring;
}
const MAX_ID_VALUE = Math.pow(2, 31) - 10;
const globalIds: Record<string, number> = {};
export function globalId(category: string) {
if (!globalIds[category] || globalIds[category] >= MAX_ID_VALUE) {
globalIds[category] = 0;
}
return ++globalIds[category];
}
export function performanceTime(startTime: number, now?: number) {
return Math.floor(((now ?? performance.now()) - startTime) * 1000) / 1000;
}
export function isReadable(stream: any) {
if (typeof Readable.isReadable === 'function') return Readable.isReadable(stream);
// patch from node
// https://github.com/nodejs/node/blob/1287530385137dda1d44975063217ccf90759475/lib/internal/streams/utils.js#L119
// simple way https://github.com/sindresorhus/is-stream/blob/main/index.js
return stream !== null
&& typeof stream === 'object'
&& typeof stream.pipe === 'function'
&& stream.readable !== false
&& typeof stream._read === 'function'
&& typeof stream._readableState === 'object';
}
export function updateSocketInfo(socketInfo: SocketInfo, internalOpaque: any, err?: any) {
const socket = internalOpaque[symbols.kRequestSocket] ?? err?.[symbols.kErrorSocket];
if (socket) {
socketInfo.id = socket[symbols.kSocketId];
socketInfo.handledRequests = socket[symbols.kHandledRequests];
socketInfo.handledResponses = socket[symbols.kHandledResponses];
if (socket[symbols.kSocketLocalAddress]) {
socketInfo.localAddress = socket[symbols.kSocketLocalAddress];
socketInfo.localPort = socket[symbols.kSocketLocalPort];
}
if (socket.remoteAddress) {
socketInfo.remoteAddress = socket.remoteAddress;
socketInfo.remotePort = socket.remotePort;
socketInfo.remoteFamily = socket.remoteFamily;
}
if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
socketInfo.attemptedRemoteAddresses = socket.autoSelectFamilyAttemptedAddresses;
}
socketInfo.bytesRead = socket.bytesRead;
socketInfo.bytesWritten = socket.bytesWritten;
if (socket[symbols.kSocketConnectErrorTime]) {
socketInfo.connectErrorTime = socket[symbols.kSocketConnectErrorTime];
socketInfo.connectProtocol = socket[symbols.kSocketConnectProtocol];
socketInfo.connectHost = socket[symbols.kSocketConnectHost];
socketInfo.connectPort = socket[symbols.kSocketConnectPort];
}
if (socket[symbols.kSocketConnectedTime]) {
socketInfo.connectedTime = socket[symbols.kSocketConnectedTime];
}
if (socket[symbols.kSocketRequestEndTime]) {
socketInfo.lastRequestEndTime = socket[symbols.kSocketRequestEndTime];
}
socket[symbols.kSocketRequestEndTime] = new Date();
}
}
export function convertHeader(headers: Headers): IncomingHttpHeaders {
const res: IncomingHttpHeaders = {};
for (const [ key, value ] of headers.entries()) {
if (res[key]) {
if (!Array.isArray(res[key])) {
res[key] = [ res[key] ];
}
res[key].push(value);
} else {
res[key] = value;
}
}
return res;
}
// support require from Node.js 16
export function patchForNode16() {
if (typeof global.ReadableStream === 'undefined') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.ReadableStream = ReadableStream;
}
if (typeof global.TransformStream === 'undefined') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.TransformStream = TransformStream;
}
if (typeof global.Blob === 'undefined') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.Blob = Blob;
}
if (typeof global.DOMException === 'undefined') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.DOMException = getDOMExceptionClass();
}
}
// https://github.com/jimmywarting/node-domexception/blob/main/index.js
function getDOMExceptionClass() {
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
atob(0);
} catch (err: any) {
return err.constructor;
}
}