-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiClient.js
More file actions
383 lines (352 loc) · 11.6 KB
/
Copy pathApiClient.js
File metadata and controls
383 lines (352 loc) · 11.6 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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/**
* ApiClient Module
* Handles all API communication with the NoTamperData backend.
*/
var ApiClient = (function() {
/**
* Sends hash and metadata to the NoTamperData API.
* @param {string} hash - The generated hash
* @param {Object} metadata - Metadata about the response
* @return {Object} API response or error object
*/
function sendHashToApi(hash, metadata) {
const accessToken = getAccessToken();
if (!accessToken) {
console.warn('No access token configured');
return {
error: 'Access token is required. Please configure your access token in the add-on settings.'
};
}
// Prepare payload
const payload = {
hash: hash,
formId: metadata?.formId || metadata?.form_id,
responseId: metadata?.responseId,
networkId: metadata?.networkId || metadata?.network_id || 0,
metadata: metadata
};
// Set up headers
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/json',
'User-Agent': 'NoTamperData-GoogleAppsScript/1.0'
};
const payloadString = JSON.stringify(payload);
const options = {
method: 'POST',
headers: headers,
payload: payloadString,
muteHttpExceptions: true,
followRedirects: false,
timeout: 60,
validateHttpsCertificates: true
};
// Validate payload
if (!payloadString || payloadString === '{}') {
console.error('Failed to generate valid payload');
return {
error: 'Failed to generate valid request payload'
};
}
try {
console.log('Sending hash to API endpoint...');
const response = UrlFetchApp.fetch(API_ENDPOINT + "/storehash", options);
const responseCode = response.getResponseCode();
const contentText = response.getContentText();
// Check if we got API documentation instead of actual response
if (contentText && contentText.includes('"endpoint":"storehash"') && contentText.includes('"method":"POST')) {
console.warn('Received API documentation - might be GET request fallback');
}
// Handle success responses (2xx)
if (responseCode >= 200 && responseCode < 300) {
console.log('Hash sent successfully');
try {
const parsedResponse = JSON.parse(contentText);
return parsedResponse;
} catch (e) {
console.error('Failed to parse API response:', e);
return { success: true };
}
}
// Handle authentication errors
else if (responseCode === 401) {
console.error('Authentication failed - invalid access token');
return {
error: 'Invalid access token. Please check your access token configuration.'
};
}
// Handle insufficient tokens
else if (responseCode === 402) {
console.error('Insufficient tokens');
return {
error: 'Insufficient tokens. Please purchase more tokens to continue.'
};
}
// Handle permission errors
else if (responseCode === 403) {
console.error('Permission denied');
return {
error: 'Access token does not have permission to perform this action.'
};
}
// Handle connection failures - try GET fallback
else if (responseCode === 0) {
console.warn('POST request failed, trying GET fallback...');
return tryGetFallback(hash, metadata, accessToken);
}
// Handle server errors
else if (responseCode >= 500) {
console.error('Server error:', responseCode);
return {
error: 'NoTamperData server error. Please try again later.'
};
}
// Handle other errors
else {
console.error('Request failed with status:', responseCode);
try {
const errorResponse = JSON.parse(contentText);
return {
error: errorResponse.error || `Request failed with status ${responseCode}`
};
} catch (e) {
return {
error: `Request failed with status ${responseCode}`
};
}
}
} catch (error) {
console.error('API request exception:', error);
// Handle specific error types
if (error.toString().includes('timeout')) {
return {
error: 'Request timed out. Please try again.'
};
} else if (error.toString().includes('network')) {
console.warn('Network error, trying GET fallback...');
return tryGetFallback(hash, metadata, accessToken);
} else {
return {
error: 'Unable to connect to verification service.'
};
}
}
}
/**
* Fallback function to try GET request when POST fails.
* Some network configurations may block POST requests.
* @param {string} hash - The generated hash
* @param {Object} metadata - Metadata about the response
* @param {string} accessToken - The access token
* @return {Object} API response or error object
*/
function tryGetFallback(hash, metadata, accessToken) {
try {
console.log('Attempting GET fallback...');
// Build URL parameters
const params = new URLSearchParams({
hash: hash,
formId: metadata?.formId || metadata?.form_id || '',
responseId: metadata?.responseId || '',
networkId: (metadata?.networkId || metadata?.network_id || 0).toString()
});
const getUrl = `${API_ENDPOINT}/storehash?${params.toString()}`;
const headers = {
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/json'
};
const response = UrlFetchApp.fetch(getUrl, {
method: 'GET',
headers: headers,
muteHttpExceptions: true,
timeout: 30
});
const responseCode = response.getResponseCode();
const contentText = response.getContentText();
if (responseCode >= 200 && responseCode < 300) {
console.log('GET fallback successful');
try {
const parsedResponse = JSON.parse(contentText);
return parsedResponse;
} catch (e) {
console.error('Failed to parse GET fallback response:', e);
return { success: true };
}
} else {
console.error('GET fallback also failed');
return {
error: 'Both POST and GET requests failed. Please check your connection.'
};
}
} catch (error) {
console.error('GET fallback exception:', error);
return {
error: 'Unable to connect to verification service via any method.'
};
}
}
/**
* Tests API connectivity and access token authentication.
* @return {Object} Test result with success/error status
*/
function testApiConnection() {
const accessToken = getAccessToken();
if (!accessToken) {
console.warn('Cannot test connection - no access token');
return {
success: false,
error: 'No access token configured'
};
}
const headers = {
'Authorization': `Bearer ${accessToken}`
};
try {
console.log('Testing API connection...');
const response = UrlFetchApp.fetch(API_ENDPOINT + "/health", {
'method': 'get',
'headers': headers,
'muteHttpExceptions': true,
'timeout': 10
});
const responseCode = response.getResponseCode();
if (responseCode === 200) {
console.log('API connection test successful');
try {
const responseData = JSON.parse(response.getContentText());
if (responseData.authentication && responseData.authentication.validated) {
return {
success: true,
message: 'API connection and access token validation successful'
};
} else {
return {
success: true,
message: 'API connection successful (access token not validated by server)'
};
}
} catch (e) {
return {
success: true,
message: 'API connection successful'
};
}
} else if (responseCode === 401) {
console.error('Invalid access token');
return {
success: false,
error: 'Invalid access token'
};
} else if (responseCode === 403) {
console.error('Access token lacks permissions');
return {
success: false,
error: 'Access token lacks permissions'
};
} else {
console.error('API test failed with status:', responseCode);
return {
success: false,
error: `API test failed with status ${responseCode}`
};
}
} catch (error) {
console.error('API connection test exception:', error);
return {
success: false,
error: 'Unable to connect to API servers'
};
}
}
/**
* Checks access token status and remaining token balance.
* @return {Object} Access token status result
*/
function checkAccessTokenStatus() {
const accessToken = getAccessToken();
if (!accessToken) {
console.warn('Cannot check status - no access token');
return {
success: false,
error: 'No access token configured'
};
}
const headers = {
'Authorization': `Bearer ${accessToken}`
};
try {
console.log('Checking access token status...');
const response = UrlFetchApp.fetch(API_ENDPOINT + "/access-token-status", {
'method': 'get',
'headers': headers,
'muteHttpExceptions': true,
'timeout': 10
});
const responseCode = response.getResponseCode();
const contentText = response.getContentText();
if (responseCode === 200) {
try {
const statusData = JSON.parse(contentText);
if (statusData.success && statusData.data) {
console.log('Access token status retrieved successfully');
return {
success: true,
data: statusData.data
};
} else {
return {
success: false,
error: statusData.error || 'Failed to get access token status'
};
}
} catch (e) {
console.error('Failed to parse status response:', e);
return {
success: false,
error: 'Failed to parse access token status response'
};
}
} else if (responseCode === 401) {
console.error('Invalid access token');
return {
success: false,
error: 'Invalid access token'
};
} else if (responseCode === 404) {
console.error('Access token not found');
return {
success: false,
error: 'Access token not found'
};
} else {
console.error('Status check failed with code:', responseCode);
return {
success: false,
error: `Access token status check failed with status ${responseCode}`
};
}
} catch (error) {
console.error('Access token status check exception:', error);
return {
success: false,
error: 'Unable to connect to API servers'
};
}
}
/**
* Health check for API connectivity (legacy function, kept for compatibility).
* @return {boolean} Whether the API is reachable
*/
function checkApiHealth() {
const result = testApiConnection();
return result.success;
}
// Public API
return {
sendHashToApi: sendHashToApi,
testApiConnection: testApiConnection,
checkAccessTokenStatus: checkAccessTokenStatus,
checkApiHealth: checkApiHealth
};
})();