-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathproxy.ts
More file actions
249 lines (224 loc) Β· 6.37 KB
/
proxy.ts
File metadata and controls
249 lines (224 loc) Β· 6.37 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
246
247
248
249
import child_process from "node:child_process";
import fs from "fs";
import path from "path";
import { Writable } from "node:stream";
import type {
ProxyRequest,
ProxyResponse,
ProxyCommand,
ProxyJSONResponse,
ms,
} from "../types";
const DEFAULT_PROXY_VM_NAME = "sd-proxy";
const DEFAULT_PROXY_CMD_TIMEOUT_MS = 5000 as ms;
const DEFAULT_STREAM_MAX_RETRY_ATTEMPTS = 3;
// Proxies a network request through sd-proxy
// For streaming requests, `downloadPath` must be specified as
// the file location where stream data is downloaded
export async function proxy(
request: ProxyRequest,
downloadPath?: string,
abortSignal?: AbortSignal,
): Promise<ProxyResponse> {
let command = "";
let commandOptions: string[] = [];
const env: Map<string, string> = new Map();
if (import.meta.env.MODE == "development") {
command = __PROXY_CMD__;
env.set("SD_PROXY_ORIGIN", __PROXY_ORIGIN__);
env.set("DISABLE_TOR", "yes");
} else {
command = "/usr/lib/qubes/qrexec-client-vm";
const proxyVmName = DEFAULT_PROXY_VM_NAME;
commandOptions = [proxyVmName, "securedrop.Proxy"];
}
const proxyCommand: ProxyCommand = {
command: command,
options: commandOptions,
env: env,
timeout: DEFAULT_PROXY_CMD_TIMEOUT_MS,
abortSignal: abortSignal,
};
if (request.stream) {
if (!downloadPath) {
return Promise.reject(
`Error: no download path specified for streaming request`,
);
}
try {
return proxyStreamRequest(
request,
proxyCommand,
downloadPath,
DEFAULT_STREAM_MAX_RETRY_ATTEMPTS,
);
} catch (err) {
return Promise.reject(`Error proxying streaming request: ${err}`);
}
}
return proxyJSONRequest(request, proxyCommand);
}
function parseJSONResponse(response: string): ProxyJSONResponse {
const result = JSON.parse(response);
const status = result["status"];
let body = result["body"];
if (!status) {
throw new Error(`Invalid response: no status code found.\n`);
}
const error =
(status >= 400 && status < 500) || (status >= 500 && status < 600);
if (!error) {
try {
if (body && typeof body === "string") {
body = JSON.parse(body);
}
} catch (e) {
console.log(
`Failed to parse response body as JSON: ${result["status"]}: ${result["body"]}: ${e}`,
);
}
}
return {
error,
data: body,
status: status,
headers: result["headers"] || {},
};
}
export async function proxyJSONRequest(
request: ProxyRequest,
command: ProxyCommand,
): Promise<ProxyJSONResponse> {
return new Promise((resolve, reject) => {
const process = child_process.spawn(command.command, command.options, {
env: Object.fromEntries(command.env),
timeout: command.timeout,
signal: command.abortSignal,
});
let stdout = "";
let stderr = "";
process.stdout.on("data", (data) => {
stdout += data.toString();
});
process.stderr.on("data", (data) => {
stderr += data.toString();
});
process.on("close", (code, signal) => {
if (signal) {
reject(new Error(`Process terminated with signal ${signal}`));
} else if (code != 0) {
reject(
new Error(`Process exited with non-zero code ${code}: ${stderr}`),
);
} else {
try {
resolve(parseJSONResponse(stdout));
} catch (err) {
reject(err);
}
}
});
process.on("error", (error) => {
reject(error);
});
process.stdin.write(JSON.stringify(request) + "\n");
process.stdin.end();
});
}
export async function proxyStreamRequest(
request: ProxyRequest,
command: ProxyCommand,
downloadPath: string,
maxRetryAttempts: number,
): Promise<ProxyResponse> {
let writeStream: fs.WriteStream;
try {
const downloadDir = path.dirname(downloadPath);
await fs.promises.mkdir(downloadDir, { recursive: true });
writeStream = fs.createWriteStream(downloadPath);
} catch (err) {
return Promise.reject(
`Error opening write stream to download path: ${err}`,
);
}
let retries = 0;
let lastErr;
while (retries < maxRetryAttempts) {
try {
return proxyStreamInner(
request,
command,
writeStream,
writeStream.bytesWritten,
);
} catch (err) {
lastErr = err;
retries += 1;
console.log(
`Error streaming proxy request: ${err}.\nRetrying... attempts=${retries}, remaining=${maxRetryAttempts - retries}`,
);
}
}
return Promise.reject(
`Failed to proxy stream request, max retry attempts exceeded. Error ${lastErr}`,
);
}
// Streams proxy request through sd-proxy, writing stream output to
// the provided writeStream.
export async function proxyStreamInner(
request: ProxyRequest,
command: ProxyCommand,
writeStream: Writable,
offset?: number,
): Promise<ProxyResponse> {
return new Promise((resolve, reject) => {
let stderr = "";
let stdout = "";
const process = child_process.spawn(command.command, command.options, {
env: Object.fromEntries(command.env),
timeout: command.timeout,
signal: command.abortSignal,
});
process.stdout.pipe(writeStream);
process.stdout.on("data", (data) => {
stdout += data;
});
process.stderr.on("data", (data) => {
stderr += data;
});
process.stdout.on("error", (err) => {
reject(`Error reading stream data: ${err}`);
});
writeStream.on("error", (err) => {
reject(`Error writing stream data: ${err}`);
});
process.on("close", async (code, signal) => {
writeStream.end();
if (signal) {
reject(`Process terminated with signal ${signal}`);
}
if (code != 0) {
reject(`Process exited with non-zero code ${code}: ${stderr}`);
}
try {
// If we receive JSON data, parse and return
resolve(parseJSONResponse(stdout));
} catch {
try {
const header = JSON.parse(stderr);
resolve({ sha256sum: header["headers"]["etag"] || "" });
} catch (err) {
reject(`Error reading headers from proxy stderr: ${err}`);
}
}
});
process.on("error", (err) => {
reject(`Proxy process error: ${err}`);
});
if (offset && offset != 0) {
request.headers["Range"] = `bytes=${offset}-`;
}
process.stdin.write(JSON.stringify(request) + "\n");
process.stdin.end();
});
}