-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathdevserver.ts
More file actions
256 lines (236 loc) · 8.03 KB
/
Copy pathdevserver.ts
File metadata and controls
256 lines (236 loc) · 8.03 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
250
251
252
253
254
255
256
/* eslint-disable @typescript-eslint/no-explicit-any */
import http from "http";
import https from "https";
import * as path from "path";
import * as fs from "fs";
import { getHandler } from "./lambda/index";
import { getStreamingHandler } from "./lambda/streamingHandler";
import {
APIGatewayProxyEvent,
APIGatewayProxyEventHeaders,
APIGatewayProxyResult,
APIGatewayProxyEventV2,
} from "aws-lambda";
import { URL } from "url";
import { buildDi } from "./lambda/utils/di";
import { LogUtil } from "./lambda/utils/log";
import fetch from "node-fetch";
import childProcess from "child_process";
import {
localdomain,
localapidomain,
localstreamingapidomain,
localport,
localapiport,
localstreamingapiport,
} from "./src/localdomain";
declare global {
namespace NodeJS {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface Global {
__COMMIT_HASH__: string;
__FULL_COMMIT_HASH__: string;
awslambda: any;
}
}
}
// Mock awslambda.streamifyResponse for local development
(global as any).awslambda = {
streamifyResponse: (handler: Function) => {
return handler;
},
};
function getBody(req: http.IncomingMessage): Promise<string> {
return new Promise((resolve) => {
let data = "";
req.on("data", (chunk) => {
data += chunk;
});
req.on("end", () => {
resolve(data);
});
});
}
async function requestToProxyEvent(request: http.IncomingMessage): Promise<APIGatewayProxyEvent> {
const body = await getBody(request);
const url = new URL(request.url || "", "http://www.example.com");
const qs: Partial<Record<string, string>> = {};
url.searchParams.forEach((v, k) => {
qs[k] = v;
});
const headers = { ...request.headers } as APIGatewayProxyEventHeaders;
const cookieHeader = headers.cookie || "";
headers["x-auth-state"] = cookieHeader.includes("session") ? "yes" : "no";
const ua = headers["user-agent"] || "";
headers["x-device-type"] = /iPhone|iPad|iPod/i.test(ua) ? "ios" : /Android/i.test(ua) ? "android" : "desktop";
return {
body: body,
headers,
multiValueHeaders: {},
httpMethod: request.method || "GET",
isBase64Encoded: false,
path: url.pathname,
pathParameters: {},
queryStringParameters: qs,
multiValueQueryStringParameters: {},
stageVariables: {},
requestContext: {} as any,
resource: "",
};
}
const handler = getHandler(() => buildDi(new LogUtil(), fetch));
const PERF_DATA_DIR = path.join(__dirname, "perfdata");
function setPerfCorsHeaders(res: http.ServerResponse): void {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
}
async function handlePerfRequest(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
setPerfCorsHeaders(res);
if (req.method === "OPTIONS") {
res.statusCode = 204;
res.end();
return;
}
if (req.method !== "POST") {
res.statusCode = 405;
res.end();
return;
}
const body = await getBody(req);
const sessionMatch = body.match(/"session":"([^"]+)"/);
const session = sessionMatch?.[1] ?? "unknown";
// Reject obvious path-traversal attempts to keep this safe even though it's dev-only.
const safeSession = /^[A-Za-z0-9_\-]+$/.test(session) ? session : "unknown";
const file = path.join(PERF_DATA_DIR, `${safeSession}.jsonl`);
fs.mkdirSync(PERF_DATA_DIR, { recursive: true });
fs.appendFileSync(file, body.endsWith("\n") ? body : body + "\n");
res.statusCode = 200;
res.end();
}
// Main API server
const server = https.createServer(
{
key: fs.readFileSync(path.join(process.env.HOME!, `.secrets/live/${localapidomain}.liftosaur.com/privkey.pem`)),
cert: fs.readFileSync(path.join(process.env.HOME!, `.secrets/live/${localapidomain}.liftosaur.com/fullchain.pem`)),
},
async (req, res) => {
try {
if (req.url === "/api/_dev/perf") {
await handlePerfRequest(req, res);
return;
}
// Handle regular API Gateway endpoints
const result = (await handler(
await requestToProxyEvent(req),
{ getRemainingTimeInMillis: () => 10000 },
() => undefined
)) as APIGatewayProxyResult;
const body = result.isBase64Encoded ? Buffer.from(result.body, "base64") : result.body;
res.statusCode = result.statusCode;
for (const k of Object.keys(result.headers || {})) {
res.setHeader(k, result.headers![k] as string);
}
res.end(body);
} catch (e) {
if (e instanceof Error) {
console.error(e);
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ name: e.name, error: e.message, stack: e.stack }));
} else {
throw e;
}
}
}
);
// Streaming API server
const streamingServer = https.createServer(
{
key: fs.readFileSync(
path.join(process.env.HOME!, `.secrets/live/${localstreamingapidomain}.liftosaur.com/privkey.pem`)
),
cert: fs.readFileSync(
path.join(process.env.HOME!, `.secrets/live/${localstreamingapidomain}.liftosaur.com/fullchain.pem`)
),
},
async (req, res) => {
try {
const url = new URL(req.url || "", "http://www.example.com");
const body = req.method === "OPTIONS" ? "" : await getBody(req);
const streamingEvent: APIGatewayProxyEventV2 = {
version: "2.0",
routeKey: "$default",
rawPath: url.pathname,
rawQueryString: url.search.substring(1),
headers: req.headers as { [key: string]: string },
requestContext: {
accountId: "123456789012",
apiId: "local",
domainName: "localhost",
domainPrefix: "local",
http: {
method: req.method || "POST",
path: url.pathname,
protocol: "HTTP/1.1",
sourceIp: "127.0.0.1",
userAgent: req.headers["user-agent"] || "",
},
requestId: "local-" + Date.now(),
time: new Date().toISOString(),
timeEpoch: Date.now(),
routeKey: "",
stage: "",
},
body,
isBase64Encoded: false,
};
const streamingHandler = getStreamingHandler(() => buildDi(new LogUtil(), fetch));
const responseStream = {
write: (chunk: unknown) => {
if (typeof chunk === "string") {
// Check if it's the metadata
if (chunk.startsWith("{") && chunk.includes("statusCode")) {
try {
const metadata = JSON.parse(chunk);
res.statusCode = metadata.statusCode;
for (const [key, value] of Object.entries(metadata.headers || {})) {
res.setHeader(key, value as string);
}
return;
} catch (e) {
// Not metadata, just write it
}
}
res.write(chunk);
} else {
res.write(chunk);
}
},
end: () => {
res.end();
},
};
await streamingHandler(streamingEvent, responseStream, () => undefined);
return;
} catch (e) {
if (e instanceof Error) {
console.error(e);
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ name: e.name, error: e.message, stack: e.stack }));
} else {
throw e;
}
}
}
);
(global as any).__COMMIT_HASH__ = childProcess.execSync("git rev-parse --short HEAD").toString().trim();
(global as any).__FULL_COMMIT_HASH__ = childProcess.execSync("git rev-parse HEAD").toString().trim();
process.env.COMMIT_HASH = (global as any).__COMMIT_HASH__;
process.env.FULL_COMMIT_HASH = (global as any).__FULL_COMMIT_HASH__;
process.env.HOST = `https://${localdomain}.liftosaur.com:${localport}`;
server.listen(localapiport, "0.0.0.0", () => {
console.log(`--------- API Server is running on port ${localapiport} ----------`);
});
streamingServer.listen(localstreamingapiport, "0.0.0.0", () => {
console.log(`--------- Streaming API Server is running on port ${localstreamingapiport} ----------`);
});