-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
186 lines (156 loc) · 5.29 KB
/
Copy pathindex.js
File metadata and controls
186 lines (156 loc) · 5.29 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
/**
* APRS API Relay
* A Cloudflare Worker that securely relays requests to the APRS.fi API
*/
// CORS headers for web clients
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400',
};
// Cache configuration - cache responses for 30 seconds
const CACHE_TTL = 30;
/**
* Handle OPTIONS requests for CORS preflight
*/
function handleOptions() {
return new Response(null, {
status: 204,
headers: CORS_HEADERS,
});
}
/**
* Handle health check requests
*/
function handleHealth() {
return new Response(JSON.stringify({
status: 'healthy',
service: 'aprs-api-relay',
version: '1.0.0',
timestamp: new Date().toISOString(),
}), {
status: 200,
headers: {
'Content-Type': 'application/json',
...CORS_HEADERS,
},
});
}
/**
* Create an error response
*/
function errorResponse(message, status = 500) {
return new Response(JSON.stringify({
error: message,
service: 'aprs-api-relay',
}), {
status,
headers: {
'Content-Type': 'application/json',
...CORS_HEADERS,
},
});
}
/**
* Validate that required API parameters are present
*/
function validateRequest(params) {
const what = params.get('what');
if (!what) {
return { valid: false, error: 'Missing required parameter: what' };
}
const validTypes = ['loc', 'wx', 'enter', 'list'];
if (!validTypes.includes(what)) {
return { valid: false, error: `Invalid "what" parameter. Must be one of: ${validTypes.join(', ')}` };
}
// For loc and wx queries, a name or location is typically required
if ((what === 'loc' || what === 'wx') && !params.get('name') && !params.get('lat')) {
return { valid: false, error: `Missing required parameter for ${what} query: name or lat/lng` };
}
return { valid: true };
}
/**
* Main request handler
*/
async function handleRequest(request, env, ctx) {
try {
const url = new URL(request.url);
const path = url.pathname;
// Handle CORS preflight
if (request.method === 'OPTIONS') {
return handleOptions();
}
// Health check endpoint (only when no query parameters)
if (path === '/health' || (path === '/' && url.search === '')) {
return handleHealth();
}
// Only allow GET requests for the proxy
if (request.method !== 'GET') {
return errorResponse('Method not allowed. Use GET.', 405);
}
// Verify API key is configured
if (!env.APRS_API_KEY) {
return errorResponse('APRS_API_KEY not configured. Please set the worker secret.', 500);
}
// Extract and validate query parameters
const params = new URLSearchParams(url.search);
// Remove any client-provided API key to prevent misuse
params.delete('apikey');
// Add the server API key
params.set('apikey', env.APRS_API_KEY);
// Validate request parameters
const validation = validateRequest(params);
if (!validation.valid) {
return errorResponse(validation.error, 400);
}
// Construct the aprs.fi API URL
const apiUrl = `https://api.aprs.fi/api/get?${params.toString()}`;
// Fetch from APRS.fi API with timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
const response = await fetch(apiUrl, {
signal: controller.signal,
headers: {
'User-Agent': 'aprs-api-relay/1.0.0 (Cloudflare Worker)',
},
}).finally(() => clearTimeout(timeoutId));
// Check for API errors
if (!response.ok) {
return errorResponse(`APRS.fi API error: ${response.status} ${response.statusText}`, response.status);
}
// Parse response to check for API-level errors
const data = await response.json();
if (data.result === 'fail') {
return new Response(JSON.stringify(data), {
status: 400,
headers: {
'Content-Type': 'application/json',
...CORS_HEADERS,
},
});
}
// Return successful response with CORS and caching headers
return new Response(JSON.stringify(data), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Cache-Control': `public, max-age=${CACHE_TTL}`,
...CORS_HEADERS,
},
});
} catch (error) {
// Handle different error types
if (error.name === 'AbortError') {
return errorResponse('Request timeout. APRS.fi API did not respond in time.', 504);
}
// Log error for debugging (won't show in production without wrangler tail)
console.error('APRS.fi Proxy Error:', error);
return errorResponse('Internal server error. Please try again later.', 500);
}
}
export default {
async fetch(request, env, ctx) {
return handleRequest(request, env, ctx);
},
};