@nordsym/apiclaw 1.8.6 → 1.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +4 -4
  2. package/apiclaw-README.md +12 -12
  3. package/convex/_generated/api.d.ts +4 -0
  4. package/convex/apiKeys.ts +220 -0
  5. package/convex/directCall.ts +49 -14
  6. package/convex/email.ts +5 -5
  7. package/convex/http.ts +598 -40
  8. package/convex/logs.ts +26 -22
  9. package/convex/migrateProviderWorkspaces.ts +154 -35
  10. package/convex/providers.ts +313 -203
  11. package/convex/schema.ts +50 -1
  12. package/convex/searchLogs.ts +2 -6
  13. package/convex/seedPratham.ts +1 -1
  14. package/convex/spendAlerts.ts +2 -2
  15. package/convex/stripeActions.ts +1 -1
  16. package/convex/updateAPIStatus.ts +2 -3
  17. package/convex/workspaceSettings.ts +136 -0
  18. package/dist/cli/commands/demo.js +2 -2
  19. package/dist/cli/commands/doctor.js +1 -1
  20. package/dist/cli/commands/login.js +1 -1
  21. package/dist/cli/commands/setup.js +2 -2
  22. package/dist/discovery.js +1 -1
  23. package/dist/execute.js +3 -3
  24. package/dist/index.js +13 -13
  25. package/dist/ui/errors.js +16 -16
  26. package/dist/ui/prompts.js +1 -1
  27. package/email-templates/filestack-provider-outreach.html +1 -1
  28. package/email-templates/partnership-template.html +1 -1
  29. package/email-templates/pratham-partnership-draft.html +2 -2
  30. package/package.json +2 -2
  31. package/reports/APIClaw-Session-Report-2026-04-05.pdf +0 -0
  32. package/reports/session-report-2026-04-05.html +433 -0
  33. package/src/cli/commands/demo.ts +2 -2
  34. package/src/cli/commands/doctor.ts +1 -1
  35. package/src/cli/commands/login.ts +1 -1
  36. package/src/cli/commands/setup.ts +2 -2
  37. package/src/discovery.ts +1 -1
  38. package/src/execute.ts +3 -3
  39. package/src/index.ts +14 -14
  40. package/src/ui/errors.ts +16 -16
  41. package/src/ui/prompts.ts +1 -1
  42. package/convex/adminActivate.d.ts +0 -3
  43. package/convex/adminActivate.js +0 -47
  44. package/convex/adminStats.d.ts +0 -9
  45. package/convex/adminStats.js +0 -280
  46. package/convex/agents.d.ts +0 -84
  47. package/convex/agents.js +0 -809
  48. package/convex/analytics.d.ts +0 -5
  49. package/convex/analytics.js +0 -167
  50. package/convex/backfillAnalytics.d.ts +0 -2
  51. package/convex/backfillAnalytics.js +0 -20
  52. package/convex/backfillSearchLogs.d.ts +0 -2
  53. package/convex/backfillSearchLogs.js +0 -29
  54. package/convex/billing.d.ts +0 -88
  55. package/convex/billing.js +0 -655
  56. package/convex/capabilities.d.ts +0 -9
  57. package/convex/capabilities.js +0 -145
  58. package/convex/chains.d.ts +0 -68
  59. package/convex/chains.js +0 -1105
  60. package/convex/credits.d.ts +0 -25
  61. package/convex/credits.js +0 -186
  62. package/convex/crons.d.ts +0 -3
  63. package/convex/crons.js +0 -17
  64. package/convex/debugFilestackLogs.d.ts +0 -2
  65. package/convex/debugFilestackLogs.js +0 -17
  66. package/convex/debugGetToken.d.ts +0 -2
  67. package/convex/debugGetToken.js +0 -18
  68. package/convex/directCall.d.ts +0 -72
  69. package/convex/directCall.js +0 -627
  70. package/convex/earnProgress.d.ts +0 -58
  71. package/convex/earnProgress.js +0 -649
  72. package/convex/email.d.ts +0 -14
  73. package/convex/email.js +0 -300
  74. package/convex/feedback.d.ts +0 -7
  75. package/convex/feedback.js +0 -227
  76. package/convex/http.d.ts +0 -3
  77. package/convex/http.js +0 -1408
  78. package/convex/inbound.d.ts +0 -2
  79. package/convex/inbound.js +0 -32
  80. package/convex/logs.d.ts +0 -48
  81. package/convex/logs.js +0 -621
  82. package/convex/migrateFilestack.d.ts +0 -2
  83. package/convex/migrateFilestack.js +0 -74
  84. package/convex/migratePartnersProd.d.ts +0 -8
  85. package/convex/migratePartnersProd.js +0 -165
  86. package/convex/migratePratham.d.ts +0 -2
  87. package/convex/migratePratham.js +0 -121
  88. package/convex/migrateProviderWorkspaces.d.ts +0 -2
  89. package/convex/migrateProviderWorkspaces.js +0 -55
  90. package/convex/mou.d.ts +0 -6
  91. package/convex/mou.js +0 -82
  92. package/convex/providerKeys.d.ts +0 -31
  93. package/convex/providerKeys.js +0 -257
  94. package/convex/providers.d.ts +0 -35
  95. package/convex/providers.js +0 -922
  96. package/convex/purchases.d.ts +0 -7
  97. package/convex/purchases.js +0 -157
  98. package/convex/ratelimit.d.ts +0 -4
  99. package/convex/ratelimit.js +0 -91
  100. package/convex/searchLogs.d.ts +0 -13
  101. package/convex/searchLogs.js +0 -246
  102. package/convex/seedAPILayerAPIs.d.ts +0 -7
  103. package/convex/seedAPILayerAPIs.js +0 -177
  104. package/convex/seedDirectCallConfigs.d.ts +0 -2
  105. package/convex/seedDirectCallConfigs.js +0 -324
  106. package/convex/seedPratham.d.ts +0 -6
  107. package/convex/seedPratham.js +0 -150
  108. package/convex/spendAlerts.d.ts +0 -36
  109. package/convex/spendAlerts.js +0 -380
  110. package/convex/stripeActions.d.ts +0 -19
  111. package/convex/stripeActions.js +0 -411
  112. package/convex/teams.d.ts +0 -21
  113. package/convex/teams.js +0 -215
  114. package/convex/telemetry.d.ts +0 -4
  115. package/convex/telemetry.js +0 -74
  116. package/convex/updateAPIStatus.d.ts +0 -6
  117. package/convex/updateAPIStatus.js +0 -40
  118. package/convex/usage.d.ts +0 -27
  119. package/convex/usage.js +0 -229
  120. package/convex/waitlist.d.ts +0 -4
  121. package/convex/waitlist.js +0 -49
  122. package/convex/webhooks.d.ts +0 -12
  123. package/convex/webhooks.js +0 -410
  124. package/convex/workspaces.d.ts +0 -33
  125. package/convex/workspaces.js +0 -991
