-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlauncher-checker.ts
289 lines (250 loc) · 8.09 KB
/
launcher-checker.ts
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import { load } from "https://deno.land/std/dotenv/mod.ts";
// Define types for our GraphQL responses
interface ScanAllResponse {
data: {
scanAll: {
scanID: string;
};
};
}
interface GetScannedAppsResponse {
data: {
getScannedAppsInfo: {
isStillScanning: boolean;
} | null;
};
}
interface CheckScanInProgressResponse {
data: {
checkScanInProgress: {
isInProgress: boolean;
};
};
}
// Load environment variables from .env file
const env = await load({ export: true });
// GraphQL endpoint and API key from environment variables (or default)
const GRAPHQL_ENDPOINT = Deno.env.get("GRAPHQL_ENDPOINT") ||
"https://api.cloud.ox.security/api/apollo-gateway"; //from env or use default
const API_KEY = Deno.env.get("API_KEY");
// Function to check if a scan is currently in progress
async function checkScanInProgress(): Promise<boolean> {
const query = `
query CheckScanInProgress {
checkScanInProgress {
isInProgress
}
}
`;
try {
const response = await fetch(GRAPHQL_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": API_KEY,
},
body: JSON.stringify({
query: query,
variables: {},
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: CheckScanInProgressResponse = await response.json();
const isInProgress = data.data?.checkScanInProgress?.isInProgress;
console.log(
`Scan in progress check: ${
isInProgress
? "A scan is currently running"
: "No scan currently running"
}`,
);
return isInProgress;
} catch (error) {
console.error(`Error checking if scan is in progress: ${error}`);
// If we can't determine if a scan is in progress, return true as a safety measure
return true;
}
}
// Function to initiate a scan and get a scanID
async function initiateScanning(): Promise<string> {
const scanMutation = `
mutation Mutation {
scanAll {
scanID
}
}
`;
const response = await fetch(GRAPHQL_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": API_KEY,
},
body: JSON.stringify({
query: scanMutation,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: ScanAllResponse = await response.json();
if (!data.data?.scanAll?.scanID) {
throw new Error("Failed to get scanID from the response");
}
console.log(`Scan initiated with scanID: ${data.data.scanAll.scanID}`);
return data.data.scanAll.scanID;
}
// Modified checkScanningStatus to include more detailed state information
async function checkScanningStatus(
scanID: string,
): Promise<{ isStillScanning: boolean | null; error?: string }> {
const statusQuery = `
query IsStillScanning($getScanInfoInput: ScanInfoInput) {
getScannedAppsInfo(getScanInfoInput: $getScanInfoInput) {
isStillScanning
}
}
`;
const variables = {
getScanInfoInput: {
scanID: scanID,
},
};
try {
const response = await fetch(GRAPHQL_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": API_KEY,
},
body: JSON.stringify({
query: statusQuery,
variables: variables,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: GetScannedAppsResponse = await response.json();
// Return the status result
return {
isStillScanning: data.data.getScannedAppsInfo?.isStillScanning ?? null,
};
} catch (error) {
console.error(`Error in checkScanningStatus: ${error}`);
return {
isStillScanning: null,
error: error.message,
};
}
}
// Modified polling function to differentiate between not-started and cancelled states
async function pollUntilScanComplete(
scanID: string,
maxAttempts = Number(Deno.env.get("MAX_POLL_ATTEMPTS")) || 100,
intervalMs = Number(Deno.env.get("POLL_INTERVAL_MS")) || 30000, //30 seconds between polls
initializationTimeoutMs = Number(Deno.env.get("INITIALIZATION_TIMEOUT_MS")) ||
300000, // 5 minutes (5*60*1000) for initialization
): Promise<{ success: boolean; status: string }> {
console.log(
`Polling every ${
intervalMs / 1000
} seconds until scan completion for scanID: ${scanID}`,
);
let attempts = 0;
let consecutiveNullResponses = 0;
const maxConsecutiveNullResponses = Math.ceil(
initializationTimeoutMs / intervalMs,
);
let scanStarted = false;
while (attempts < maxAttempts) {
attempts++;
console.log(`Poll attempt ${attempts}/${maxAttempts}`);
const statusResult = await checkScanningStatus(scanID);
// If we got a null response
if (statusResult.isStillScanning === null) {
consecutiveNullResponses++;
// If we previously detected the scan as started, a null now likely means cancellation
if (scanStarted) {
console.log(
"Scan appears to have been cancelled - previously running but now returning null",
);
return { success: false, status: "cancelled" };
}
// If we've been getting null responses for too long, it might be stuck or cancelled before starting
if (consecutiveNullResponses >= maxConsecutiveNullResponses) {
console.log(
`Scan initialization timeout after ${
initializationTimeoutMs / 1000
} seconds. Scan may have been cancelled externally before initialization completed.`,
);
return { success: false, status: "initialization_timeout" };
}
console.log(
`Scan initializing... (${consecutiveNullResponses}/${maxConsecutiveNullResponses} attempts with null response)`,
);
} // If isStillScanning is false, scan is complete
else if (statusResult.isStillScanning === false) {
console.log("Scan completed successfully!");
return { success: true, status: "completed" };
} // If isStillScanning is true, scan is in progress
else {
console.log("Scan in progress...");
scanStarted = true;
consecutiveNullResponses = 0; // Reset counter since we got a non-null response
}
// Wait before next attempt
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
return { success: false, status: "max_attempts_reached" };
}
// Updated main function to handle the more detailed status response
async function main() {
try {
// Step 1: Check if a scan is already in progress
const scanInProgress = await checkScanInProgress();
if (scanInProgress) {
console.log(
"Cannot start a new scan because a scan is already in progress.",
);
return;
}
// Step 2: Initiate scan and get scanID
const scanID = await initiateScanning();
// Step 3: Poll until scan is complete or a definitive state is reached
const result = await pollUntilScanComplete(scanID);
if (result.success) {
console.log(
`Process completed successfully with status: ${result.status}`,
);
} else {
console.log(
`Process did not complete successfully. Status: ${result.status}`,
);
// Take different actions based on status
switch (result.status) {
case "cancelled":
console.log(
"The scan was cancelled externally after it was started. You may want to initiate a new scan.",
);
break;
case "initialization_timeout":
console.log(
"The scan failed to initialize within the expected timeframe. Check resources or if an external process cancelled the scan.",
);
break;
case "max_attempts_reached":
console.log(
"Maximum polling attempts reached. The scan may still be running but taking longer than expected. Increase MAX_POLL_ATTEMPTS if this occurs regularly.",
);
break;
}
}
} catch (error) {
console.error(`Error in scanning process: ${error}`);
}
}
// Run the program
main();