package/convex/http.js DELETED
@@ -1,1408 +0,0 @@
1
- import { httpRouter } from "convex/server";
2
- import { httpAction } from "./_generated/server";
3
- import { api, internal } from "./_generated/api";
4
- import { createCheckoutSession, createPortalSession, handleStripeWebhook, checkoutOptions, portalOptions, webhookOptions, } from "./stripeActions";
5
- const http = httpRouter();
6
- // Provider catalog
7
- const PROVIDERS = {
8
- "46elks": {
9
- name: "46elks",
10
- description: "SMS API for EU/Nordics. GDPR compliant.",
11
- category: "sms",
12
- pricing: "~$0.035/SMS",
13
- regions: ["EU", "Nordic"],
14
- tags: ["sms", "eu", "gdpr", "nordic"],
15
- },
16
- twilio: {
17
- name: "Twilio",
18
- description: "SMS and Voice API. Global coverage.",
19
- category: "sms",
20
- pricing: "~$0.04/SMS, ~$0.01/min voice",
21
- regions: ["Global"],
22
- tags: ["sms", "voice", "global"],
23
- },
24
- resend: {
25
- name: "Resend",
26
- description: "Modern email API. Developer-friendly.",
27
- category: "email",
28
- pricing: "~$0.001/email",
29
- regions: ["Global"],
30
- tags: ["email", "transactional"],
31
- },
32
- brave_search: {
33
- name: "Brave Search",
34
- description: "Privacy-focused web search API.",
35
- category: "search",
36
- pricing: "~$0.005/search",
37
- regions: ["Global"],
38
- tags: ["search", "web", "privacy"],
39
- },
40
- openrouter: {
41
- name: "OpenRouter",
42
- description: "Multi-model LLM API. Access GPT, Claude, Llama, etc.",
43
- category: "llm",
44
- pricing: "Varies by model",
45
- regions: ["Global"],
46
- tags: ["llm", "ai", "gpt", "claude"],
47
- },
48
- elevenlabs: {
49
- name: "ElevenLabs",
50
- description: "Text-to-speech API. High quality voices.",
51
- category: "tts",
52
- pricing: "~$0.0003/char",
53
- regions: ["Global"],
54
- tags: ["tts", "voice", "audio"],
55
- },
56
- replicate: {
57
- name: "Replicate",
58
- description: "Run AI models (Whisper, SDXL, Llama, etc). Pay per prediction.",
59
- category: "ai",
60
- pricing: "Varies by model",
61
- regions: ["Global"],
62
- tags: ["ai", "ml", "whisper", "image", "audio", "transcription"],
63
- },
64
- firecrawl: {
65
- name: "Firecrawl",
66
- description: "Web scraping and crawling API. Extract clean data from any URL.",
67
- category: "scraping",
68
- pricing: "~$0.001/page",
69
- regions: ["Global"],
70
- tags: ["scraping", "web", "crawl", "extract"],
71
- },
72
- github: {
73
- name: "GitHub",
74
- description: "GitHub API. Search repos, manage code, access developer data.",
75
- category: "code",
76
- pricing: "Free tier available",
77
- regions: ["Global"],
78
- tags: ["github", "code", "repos", "developer"],
79
- },
80
- e2b: {
81
- name: "E2B",
82
- description: "Secure code sandbox for AI agents. Run Python, shell commands in isolated environments.",
83
- category: "sandbox",
84
- pricing: "$0.000028/s (2 vCPU)",
85
- regions: ["Global"],
86
- tags: ["sandbox", "code", "python", "execution", "ai", "agents"],
87
- },
88
- apilayer: {
89
- name: "APILayer",
90
- description: "14 APIs: exchange rates, market data, aviation, PDF, screenshots, email/phone verification, VAT, news, scraping, and more.",
91
- category: "multi",
92
- pricing: "Free tier available, paid plans per API",
93
- regions: ["Global"],
94
- tags: ["exchange", "stocks", "aviation", "pdf", "screenshot", "verification", "vat", "news", "scraping"],
95
- },
96
- };
97
- // CORS headers
98
- const corsHeaders = {
99
- "Access-Control-Allow-Origin": "*",
100
- "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
101
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
102
- };
103
- // Helper for JSON responses
104
- function jsonResponse(data, status = 200) {
105
- return new Response(JSON.stringify(data), {
106
- status,
107
- headers: { "Content-Type": "application/json", ...corsHeaders },
108
- });
109
- }
110
- // Helper to validate session and log API usage
111
- async function validateAndLogProxyCall(ctx, request, provider, action) {
112
- const identifier = request.headers.get("X-APIClaw-Identifier");
113
- const subagentId = request.headers.get("X-APIClaw-Subagent") || "main";
114
- console.log("[Proxy] Call received", { provider, action, identifier, subagentId });
115
- // Resolve workspaceId from identifier if possible
116
- let resolvedWorkspaceId;
117
- if (identifier && !identifier.startsWith("anon:") && identifier !== "unknown" && identifier.length > 20) {
118
- resolvedWorkspaceId = identifier;
119
- }
120
- // ALWAYS log to analytics (even if identifier is missing)
121
- try {
122
- const result = await ctx.runMutation(api.analytics.log, {
123
- event: "api_call",
124
- provider,
125
- identifier: identifier || "unknown",
126
- workspaceId: resolvedWorkspaceId,
127
- metadata: { action, subagentId },
128
- });
129
- console.log("[Proxy] Analytics logged:", result);
130
- }
131
- catch (e) {
132
- console.error("[Proxy] Analytics logging failed:", e.message, e.stack);
133
- // Continue even if analytics fails
134
- }
135
- // If we have an identifier and it's a workspace ID (not anon:), log to workspace
136
- if (resolvedWorkspaceId) {
137
- try {
138
- await ctx.runMutation(api.logs.createProxyLog, {
139
- workspaceId: resolvedWorkspaceId,
140
- provider,
141
- action,
142
- subagentId,
143
- });
144
- // Increment workspace usage
145
- await ctx.runMutation(api.workspaces.incrementUsage, {
146
- workspaceId: resolvedWorkspaceId,
147
- });
148
- console.log("[Proxy] Workspace logged for:", resolvedWorkspaceId);
149
- return { valid: true, workspaceId: resolvedWorkspaceId, subagentId };
150
- }
151
- catch (e) {
152
- console.error("[Proxy] Workspace logging failed:", e.message);
153
- // Continue even if workspace logging fails
154
- }
155
- }
156
- // Return success regardless (don't block API calls)
157
- return { valid: true, subagentId };
158
- }
159
- // OPTIONS handler for CORS
160
- http.route({
161
- path: "/api/discover",
162
- method: "OPTIONS",
163
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
164
- });
165
- http.route({
166
- path: "/api/details",
167
- method: "OPTIONS",
168
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
169
- });
170
- http.route({
171
- path: "/api/balance",
172
- method: "OPTIONS",
173
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
174
- });
175
- http.route({
176
- path: "/api/purchase",
177
- method: "OPTIONS",
178
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
179
- });
180
- http.route({
181
- path: "/admin/grant-credits",
182
- method: "OPTIONS",
183
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
184
- });
185
- // Discover APIs
186
- http.route({
187
- path: "/api/discover",
188
- method: "POST",
189
- handler: httpAction(async (ctx, request) => {
190
- try {
191
- const startTime = Date.now();
192
- const body = await request.json();
193
- const query = (body.query || "").toLowerCase();
194
- // Get optional auth context
195
- const sessionToken = request.headers.get("X-APIClaw-Session");
196
- const userAgent = request.headers.get("User-Agent");
197
- const results = Object.entries(PROVIDERS)
198
- .filter(([id, provider]) => {
199
- if (!query)
200
- return true;
201
- return (provider.name.toLowerCase().includes(query) ||
202
- provider.description.toLowerCase().includes(query) ||
203
- provider.category.toLowerCase().includes(query) ||
204
- provider.tags.some((tag) => tag.includes(query)));
205
- })
206
- .map(([id, provider]) => ({
207
- providerId: id,
208
- ...provider,
209
- }));
210
- const responseTimeMs = Date.now() - startTime;
211
- // Log the search (fire and forget)
212
- if (query) {
213
- ctx.runMutation(internal.searchLogs.logSearch, {
214
- query: body.query || "", // Original query (not lowercased)
215
- resultsCount: results.length,
216
- matchedProviders: results.map(r => r.providerId),
217
- sessionToken: sessionToken || undefined,
218
- userAgent: userAgent || undefined,
219
- responseTimeMs,
220
- }).catch(() => { }); // Ignore errors, don't block response
221
- }
222
- return jsonResponse({ providers: results, total: results.length });
223
- }
224
- catch (e) {
225
- return jsonResponse({ error: "Invalid request" }, 400);
226
- }
227
- }),
228
- });
229
- // Get provider details
230
- http.route({
231
- path: "/api/details",
232
- method: "POST",
233
- handler: httpAction(async (ctx, request) => {
234
- try {
235
- const body = await request.json();
236
- const { providerId } = body;
237
- if (!providerId) {
238
- return jsonResponse({ error: "providerId required" }, 400);
239
- }
240
- const provider = PROVIDERS[providerId];
241
- if (!provider) {
242
- return jsonResponse({ error: "Provider not found" }, 404);
243
- }
244
- return jsonResponse({
245
- providerId,
246
- ...provider,
247
- creditsPerDollar: getCreditsPerDollar(providerId),
248
- documentation: `https://apiclaw.com/docs/${providerId}`,
249
- });
250
- }
251
- catch (e) {
252
- return jsonResponse({ error: "Invalid request" }, 400);
253
- }
254
- }),
255
- });
256
- // Check balance
257
- http.route({
258
- path: "/api/balance",
259
- method: "GET",
260
- handler: httpAction(async (ctx, request) => {
261
- const url = new URL(request.url);
262
- const agentId = url.searchParams.get("agentId");
263
- if (!agentId) {
264
- return jsonResponse({ error: "agentId required" }, 400);
265
- }
266
- const credits = await ctx.runQuery(api.credits.getAgentCredits, { agentId });
267
- if (!credits) {
268
- return jsonResponse({
269
- agentId,
270
- balanceUsd: 0,
271
- currency: "USD",
272
- message: "No account found. Top up to get started!",
273
- });
274
- }
275
- return jsonResponse({
276
- agentId: credits.agentId,
277
- balanceUsd: credits.balanceUsd,
278
- currency: credits.currency,
279
- });
280
- }),
281
- });
282
- // Purchase API access
283
- http.route({
284
- path: "/api/purchase",
285
- method: "POST",
286
- handler: httpAction(async (ctx, request) => {
287
- try {
288
- const body = await request.json();
289
- const { agentId, providerId, amountUsd } = body;
290
- if (!agentId || !providerId || !amountUsd) {
291
- return jsonResponse({ error: "agentId, providerId, and amountUsd required" }, 400);
292
- }
293
- if (amountUsd < 1 || amountUsd > 1000) {
294
- return jsonResponse({ error: "amountUsd must be between 1 and 1000" }, 400);
295
- }
296
- const provider = PROVIDERS[providerId];
297
- if (!provider) {
298
- return jsonResponse({ error: "Provider not found" }, 404);
299
- }
300
- // Check balance first
301
- const credits = await ctx.runQuery(api.credits.getAgentCredits, { agentId });
302
- if (!credits || credits.balanceUsd < amountUsd) {
303
- return jsonResponse({
304
- error: "Insufficient balance",
305
- currentBalance: credits?.balanceUsd || 0,
306
- required: amountUsd,
307
- }, 402);
308
- }
309
- // Execute purchase
310
- const purchase = await ctx.runMutation(api.purchases.purchaseAccess, {
311
- agentId,
312
- providerId,
313
- amountUsd,
314
- credentials: generateCredentials(providerId),
315
- });
316
- if (!purchase) {
317
- return jsonResponse({ error: "Purchase failed" }, 500);
318
- }
319
- return jsonResponse({
320
- success: true,
321
- purchase: {
322
- id: purchase._id,
323
- providerId: purchase.providerId,
324
- amountUsd: purchase.amountUsd,
325
- creditsGranted: purchase.creditsGranted,
326
- status: purchase.status,
327
- },
328
- message: `Successfully purchased $${amountUsd} of ${provider.name} credits`,
329
- });
330
- }
331
- catch (e) {
332
- return jsonResponse({ error: e.message || "Purchase failed" }, 400);
333
- }
334
- }),
335
- });
336
- // Admin: Grant credits
337
- http.route({
338
- path: "/admin/grant-credits",
339
- method: "POST",
340
- handler: httpAction(async (ctx, request) => {
341
- try {
342
- const body = await request.json();
343
- const { agentId, amount, reason } = body;
344
- if (!agentId || !amount) {
345
- return jsonResponse({ error: "agentId and amount required" }, 400);
346
- }
347
- // TODO: Add admin auth check here
348
- // For now, allow grants (this is for Hivr integration)
349
- const result = await ctx.runMutation(api.credits.addCredits, {
350
- agentId,
351
- amountUsd: amount,
352
- source: reason || "admin_grant",
353
- });
354
- return jsonResponse({
355
- success: true,
356
- agentId,
357
- credited: amount,
358
- newBalance: result?.balanceUsd,
359
- reason,
360
- });
361
- }
362
- catch (e) {
363
- return jsonResponse({ error: e.message || "Grant failed" }, 400);
364
- }
365
- }),
366
- });
367
- // Helper functions
368
- function getCreditsPerDollar(providerId) {
369
- const rates = {
370
- "46elks": 30,
371
- twilio: 25,
372
- resend: 1000,
373
- brave_search: 200,
374
- openrouter: 100,
375
- elevenlabs: 3333,
376
- };
377
- return rates[providerId] || 100;
378
- }
379
- function generateCredentials(providerId) {
380
- // In production, this would generate or retrieve actual API keys
381
- // For now, return placeholder indicating how to use
382
- return {
383
- type: "apiclaw_proxy",
384
- endpoint: `https://brilliant-puffin-712.convex.site/proxy/${providerId}`,
385
- note: "Use APIClaw proxy endpoint. Credentials managed automatically.",
386
- };
387
- }
388
- export default http;
389
- // ==============================================
390
- // DIRECT CALL PROXY ENDPOINTS
391
- // ==============================================
392
- // OpenRouter proxy
393
- http.route({
394
- path: "/proxy/openrouter",
395
- method: "POST",
396
- handler: httpAction(async (ctx, request) => {
397
- // Validate session and log usage
398
- await validateAndLogProxyCall(ctx, request, "openrouter", "chat");
399
- const OPENROUTER_KEY = process.env.OPENROUTER_API_KEY;
400
- if (!OPENROUTER_KEY) {
401
- return jsonResponse({ error: "OpenRouter not configured" }, 500);
402
- }
403
- try {
404
- const body = await request.json();
405
- const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
406
- method: "POST",
407
- headers: {
408
- "Authorization": `Bearer ${OPENROUTER_KEY}`,
409
- "Content-Type": "application/json",
410
- "HTTP-Referer": "https://apiclaw.nordsym.com",
411
- "X-Title": "APIClaw",
412
- },
413
- body: JSON.stringify(body),
414
- });
415
- const data = await response.json();
416
- return jsonResponse(data, response.status);
417
- }
418
- catch (e) {
419
- return jsonResponse({ error: e.message }, 500);
420
- }
421
- }),
422
- });
423
- // Brave Search proxy
424
- http.route({
425
- path: "/proxy/brave_search",
426
- method: "POST",
427
- handler: httpAction(async (ctx, request) => {
428
- // Validate session and log usage
429
- await validateAndLogProxyCall(ctx, request, "brave_search", "search");
430
- const BRAVE_KEY = process.env.BRAVE_API_KEY;
431
- if (!BRAVE_KEY) {
432
- return jsonResponse({ error: "Brave Search not configured" }, 500);
433
- }
434
- try {
435
- const body = await request.json();
436
- const { query, count = 10 } = body;
437
- const url = new URL("https://api.search.brave.com/res/v1/web/search");
438
- url.searchParams.set("q", query);
439
- url.searchParams.set("count", String(count));
440
- const response = await fetch(url.toString(), {
441
- headers: { "X-Subscription-Token": BRAVE_KEY },
442
- });
443
- const data = await response.json();
444
- return jsonResponse(data, response.status);
445
- }
446
- catch (e) {
447
- return jsonResponse({ error: e.message }, 500);
448
- }
449
- }),
450
- });
451
- // Resend email proxy
452
- http.route({
453
- path: "/proxy/resend",
454
- method: "POST",
455
- handler: httpAction(async (ctx, request) => {
456
- // Validate session and log usage
457
- await validateAndLogProxyCall(ctx, request, "resend", "send_email");
458
- const RESEND_KEY = process.env.RESEND_API_KEY;
459
- if (!RESEND_KEY) {
460
- return jsonResponse({ error: "Resend not configured" }, 500);
461
- }
462
- try {
463
- const body = await request.json();
464
- const response = await fetch("https://api.resend.com/emails", {
465
- method: "POST",
466
- headers: {
467
- "Authorization": `Bearer ${RESEND_KEY}`,
468
- "Content-Type": "application/json",
469
- },
470
- body: JSON.stringify(body),
471
- });
472
- const data = await response.json();
473
- return jsonResponse(data, response.status);
474
- }
475
- catch (e) {
476
- return jsonResponse({ error: e.message }, 500);
477
- }
478
- }),
479
- });
480
- // ElevenLabs TTS proxy
481
- http.route({
482
- path: "/proxy/elevenlabs",
483
- method: "POST",
484
- handler: httpAction(async (ctx, request) => {
485
- // Validate session and log usage
486
- await validateAndLogProxyCall(ctx, request, "elevenlabs", "text_to_speech");
487
- const ELEVENLABS_KEY = process.env.ELEVENLABS_API_KEY;
488
- if (!ELEVENLABS_KEY) {
489
- return jsonResponse({ error: "ElevenLabs not configured" }, 500);
490
- }
491
- try {
492
- const body = await request.json();
493
- const { text, voice_id = "21m00Tcm4TlvDq8ikWAM" } = body;
494
- const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voice_id}`, {
495
- method: "POST",
496
- headers: {
497
- "xi-api-key": ELEVENLABS_KEY,
498
- "Content-Type": "application/json",
499
- },
500
- body: JSON.stringify({
501
- text,
502
- model_id: "eleven_turbo_v2",
503
- }),
504
- });
505
- if (!response.ok) {
506
- const error = await response.text();
507
- return jsonResponse({ error }, response.status);
508
- }
509
- // Return audio as base64
510
- const arrayBuffer = await response.arrayBuffer();
511
- const base64 = Buffer.from(arrayBuffer).toString("base64");
512
- return jsonResponse({
513
- audio_base64: base64,
514
- content_type: "audio/mpeg",
515
- });
516
- }
517
- catch (e) {
518
- return jsonResponse({ error: e.message }, 500);
519
- }
520
- }),
521
- });
522
- http.route({
523
- path: "/proxy/openrouter",
524
- method: "OPTIONS",
525
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
526
- });
527
- http.route({
528
- path: "/proxy/brave_search",
529
- method: "OPTIONS",
530
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
531
- });
532
- http.route({
533
- path: "/proxy/resend",
534
- method: "OPTIONS",
535
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
536
- });
537
- http.route({
538
- path: "/proxy/elevenlabs",
539
- method: "OPTIONS",
540
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
541
- });
542
- // 46elks SMS proxy
543
- http.route({
544
- path: "/proxy/46elks",
545
- method: "POST",
546
- handler: httpAction(async (ctx, request) => {
547
- // Validate session and log usage
548
- await validateAndLogProxyCall(ctx, request, "46elks", "send_sms");
549
- const ELKS_USER = process.env.ELKS_API_USER;
550
- const ELKS_PASS = process.env.ELKS_API_PASSWORD;
551
- if (!ELKS_USER || !ELKS_PASS) {
552
- return jsonResponse({ error: "46elks not configured" }, 500);
553
- }
554
- try {
555
- const body = await request.json();
556
- const { to, message, from = "APIClaw" } = body;
557
- const auth = btoa(`${ELKS_USER}:${ELKS_PASS}`);
558
- const response = await fetch("https://api.46elks.com/a1/sms", {
559
- method: "POST",
560
- headers: {
561
- "Authorization": `Basic ${auth}`,
562
- "Content-Type": "application/x-www-form-urlencoded",
563
- },
564
- body: new URLSearchParams({ from, to, message }),
565
- });
566
- const data = await response.json();
567
- return jsonResponse(data, response.status);
568
- }
569
- catch (e) {
570
- return jsonResponse({ error: e.message }, 500);
571
- }
572
- }),
573
- });
574
- // Twilio SMS proxy
575
- http.route({
576
- path: "/proxy/twilio",
577
- method: "POST",
578
- handler: httpAction(async (ctx, request) => {
579
- // Validate session and log usage
580
- await validateAndLogProxyCall(ctx, request, "twilio", "send_sms");
581
- const TWILIO_SID = process.env.TWILIO_ACCOUNT_SID;
582
- const TWILIO_TOKEN = process.env.TWILIO_AUTH_TOKEN;
583
- if (!TWILIO_SID || !TWILIO_TOKEN) {
584
- return jsonResponse({ error: "Twilio not configured" }, 500);
585
- }
586
- try {
587
- const body = await request.json();
588
- const { to, message, from } = body;
589
- if (!from) {
590
- return jsonResponse({ error: "Twilio requires 'from' number" }, 400);
591
- }
592
- const auth = btoa(`${TWILIO_SID}:${TWILIO_TOKEN}`);
593
- const response = await fetch(`https://api.twilio.com/2010-04-01/Accounts/${TWILIO_SID}/Messages.json`, {
594
- method: "POST",
595
- headers: {
596
- "Authorization": `Basic ${auth}`,
597
- "Content-Type": "application/x-www-form-urlencoded",
598
- },
599
- body: new URLSearchParams({ To: to, From: from, Body: message }),
600
- });
601
- const data = await response.json();
602
- return jsonResponse(data, response.status);
603
- }
604
- catch (e) {
605
- return jsonResponse({ error: e.message }, 500);
606
- }
607
- }),
608
- });
609
- // CORS for new endpoints
610
- http.route({
611
- path: "/proxy/46elks",
612
- method: "OPTIONS",
613
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
614
- });
615
- http.route({
616
- path: "/proxy/twilio",
617
- method: "OPTIONS",
618
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
619
- });
620
- // GitHub API proxy
621
- http.route({
622
- path: "/proxy/github",
623
- method: "POST",
624
- handler: httpAction(async (ctx, request) => {
625
- // Validate session and log usage
626
- const body = await request.json();
627
- const action = body.action || "search_repos";
628
- await validateAndLogProxyCall(ctx, request, "github", action);
629
- const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
630
- if (!GITHUB_TOKEN) {
631
- return jsonResponse({ error: "GitHub not configured" }, 500);
632
- }
633
- try {
634
- const { action, ...params } = body;
635
- let url;
636
- let method = "GET";
637
- let fetchBody;
638
- // Route based on action
639
- switch (action) {
640
- case "search_repos":
641
- const { query, sort = "stars", limit = 10 } = params;
642
- url = `https://api.github.com/search/repositories?q=${encodeURIComponent(query)}&sort=${sort}&per_page=${limit}`;
643
- break;
644
- case "get_repo":
645
- const { owner, repo } = params;
646
- url = `https://api.github.com/repos/${owner}/${repo}`;
647
- break;
648
- case "list_issues":
649
- const { owner: issueOwner, repo: issueRepo, state = "open", limit: issueLimit = 10 } = params;
650
- url = `https://api.github.com/repos/${issueOwner}/${issueRepo}/issues?state=${state}&per_page=${issueLimit}`;
651
- break;
652
- case "create_issue":
653
- const { owner: createOwner, repo: createRepo, title, body: issueBody = "" } = params;
654
- url = `https://api.github.com/repos/${createOwner}/${createRepo}/issues`;
655
- method = "POST";
656
- fetchBody = JSON.stringify({ title, body: issueBody });
657
- break;
658
- case "get_file":
659
- const { owner: fileOwner, repo: fileRepo, path } = params;
660
- url = `https://api.github.com/repos/${fileOwner}/${fileRepo}/contents/${path}`;
661
- break;
662
- default:
663
- return jsonResponse({ error: `Unknown action: ${action}` }, 400);
664
- }
665
- const response = await fetch(url, {
666
- method,
667
- headers: {
668
- "Authorization": `Bearer ${GITHUB_TOKEN}`,
669
- "Accept": "application/vnd.github+json",
670
- "User-Agent": "APIClaw",
671
- ...(fetchBody ? { "Content-Type": "application/json" } : {}),
672
- },
673
- ...(fetchBody ? { body: fetchBody } : {}),
674
- });
675
- const data = await response.json();
676
- return jsonResponse(data, response.status);
677
- }
678
- catch (e) {
679
- return jsonResponse({ error: e.message }, 500);
680
- }
681
- }),
682
- });
683
- http.route({
684
- path: "/proxy/github",
685
- method: "OPTIONS",
686
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
687
- });
688
- // ==============================================
689
- // SERPER (Google Search) PROXY
690
- // ==============================================
691
- http.route({
692
- path: "/proxy/serper",
693
- method: "POST",
694
- handler: httpAction(async (ctx, request) => {
695
- await validateAndLogProxyCall(ctx, request, "serper", "search");
696
- const SERPER_KEY = process.env.SERPER_API_KEY;
697
- if (!SERPER_KEY) {
698
- return jsonResponse({ error: "Serper not configured" }, 500);
699
- }
700
- try {
701
- const body = await request.json();
702
- const { query, q, num = 10, gl = "us", hl = "en" } = body;
703
- const searchQuery = query || q;
704
- if (!searchQuery) {
705
- return jsonResponse({ error: "query required" }, 400);
706
- }
707
- const response = await fetch("https://google.serper.dev/search", {
708
- method: "POST",
709
- headers: {
710
- "X-API-KEY": SERPER_KEY,
711
- "Content-Type": "application/json",
712
- },
713
- body: JSON.stringify({ q: searchQuery, num, gl, hl }),
714
- });
715
- const data = await response.json();
716
- return jsonResponse(data, response.status);
717
- }
718
- catch (e) {
719
- return jsonResponse({ error: e.message }, 500);
720
- }
721
- }),
722
- });
723
- http.route({
724
- path: "/proxy/serper",
725
- method: "OPTIONS",
726
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
727
- });
728
- // ==============================================
729
- // FIRECRAWL (Web Scraping) PROXY
730
- // ==============================================
731
- http.route({
732
- path: "/proxy/firecrawl",
733
- method: "POST",
734
- handler: httpAction(async (ctx, request) => {
735
- await validateAndLogProxyCall(ctx, request, "firecrawl", "scrape");
736
- const FIRECRAWL_KEY = process.env.FIRECRAWL_API_KEY;
737
- if (!FIRECRAWL_KEY) {
738
- return jsonResponse({ error: "Firecrawl not configured" }, 500);
739
- }
740
- try {
741
- const body = await request.json();
742
- const { url, formats = ["markdown"], onlyMainContent = true } = body;
743
- if (!url) {
744
- return jsonResponse({ error: "url required" }, 400);
745
- }
746
- const response = await fetch("https://api.firecrawl.dev/v1/scrape", {
747
- method: "POST",
748
- headers: {
749
- Authorization: `Bearer ${FIRECRAWL_KEY}`,
750
- "Content-Type": "application/json",
751
- },
752
- body: JSON.stringify({ url, formats, onlyMainContent }),
753
- });
754
- const data = await response.json();
755
- return jsonResponse(data, response.status);
756
- }
757
- catch (e) {
758
- return jsonResponse({ error: e.message }, 500);
759
- }
760
- }),
761
- });
762
- http.route({
763
- path: "/proxy/firecrawl",
764
- method: "OPTIONS",
765
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
766
- });
767
- // ==============================================
768
- // GROQ (LLM) PROXY
769
- // ==============================================
770
- http.route({
771
- path: "/proxy/groq",
772
- method: "POST",
773
- handler: httpAction(async (ctx, request) => {
774
- await validateAndLogProxyCall(ctx, request, "groq", "chat");
775
- const GROQ_KEY = process.env.GROQ_API_KEY;
776
- if (!GROQ_KEY) {
777
- return jsonResponse({ error: "Groq not configured" }, 500);
778
- }
779
- try {
780
- const body = await request.json();
781
- const { model = "llama-3.3-70b-versatile", messages, temperature = 0.7, max_tokens = 1024 } = body;
782
- if (!messages) {
783
- return jsonResponse({ error: "messages required" }, 400);
784
- }
785
- const response = await fetch("https://api.groq.com/openai/v1/chat/completions", {
786
- method: "POST",
787
- headers: {
788
- Authorization: `Bearer ${GROQ_KEY}`,
789
- "Content-Type": "application/json",
790
- },
791
- body: JSON.stringify({ model, messages, temperature, max_tokens }),
792
- });
793
- const data = await response.json();
794
- return jsonResponse(data, response.status);
795
- }
796
- catch (e) {
797
- return jsonResponse({ error: e.message }, 500);
798
- }
799
- }),
800
- });
801
- http.route({
802
- path: "/proxy/groq",
803
- method: "OPTIONS",
804
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
805
- });
806
- // ==============================================
807
- // MISTRAL (LLM/Embeddings) PROXY
808
- // ==============================================
809
- http.route({
810
- path: "/proxy/mistral",
811
- method: "POST",
812
- handler: httpAction(async (ctx, request) => {
813
- await validateAndLogProxyCall(ctx, request, "mistral", "chat");
814
- const MISTRAL_KEY = process.env.MISTRAL_API_KEY;
815
- if (!MISTRAL_KEY) {
816
- return jsonResponse({ error: "Mistral not configured" }, 500);
817
- }
818
- try {
819
- const body = await request.json();
820
- const { model = "mistral-small-latest", messages, temperature = 0.7, max_tokens = 1024 } = body;
821
- if (!messages) {
822
- return jsonResponse({ error: "messages required" }, 400);
823
- }
824
- const response = await fetch("https://api.mistral.ai/v1/chat/completions", {
825
- method: "POST",
826
- headers: {
827
- Authorization: `Bearer ${MISTRAL_KEY}`,
828
- "Content-Type": "application/json",
829
- },
830
- body: JSON.stringify({ model, messages, temperature, max_tokens }),
831
- });
832
- const data = await response.json();
833
- return jsonResponse(data, response.status);
834
- }
835
- catch (e) {
836
- return jsonResponse({ error: e.message }, 500);
837
- }
838
- }),
839
- });
840
- http.route({
841
- path: "/proxy/mistral",
842
- method: "OPTIONS",
843
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
844
- });
845
- // ==============================================
846
- // COHERE (LLM/Rerank) PROXY
847
- // ==============================================
848
- http.route({
849
- path: "/proxy/cohere",
850
- method: "POST",
851
- handler: httpAction(async (ctx, request) => {
852
- await validateAndLogProxyCall(ctx, request, "cohere", "chat");
853
- const COHERE_KEY = process.env.COHERE_API_KEY;
854
- if (!COHERE_KEY) {
855
- return jsonResponse({ error: "Cohere not configured" }, 500);
856
- }
857
- try {
858
- const body = await request.json();
859
- const { model = "command-a-03-2025", message, chat_history, temperature = 0.7, max_tokens = 1024 } = body;
860
- if (!message) {
861
- return jsonResponse({ error: "message required" }, 400);
862
- }
863
- const response = await fetch("https://api.cohere.com/v2/chat", {
864
- method: "POST",
865
- headers: {
866
- Authorization: `Bearer ${COHERE_KEY}`,
867
- "Content-Type": "application/json",
868
- },
869
- body: JSON.stringify({ model, message, chat_history, temperature, max_tokens }),
870
- });
871
- const data = await response.json();
872
- return jsonResponse(data, response.status);
873
- }
874
- catch (e) {
875
- return jsonResponse({ error: e.message }, 500);
876
- }
877
- }),
878
- });
879
- http.route({
880
- path: "/proxy/cohere",
881
- method: "OPTIONS",
882
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
883
- });
884
- // ==============================================
885
- // REPLICATE (ML Models) PROXY
886
- // ==============================================
887
- http.route({
888
- path: "/proxy/replicate",
889
- method: "POST",
890
- handler: httpAction(async (ctx, request) => {
891
- await validateAndLogProxyCall(ctx, request, "replicate", "prediction");
892
- const REPLICATE_KEY = process.env.REPLICATE_API_TOKEN;
893
- if (!REPLICATE_KEY) {
894
- return jsonResponse({ error: "Replicate not configured" }, 500);
895
- }
896
- try {
897
- const body = await request.json();
898
- const { model, input, version } = body;
899
- if (!model && !version) {
900
- return jsonResponse({ error: "model or version required" }, 400);
901
- }
902
- const endpoint = version
903
- ? "https://api.replicate.com/v1/predictions"
904
- : `https://api.replicate.com/v1/models/${model}/predictions`;
905
- const payload = version ? { version, input } : { input };
906
- const response = await fetch(endpoint, {
907
- method: "POST",
908
- headers: {
909
- Authorization: `Bearer ${REPLICATE_KEY}`,
910
- "Content-Type": "application/json",
911
- Prefer: "wait",
912
- },
913
- body: JSON.stringify(payload),
914
- });
915
- const data = await response.json();
916
- return jsonResponse(data, response.status);
917
- }
918
- catch (e) {
919
- return jsonResponse({ error: e.message }, 500);
920
- }
921
- }),
922
- });
923
- http.route({
924
- path: "/proxy/replicate",
925
- method: "OPTIONS",
926
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
927
- });
928
- // ==============================================
929
- // DEEPGRAM (Speech-to-Text) PROXY
930
- // ==============================================
931
- http.route({
932
- path: "/proxy/deepgram",
933
- method: "POST",
934
- handler: httpAction(async (ctx, request) => {
935
- await validateAndLogProxyCall(ctx, request, "deepgram", "transcribe");
936
- const DEEPGRAM_KEY = process.env.DEEPGRAM_API_KEY;
937
- if (!DEEPGRAM_KEY) {
938
- return jsonResponse({ error: "Deepgram not configured" }, 500);
939
- }
940
- try {
941
- const body = await request.json();
942
- const { url, model = "nova-3", language = "en", smart_format = true } = body;
943
- if (!url) {
944
- return jsonResponse({ error: "url required (audio file URL)" }, 400);
945
- }
946
- const params = new URLSearchParams({
947
- model,
948
- language,
949
- smart_format: String(smart_format),
950
- });
951
- const response = await fetch(`https://api.deepgram.com/v1/listen?${params}`, {
952
- method: "POST",
953
- headers: {
954
- Authorization: `Token ${DEEPGRAM_KEY}`,
955
- "Content-Type": "application/json",
956
- },
957
- body: JSON.stringify({ url }),
958
- });
959
- const data = await response.json();
960
- return jsonResponse(data, response.status);
961
- }
962
- catch (e) {
963
- return jsonResponse({ error: e.message }, 500);
964
- }
965
- }),
966
- });
967
- http.route({
968
- path: "/proxy/deepgram",
969
- method: "OPTIONS",
970
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
971
- });
972
- // ==============================================
973
- // E2B (Code Sandbox) PROXY
974
- // ==============================================
975
- http.route({
976
- path: "/proxy/e2b",
977
- method: "POST",
978
- handler: httpAction(async (ctx, request) => {
979
- await validateAndLogProxyCall(ctx, request, "e2b", "execute");
980
- const E2B_KEY = process.env.E2B_API_KEY;
981
- if (!E2B_KEY) {
982
- return jsonResponse({ error: "E2B not configured" }, 500);
983
- }
984
- try {
985
- const body = await request.json();
986
- const { code, language = "python", template = "base" } = body;
987
- if (!code) {
988
- return jsonResponse({ error: "code required" }, 400);
989
- }
990
- const response = await fetch("https://api.e2b.dev/sandboxes", {
991
- method: "POST",
992
- headers: {
993
- "X-API-Key": E2B_KEY,
994
- "Content-Type": "application/json",
995
- },
996
- body: JSON.stringify({ templateID: template, metadata: { language } }),
997
- });
998
- const sandbox = await response.json();
999
- if (!response.ok) {
1000
- return jsonResponse(sandbox, response.status);
1001
- }
1002
- const execResponse = await fetch(`https://api.e2b.dev/sandboxes/${sandbox.sandboxID}/code/execution`, {
1003
- method: "POST",
1004
- headers: {
1005
- "X-API-Key": E2B_KEY,
1006
- "Content-Type": "application/json",
1007
- },
1008
- body: JSON.stringify({ code, language }),
1009
- });
1010
- const result = await execResponse.json();
1011
- return jsonResponse(result, execResponse.status);
1012
- }
1013
- catch (e) {
1014
- return jsonResponse({ error: e.message }, 500);
1015
- }
1016
- }),
1017
- });
1018
- http.route({
1019
- path: "/proxy/e2b",
1020
- method: "OPTIONS",
1021
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1022
- });
1023
- // ==============================================
1024
- // TOGETHER AI (Open-source LLM Inference) PROXY
1025
- // ==============================================
1026
- http.route({
1027
- path: "/proxy/together",
1028
- method: "POST",
1029
- handler: httpAction(async (ctx, request) => {
1030
- await validateAndLogProxyCall(ctx, request, "together", "chat");
1031
- const TOGETHER_KEY = process.env.TOGETHER_API_KEY;
1032
- if (!TOGETHER_KEY) {
1033
- return jsonResponse({ error: "Together AI not configured" }, 500);
1034
- }
1035
- try {
1036
- const body = await request.json();
1037
- const { model = "meta-llama/Llama-3.3-70B-Instruct-Turbo", messages, temperature = 0.7, max_tokens = 1024 } = body;
1038
- if (!messages || !Array.isArray(messages)) {
1039
- return jsonResponse({ error: "messages array required" }, 400);
1040
- }
1041
- const response = await fetch("https://api.together.xyz/v1/chat/completions", {
1042
- method: "POST",
1043
- headers: {
1044
- Authorization: `Bearer ${TOGETHER_KEY}`,
1045
- "Content-Type": "application/json",
1046
- },
1047
- body: JSON.stringify({ model, messages, temperature, max_tokens }),
1048
- });
1049
- const data = await response.json();
1050
- return jsonResponse(data, response.status);
1051
- }
1052
- catch (e) {
1053
- return jsonResponse({ error: e.message }, 500);
1054
- }
1055
- }),
1056
- });
1057
- http.route({
1058
- path: "/proxy/together",
1059
- method: "OPTIONS",
1060
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1061
- });
1062
- // ==============================================
1063
- // STABILITY AI (Image Generation) PROXY
1064
- // ==============================================
1065
- http.route({
1066
- path: "/proxy/stability",
1067
- method: "POST",
1068
- handler: httpAction(async (ctx, request) => {
1069
- await validateAndLogProxyCall(ctx, request, "stability", "generate");
1070
- const STABILITY_KEY = process.env.STABILITY_API_KEY;
1071
- if (!STABILITY_KEY) {
1072
- return jsonResponse({ error: "Stability AI not configured" }, 500);
1073
- }
1074
- try {
1075
- const body = await request.json();
1076
- const { prompt, model = "sd3.5-large", output_format = "png", aspect_ratio = "1:1" } = body;
1077
- if (!prompt) {
1078
- return jsonResponse({ error: "prompt required" }, 400);
1079
- }
1080
- const formData = new FormData();
1081
- formData.append("prompt", prompt);
1082
- formData.append("output_format", output_format);
1083
- formData.append("aspect_ratio", aspect_ratio);
1084
- const response = await fetch(`https://api.stability.ai/v2beta/stable-image/generate/${model}`, {
1085
- method: "POST",
1086
- headers: {
1087
- Authorization: `Bearer ${STABILITY_KEY}`,
1088
- Accept: "application/json",
1089
- },
1090
- body: formData,
1091
- });
1092
- const data = await response.json();
1093
- return jsonResponse(data, response.status);
1094
- }
1095
- catch (e) {
1096
- return jsonResponse({ error: e.message }, 500);
1097
- }
1098
- }),
1099
- });
1100
- http.route({
1101
- path: "/proxy/stability",
1102
- method: "OPTIONS",
1103
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1104
- });
1105
- // ==============================================
1106
- // ASSEMBLYAI (Audio Intelligence) PROXY
1107
- // ==============================================
1108
- http.route({
1109
- path: "/proxy/assemblyai",
1110
- method: "POST",
1111
- handler: httpAction(async (ctx, request) => {
1112
- await validateAndLogProxyCall(ctx, request, "assemblyai", "transcribe");
1113
- const ASSEMBLYAI_KEY = process.env.ASSEMBLYAI_API_KEY;
1114
- if (!ASSEMBLYAI_KEY) {
1115
- return jsonResponse({ error: "AssemblyAI not configured" }, 500);
1116
- }
1117
- try {
1118
- const body = await request.json();
1119
- const { audio_url, language_detection = true, speaker_labels = true } = body;
1120
- if (!audio_url) {
1121
- return jsonResponse({ error: "audio_url required" }, 400);
1122
- }
1123
- const response = await fetch("https://api.assemblyai.com/v2/transcript", {
1124
- method: "POST",
1125
- headers: {
1126
- Authorization: ASSEMBLYAI_KEY,
1127
- "Content-Type": "application/json",
1128
- },
1129
- body: JSON.stringify({ audio_url, language_detection, speaker_labels }),
1130
- });
1131
- const data = await response.json();
1132
- return jsonResponse(data, response.status);
1133
- }
1134
- catch (e) {
1135
- return jsonResponse({ error: e.message }, 500);
1136
- }
1137
- }),
1138
- });
1139
- http.route({
1140
- path: "/proxy/assemblyai",
1141
- method: "OPTIONS",
1142
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1143
- });
1144
- // ==============================================
1145
- // APILAYER (Multi-API: Exchange, Stocks, Aviation, etc.) PROXY
1146
- // ==============================================
1147
- http.route({
1148
- path: "/proxy/apilayer",
1149
- method: "POST",
1150
- handler: httpAction(async (ctx, request) => {
1151
- await validateAndLogProxyCall(ctx, request, "apilayer", "call");
1152
- const APILAYER_KEY = process.env.APILAYER_API_KEY;
1153
- if (!APILAYER_KEY) {
1154
- return jsonResponse({ error: "APILayer not configured" }, 500);
1155
- }
1156
- try {
1157
- const body = await request.json();
1158
- const { service, endpoint, params = {} } = body;
1159
- if (!service || !endpoint) {
1160
- return jsonResponse({ error: "service and endpoint required (e.g. service:'exchangerates', endpoint:'/latest')" }, 400);
1161
- }
1162
- const queryString = new URLSearchParams(params).toString();
1163
- const url = `https://api.apilayer.com/${service}${endpoint}${queryString ? '?' + queryString : ''}`;
1164
- const response = await fetch(url, {
1165
- method: "GET",
1166
- headers: {
1167
- apikey: APILAYER_KEY,
1168
- },
1169
- });
1170
- const data = await response.json();
1171
- return jsonResponse(data, response.status);
1172
- }
1173
- catch (e) {
1174
- return jsonResponse({ error: e.message }, 500);
1175
- }
1176
- }),
1177
- });
1178
- http.route({
1179
- path: "/proxy/apilayer",
1180
- method: "OPTIONS",
1181
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1182
- });
1183
- // ==============================================
1184
- // WORKSPACE / MAGIC LINK ENDPOINTS
1185
- // ==============================================
1186
- // Create magic link and send email
1187
- http.route({
1188
- path: "/workspace/magic-link",
1189
- method: "POST",
1190
- handler: httpAction(async (ctx, request) => {
1191
- try {
1192
- const body = await request.json();
1193
- const { email, fingerprint } = body;
1194
- if (!email || !email.includes("@")) {
1195
- return jsonResponse({ error: "Valid email required" }, 400);
1196
- }
1197
- // Create magic link
1198
- const result = await ctx.runMutation(api.workspaces.createMagicLink, {
1199
- email: email.toLowerCase(),
1200
- fingerprint,
1201
- });
1202
- // Send email directly - SIMPLE HTML (complex tables get stripped by Gmail)
1203
- const verifyUrl = `https://apiclaw.nordsym.com/auth/verify?token=${result.token}`;
1204
- const html = `<div style="font-family:Arial,sans-serif;max-width:500px;margin:0 auto;padding:20px;">
1205
- <h1>🦞 APIClaw</h1>
1206
- <h2>An AI Agent Wants to Connect</h2>
1207
- <p>Click below to verify your email and activate your workspace.</p>
1208
- <p><a href="${verifyUrl}" style="background:#ef4444;color:white;padding:14px 32px;border-radius:8px;text-decoration:none;display:inline-block;">Verify Email</a></p>
1209
- <p style="color:#666;font-size:13px;">Free tier: 50 API calls. This link expires in 1 hour.</p>
1210
- <p style="color:#999;font-size:11px;">Or copy this link: ${verifyUrl}</p>
1211
- </div>`;
1212
- const RESEND_KEY = process.env.RESEND_API_KEY;
1213
- if (!RESEND_KEY) {
1214
- console.error("RESEND_API_KEY not configured");
1215
- return jsonResponse({ error: "Email service not configured" }, 500);
1216
- }
1217
- const emailResponse = await fetch("https://api.resend.com/emails", {
1218
- method: "POST",
1219
- headers: {
1220
- "Authorization": `Bearer ${RESEND_KEY}`,
1221
- "Content-Type": "application/json",
1222
- },
1223
- body: JSON.stringify({
1224
- from: "APIClaw <noreply@apiclaw.nordsym.com>",
1225
- to: email.toLowerCase(),
1226
- subject: "🦞 Verify Your Email — APIClaw",
1227
- html: html,
1228
- }),
1229
- });
1230
- if (!emailResponse.ok) {
1231
- const errorText = await emailResponse.text();
1232
- console.error("Resend error:", emailResponse.status, errorText);
1233
- return jsonResponse({ error: "Failed to send email", details: errorText }, 500);
1234
- }
1235
- const emailResult = await emailResponse.json();
1236
- console.log("Email sent successfully:", emailResult.id);
1237
- return jsonResponse({
1238
- success: true,
1239
- token: result.token,
1240
- expiresAt: result.expiresAt,
1241
- message: "Magic link sent! Check your email.",
1242
- emailId: emailResult.id,
1243
- });
1244
- }
1245
- catch (e) {
1246
- console.error("Magic link error:", e);
1247
- return jsonResponse({ error: e.message || "Failed to create magic link" }, 500);
1248
- }
1249
- }),
1250
- });
1251
- http.route({
1252
- path: "/workspace/magic-link",
1253
- method: "OPTIONS",
1254
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1255
- });
1256
- // Poll magic link status (for agents to check if user clicked)
1257
- http.route({
1258
- path: "/workspace/poll",
1259
- method: "GET",
1260
- handler: httpAction(async (ctx, request) => {
1261
- const url = new URL(request.url);
1262
- const token = url.searchParams.get("token");
1263
- if (!token) {
1264
- return jsonResponse({ error: "token required" }, 400);
1265
- }
1266
- const result = await ctx.runQuery(api.workspaces.pollMagicLink, { token });
1267
- return jsonResponse(result);
1268
- }),
1269
- });
1270
- http.route({
1271
- path: "/workspace/poll",
1272
- method: "OPTIONS",
1273
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1274
- });
1275
- // Verify session token
1276
- http.route({
1277
- path: "/workspace/verify-session",
1278
- method: "GET",
1279
- handler: httpAction(async (ctx, request) => {
1280
- const url = new URL(request.url);
1281
- const sessionToken = url.searchParams.get("sessionToken");
1282
- if (!sessionToken) {
1283
- return jsonResponse({ error: "sessionToken required" }, 400);
1284
- }
1285
- const result = await ctx.runQuery(api.workspaces.verifySession, { sessionToken });
1286
- if (!result) {
1287
- return jsonResponse({ error: "Invalid or expired session" }, 401);
1288
- }
1289
- return jsonResponse(result);
1290
- }),
1291
- });
1292
- http.route({
1293
- path: "/workspace/verify-session",
1294
- method: "OPTIONS",
1295
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1296
- });
1297
- // Get workspace by email
1298
- http.route({
1299
- path: "/workspace/by-email",
1300
- method: "GET",
1301
- handler: httpAction(async (ctx, request) => {
1302
- const url = new URL(request.url);
1303
- const email = url.searchParams.get("email");
1304
- if (!email) {
1305
- return jsonResponse({ error: "email required" }, 400);
1306
- }
1307
- const result = await ctx.runQuery(api.workspaces.getByEmail, { email });
1308
- if (!result) {
1309
- return jsonResponse({ exists: false });
1310
- }
1311
- return jsonResponse({ exists: true, workspace: result });
1312
- }),
1313
- });
1314
- http.route({
1315
- path: "/workspace/by-email",
1316
- method: "OPTIONS",
1317
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1318
- });
1319
- // Send reminder email
1320
- http.route({
1321
- path: "/workspace/send-reminder",
1322
- method: "POST",
1323
- handler: httpAction(async (ctx, request) => {
1324
- try {
1325
- const body = await request.json();
1326
- const { email, token } = body;
1327
- if (!email || !token) {
1328
- return jsonResponse({ error: "email and token required" }, 400);
1329
- }
1330
- await ctx.runAction(api.email.sendReminderEmail, { email, token });
1331
- return jsonResponse({ success: true });
1332
- }
1333
- catch (e) {
1334
- return jsonResponse({ error: e.message }, 500);
1335
- }
1336
- }),
1337
- });
1338
- http.route({
1339
- path: "/workspace/send-reminder",
1340
- method: "OPTIONS",
1341
- handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1342
- });
1343
- // ==============================================
1344
- // STRIPE BILLING ENDPOINTS
1345
- // ==============================================
1346
- // Create checkout session
1347
- http.route({
1348
- path: "/api/billing/checkout",
1349
- method: "POST",
1350
- handler: createCheckoutSession,
1351
- });
1352
- http.route({
1353
- path: "/api/billing/checkout",
1354
- method: "OPTIONS",
1355
- handler: checkoutOptions,
1356
- });
1357
- // Create billing portal session
1358
- http.route({
1359
- path: "/api/billing/portal",
1360
- method: "POST",
1361
- handler: createPortalSession,
1362
- });
1363
- http.route({
1364
- path: "/api/billing/portal",
1365
- method: "OPTIONS",
1366
- handler: portalOptions,
1367
- });
1368
- // Stripe webhook handler
1369
- http.route({
1370
- path: "/api/webhooks/stripe",
1371
- method: "POST",
1372
- handler: handleStripeWebhook,
1373
- });
1374
- http.route({
1375
- path: "/api/webhooks/stripe",
1376
- method: "OPTIONS",
1377
- handler: webhookOptions,
1378
- });
1379
- // Test endpoint to debug logging
1380
- http.route({
1381
- path: "/proxy/test-logging",
1382
- method: "POST",
1383
- handler: httpAction(async (ctx, request) => {
1384
- const identifier = request.headers.get("X-APIClaw-Identifier");
1385
- try {
1386
- const logId = await ctx.runMutation(api.analytics.log, {
1387
- event: "test_endpoint",
1388
- provider: "test",
1389
- identifier: identifier || "test",
1390
- metadata: { test: true },
1391
- });
1392
- return jsonResponse({
1393
- success: true,
1394
- identifier,
1395
- logId,
1396
- message: "Logged successfully"
1397
- });
1398
- }
1399
- catch (e) {
1400
- return jsonResponse({
1401
- success: false,
1402
- error: e.message,
1403
- stack: e.stack
1404
- }, 500);
1405
- }
1406
- }),
1407
- });
1408
- //# sourceMappingURL=http.js.map