@nordsym/apiclaw 1.5.13 → 1.5.15

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 (70) hide show
  1. package/dist/bin.js +1 -1
  2. package/dist/cli/commands/mcp-install.js +44 -49
  3. package/dist/cli/commands/mcp-install.js.map +1 -1
  4. package/dist/cli/index.js +7 -0
  5. package/dist/convex/adminActivate.js +46 -0
  6. package/dist/convex/adminStats.js +41 -0
  7. package/dist/convex/agents.js +498 -0
  8. package/dist/convex/analytics.js +165 -0
  9. package/dist/convex/billing.js +654 -0
  10. package/dist/convex/capabilities.js +144 -0
  11. package/dist/convex/chains.js +1041 -0
  12. package/dist/convex/credits.js +185 -0
  13. package/dist/convex/crons.js +16 -0
  14. package/dist/convex/directCall.js +626 -0
  15. package/dist/convex/earnProgress.js +648 -0
  16. package/dist/convex/email.js +299 -0
  17. package/dist/convex/feedback.js +226 -0
  18. package/dist/convex/http.js +909 -0
  19. package/dist/convex/logs.js +486 -0
  20. package/dist/convex/mou.js +81 -0
  21. package/dist/convex/providerKeys.js +256 -0
  22. package/dist/convex/providers.js +755 -0
  23. package/dist/convex/purchases.js +156 -0
  24. package/dist/convex/ratelimit.js +90 -0
  25. package/dist/convex/schema.js +709 -0
  26. package/dist/convex/searchLogs.js +128 -0
  27. package/dist/convex/spendAlerts.js +379 -0
  28. package/dist/convex/stripeActions.js +410 -0
  29. package/dist/convex/teams.js +214 -0
  30. package/dist/convex/telemetry.js +73 -0
  31. package/dist/convex/usage.js +228 -0
  32. package/dist/convex/waitlist.js +48 -0
  33. package/dist/convex/webhooks.js +409 -0
  34. package/dist/convex/workspaces.js +879 -0
  35. package/dist/src/analytics.js +129 -0
  36. package/dist/src/bin.js +17 -0
  37. package/dist/src/capability-router.js +240 -0
  38. package/dist/src/chainExecutor.js +451 -0
  39. package/dist/src/chainResolver.js +518 -0
  40. package/dist/src/cli/commands/doctor.js +324 -0
  41. package/dist/src/cli/commands/mcp-install.js +255 -0
  42. package/dist/src/cli/commands/restore.js +259 -0
  43. package/dist/src/cli/commands/setup.js +205 -0
  44. package/dist/src/cli/commands/uninstall.js +188 -0
  45. package/dist/src/cli/index.js +111 -0
  46. package/dist/src/cli.js +302 -0
  47. package/dist/src/confirmation.js +240 -0
  48. package/dist/src/credentials.js +357 -0
  49. package/dist/src/credits.js +260 -0
  50. package/dist/src/crypto.js +66 -0
  51. package/dist/src/discovery.js +504 -0
  52. package/dist/src/enterprise/env.js +123 -0
  53. package/dist/src/enterprise/script-generator.js +460 -0
  54. package/dist/src/execute-dynamic.js +473 -0
  55. package/dist/src/execute.js +1727 -0
  56. package/dist/src/index.js +2062 -0
  57. package/dist/src/metered.js +80 -0
  58. package/dist/src/open-apis.js +276 -0
  59. package/dist/src/proxy.js +28 -0
  60. package/dist/src/session.js +86 -0
  61. package/dist/src/stripe.js +407 -0
  62. package/dist/src/telemetry.js +49 -0
  63. package/dist/src/types.js +2 -0
  64. package/dist/src/utils/backup.js +181 -0
  65. package/dist/src/utils/config.js +220 -0
  66. package/dist/src/utils/os.js +105 -0
  67. package/dist/src/utils/paths.js +159 -0
  68. package/package.json +1 -1
  69. package/src/bin.ts +1 -1
  70. package/src/cli/index.ts +8 -0
@@ -0,0 +1,909 @@
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
+ // ALWAYS log to analytics (even if identifier is missing)
116
+ try {
117
+ const result = await ctx.runMutation(api.analytics.log, {
118
+ event: "api_call",
119
+ provider,
120
+ identifier: identifier || "unknown",
121
+ metadata: { action, subagentId },
122
+ });
123
+ console.log("[Proxy] Analytics logged:", result);
124
+ }
125
+ catch (e) {
126
+ console.error("[Proxy] Analytics logging failed:", e.message, e.stack);
127
+ // Continue even if analytics fails
128
+ }
129
+ // If we have an identifier and it's a workspace ID (not anon:), log to workspace
130
+ if (identifier && !identifier.startsWith("anon:") && identifier !== "unknown") {
131
+ try {
132
+ // Validate it's actually a workspace ID by checking format
133
+ if (identifier.length > 20) {
134
+ await ctx.runMutation(api.logs.createProxyLog, {
135
+ workspaceId: identifier,
136
+ provider,
137
+ action,
138
+ subagentId,
139
+ });
140
+ // Increment workspace usage
141
+ await ctx.runMutation(api.workspaces.incrementUsage, {
142
+ workspaceId: identifier,
143
+ });
144
+ console.log("[Proxy] Workspace logged for:", identifier);
145
+ return { valid: true, workspaceId: identifier, subagentId };
146
+ }
147
+ }
148
+ catch (e) {
149
+ console.error("[Proxy] Workspace logging failed:", e.message);
150
+ // Continue even if workspace logging fails
151
+ }
152
+ }
153
+ // Return success regardless (don't block API calls)
154
+ return { valid: true, subagentId };
155
+ }
156
+ // OPTIONS handler for CORS
157
+ http.route({
158
+ path: "/api/discover",
159
+ method: "OPTIONS",
160
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
161
+ });
162
+ http.route({
163
+ path: "/api/details",
164
+ method: "OPTIONS",
165
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
166
+ });
167
+ http.route({
168
+ path: "/api/balance",
169
+ method: "OPTIONS",
170
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
171
+ });
172
+ http.route({
173
+ path: "/api/purchase",
174
+ method: "OPTIONS",
175
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
176
+ });
177
+ http.route({
178
+ path: "/admin/grant-credits",
179
+ method: "OPTIONS",
180
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
181
+ });
182
+ // Discover APIs
183
+ http.route({
184
+ path: "/api/discover",
185
+ method: "POST",
186
+ handler: httpAction(async (ctx, request) => {
187
+ try {
188
+ const startTime = Date.now();
189
+ const body = await request.json();
190
+ const query = (body.query || "").toLowerCase();
191
+ // Get optional auth context
192
+ const sessionToken = request.headers.get("X-APIClaw-Session");
193
+ const userAgent = request.headers.get("User-Agent");
194
+ const results = Object.entries(PROVIDERS)
195
+ .filter(([id, provider]) => {
196
+ if (!query)
197
+ return true;
198
+ return (provider.name.toLowerCase().includes(query) ||
199
+ provider.description.toLowerCase().includes(query) ||
200
+ provider.category.toLowerCase().includes(query) ||
201
+ provider.tags.some((tag) => tag.includes(query)));
202
+ })
203
+ .map(([id, provider]) => ({
204
+ providerId: id,
205
+ ...provider,
206
+ }));
207
+ const responseTimeMs = Date.now() - startTime;
208
+ // Log the search (fire and forget)
209
+ if (query) {
210
+ ctx.runMutation(internal.searchLogs.logSearch, {
211
+ query: body.query || "", // Original query (not lowercased)
212
+ resultsCount: results.length,
213
+ matchedProviders: results.map(r => r.providerId),
214
+ sessionToken: sessionToken || undefined,
215
+ userAgent: userAgent || undefined,
216
+ responseTimeMs,
217
+ }).catch(() => { }); // Ignore errors, don't block response
218
+ }
219
+ return jsonResponse({ providers: results, total: results.length });
220
+ }
221
+ catch (e) {
222
+ return jsonResponse({ error: "Invalid request" }, 400);
223
+ }
224
+ }),
225
+ });
226
+ // Get provider details
227
+ http.route({
228
+ path: "/api/details",
229
+ method: "POST",
230
+ handler: httpAction(async (ctx, request) => {
231
+ try {
232
+ const body = await request.json();
233
+ const { providerId } = body;
234
+ if (!providerId) {
235
+ return jsonResponse({ error: "providerId required" }, 400);
236
+ }
237
+ const provider = PROVIDERS[providerId];
238
+ if (!provider) {
239
+ return jsonResponse({ error: "Provider not found" }, 404);
240
+ }
241
+ return jsonResponse({
242
+ providerId,
243
+ ...provider,
244
+ creditsPerDollar: getCreditsPerDollar(providerId),
245
+ documentation: `https://apiclaw.com/docs/${providerId}`,
246
+ });
247
+ }
248
+ catch (e) {
249
+ return jsonResponse({ error: "Invalid request" }, 400);
250
+ }
251
+ }),
252
+ });
253
+ // Check balance
254
+ http.route({
255
+ path: "/api/balance",
256
+ method: "GET",
257
+ handler: httpAction(async (ctx, request) => {
258
+ const url = new URL(request.url);
259
+ const agentId = url.searchParams.get("agentId");
260
+ if (!agentId) {
261
+ return jsonResponse({ error: "agentId required" }, 400);
262
+ }
263
+ const credits = await ctx.runQuery(api.credits.getAgentCredits, { agentId });
264
+ if (!credits) {
265
+ return jsonResponse({
266
+ agentId,
267
+ balanceUsd: 0,
268
+ currency: "USD",
269
+ message: "No account found. Top up to get started!",
270
+ });
271
+ }
272
+ return jsonResponse({
273
+ agentId: credits.agentId,
274
+ balanceUsd: credits.balanceUsd,
275
+ currency: credits.currency,
276
+ });
277
+ }),
278
+ });
279
+ // Purchase API access
280
+ http.route({
281
+ path: "/api/purchase",
282
+ method: "POST",
283
+ handler: httpAction(async (ctx, request) => {
284
+ try {
285
+ const body = await request.json();
286
+ const { agentId, providerId, amountUsd } = body;
287
+ if (!agentId || !providerId || !amountUsd) {
288
+ return jsonResponse({ error: "agentId, providerId, and amountUsd required" }, 400);
289
+ }
290
+ if (amountUsd < 1 || amountUsd > 1000) {
291
+ return jsonResponse({ error: "amountUsd must be between 1 and 1000" }, 400);
292
+ }
293
+ const provider = PROVIDERS[providerId];
294
+ if (!provider) {
295
+ return jsonResponse({ error: "Provider not found" }, 404);
296
+ }
297
+ // Check balance first
298
+ const credits = await ctx.runQuery(api.credits.getAgentCredits, { agentId });
299
+ if (!credits || credits.balanceUsd < amountUsd) {
300
+ return jsonResponse({
301
+ error: "Insufficient balance",
302
+ currentBalance: credits?.balanceUsd || 0,
303
+ required: amountUsd,
304
+ }, 402);
305
+ }
306
+ // Execute purchase
307
+ const purchase = await ctx.runMutation(api.purchases.purchaseAccess, {
308
+ agentId,
309
+ providerId,
310
+ amountUsd,
311
+ credentials: generateCredentials(providerId),
312
+ });
313
+ if (!purchase) {
314
+ return jsonResponse({ error: "Purchase failed" }, 500);
315
+ }
316
+ return jsonResponse({
317
+ success: true,
318
+ purchase: {
319
+ id: purchase._id,
320
+ providerId: purchase.providerId,
321
+ amountUsd: purchase.amountUsd,
322
+ creditsGranted: purchase.creditsGranted,
323
+ status: purchase.status,
324
+ },
325
+ message: `Successfully purchased $${amountUsd} of ${provider.name} credits`,
326
+ });
327
+ }
328
+ catch (e) {
329
+ return jsonResponse({ error: e.message || "Purchase failed" }, 400);
330
+ }
331
+ }),
332
+ });
333
+ // Admin: Grant credits
334
+ http.route({
335
+ path: "/admin/grant-credits",
336
+ method: "POST",
337
+ handler: httpAction(async (ctx, request) => {
338
+ try {
339
+ const body = await request.json();
340
+ const { agentId, amount, reason } = body;
341
+ if (!agentId || !amount) {
342
+ return jsonResponse({ error: "agentId and amount required" }, 400);
343
+ }
344
+ // TODO: Add admin auth check here
345
+ // For now, allow grants (this is for Hivr integration)
346
+ const result = await ctx.runMutation(api.credits.addCredits, {
347
+ agentId,
348
+ amountUsd: amount,
349
+ source: reason || "admin_grant",
350
+ });
351
+ return jsonResponse({
352
+ success: true,
353
+ agentId,
354
+ credited: amount,
355
+ newBalance: result?.balanceUsd,
356
+ reason,
357
+ });
358
+ }
359
+ catch (e) {
360
+ return jsonResponse({ error: e.message || "Grant failed" }, 400);
361
+ }
362
+ }),
363
+ });
364
+ // Helper functions
365
+ function getCreditsPerDollar(providerId) {
366
+ const rates = {
367
+ "46elks": 30,
368
+ twilio: 25,
369
+ resend: 1000,
370
+ brave_search: 200,
371
+ openrouter: 100,
372
+ elevenlabs: 3333,
373
+ };
374
+ return rates[providerId] || 100;
375
+ }
376
+ function generateCredentials(providerId) {
377
+ // In production, this would generate or retrieve actual API keys
378
+ // For now, return placeholder indicating how to use
379
+ return {
380
+ type: "apiclaw_proxy",
381
+ endpoint: `https://brilliant-puffin-712.convex.site/proxy/${providerId}`,
382
+ note: "Use APIClaw proxy endpoint. Credentials managed automatically.",
383
+ };
384
+ }
385
+ export default http;
386
+ // ==============================================
387
+ // DIRECT CALL PROXY ENDPOINTS
388
+ // ==============================================
389
+ // OpenRouter proxy
390
+ http.route({
391
+ path: "/proxy/openrouter",
392
+ method: "POST",
393
+ handler: httpAction(async (ctx, request) => {
394
+ // Validate session and log usage
395
+ await validateAndLogProxyCall(ctx, request, "openrouter", "chat");
396
+ const OPENROUTER_KEY = process.env.OPENROUTER_API_KEY;
397
+ if (!OPENROUTER_KEY) {
398
+ return jsonResponse({ error: "OpenRouter not configured" }, 500);
399
+ }
400
+ try {
401
+ const body = await request.json();
402
+ const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
403
+ method: "POST",
404
+ headers: {
405
+ "Authorization": `Bearer ${OPENROUTER_KEY}`,
406
+ "Content-Type": "application/json",
407
+ "HTTP-Referer": "https://apiclaw.nordsym.com",
408
+ "X-Title": "APIClaw",
409
+ },
410
+ body: JSON.stringify(body),
411
+ });
412
+ const data = await response.json();
413
+ return jsonResponse(data, response.status);
414
+ }
415
+ catch (e) {
416
+ return jsonResponse({ error: e.message }, 500);
417
+ }
418
+ }),
419
+ });
420
+ // Brave Search proxy
421
+ http.route({
422
+ path: "/proxy/brave_search",
423
+ method: "POST",
424
+ handler: httpAction(async (ctx, request) => {
425
+ // Validate session and log usage
426
+ await validateAndLogProxyCall(ctx, request, "brave_search", "search");
427
+ const BRAVE_KEY = process.env.BRAVE_API_KEY;
428
+ if (!BRAVE_KEY) {
429
+ return jsonResponse({ error: "Brave Search not configured" }, 500);
430
+ }
431
+ try {
432
+ const body = await request.json();
433
+ const { query, count = 10 } = body;
434
+ const url = new URL("https://api.search.brave.com/res/v1/web/search");
435
+ url.searchParams.set("q", query);
436
+ url.searchParams.set("count", String(count));
437
+ const response = await fetch(url.toString(), {
438
+ headers: { "X-Subscription-Token": BRAVE_KEY },
439
+ });
440
+ const data = await response.json();
441
+ return jsonResponse(data, response.status);
442
+ }
443
+ catch (e) {
444
+ return jsonResponse({ error: e.message }, 500);
445
+ }
446
+ }),
447
+ });
448
+ // Resend email proxy
449
+ http.route({
450
+ path: "/proxy/resend",
451
+ method: "POST",
452
+ handler: httpAction(async (ctx, request) => {
453
+ // Validate session and log usage
454
+ await validateAndLogProxyCall(ctx, request, "resend", "send_email");
455
+ const RESEND_KEY = process.env.RESEND_API_KEY;
456
+ if (!RESEND_KEY) {
457
+ return jsonResponse({ error: "Resend not configured" }, 500);
458
+ }
459
+ try {
460
+ const body = await request.json();
461
+ const response = await fetch("https://api.resend.com/emails", {
462
+ method: "POST",
463
+ headers: {
464
+ "Authorization": `Bearer ${RESEND_KEY}`,
465
+ "Content-Type": "application/json",
466
+ },
467
+ body: JSON.stringify(body),
468
+ });
469
+ const data = await response.json();
470
+ return jsonResponse(data, response.status);
471
+ }
472
+ catch (e) {
473
+ return jsonResponse({ error: e.message }, 500);
474
+ }
475
+ }),
476
+ });
477
+ // ElevenLabs TTS proxy
478
+ http.route({
479
+ path: "/proxy/elevenlabs",
480
+ method: "POST",
481
+ handler: httpAction(async (ctx, request) => {
482
+ // Validate session and log usage
483
+ await validateAndLogProxyCall(ctx, request, "elevenlabs", "text_to_speech");
484
+ const ELEVENLABS_KEY = process.env.ELEVENLABS_API_KEY;
485
+ if (!ELEVENLABS_KEY) {
486
+ return jsonResponse({ error: "ElevenLabs not configured" }, 500);
487
+ }
488
+ try {
489
+ const body = await request.json();
490
+ const { text, voice_id = "21m00Tcm4TlvDq8ikWAM" } = body;
491
+ const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voice_id}`, {
492
+ method: "POST",
493
+ headers: {
494
+ "xi-api-key": ELEVENLABS_KEY,
495
+ "Content-Type": "application/json",
496
+ },
497
+ body: JSON.stringify({
498
+ text,
499
+ model_id: "eleven_turbo_v2",
500
+ }),
501
+ });
502
+ if (!response.ok) {
503
+ const error = await response.text();
504
+ return jsonResponse({ error }, response.status);
505
+ }
506
+ // Return audio as base64
507
+ const arrayBuffer = await response.arrayBuffer();
508
+ const base64 = Buffer.from(arrayBuffer).toString("base64");
509
+ return jsonResponse({
510
+ audio_base64: base64,
511
+ content_type: "audio/mpeg",
512
+ });
513
+ }
514
+ catch (e) {
515
+ return jsonResponse({ error: e.message }, 500);
516
+ }
517
+ }),
518
+ });
519
+ http.route({
520
+ path: "/proxy/openrouter",
521
+ method: "OPTIONS",
522
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
523
+ });
524
+ http.route({
525
+ path: "/proxy/brave_search",
526
+ method: "OPTIONS",
527
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
528
+ });
529
+ http.route({
530
+ path: "/proxy/resend",
531
+ method: "OPTIONS",
532
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
533
+ });
534
+ http.route({
535
+ path: "/proxy/elevenlabs",
536
+ method: "OPTIONS",
537
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
538
+ });
539
+ // 46elks SMS proxy
540
+ http.route({
541
+ path: "/proxy/46elks",
542
+ method: "POST",
543
+ handler: httpAction(async (ctx, request) => {
544
+ // Validate session and log usage
545
+ await validateAndLogProxyCall(ctx, request, "46elks", "send_sms");
546
+ const ELKS_USER = process.env.ELKS_API_USER;
547
+ const ELKS_PASS = process.env.ELKS_API_PASSWORD;
548
+ if (!ELKS_USER || !ELKS_PASS) {
549
+ return jsonResponse({ error: "46elks not configured" }, 500);
550
+ }
551
+ try {
552
+ const body = await request.json();
553
+ const { to, message, from = "APIClaw" } = body;
554
+ const auth = btoa(`${ELKS_USER}:${ELKS_PASS}`);
555
+ const response = await fetch("https://api.46elks.com/a1/sms", {
556
+ method: "POST",
557
+ headers: {
558
+ "Authorization": `Basic ${auth}`,
559
+ "Content-Type": "application/x-www-form-urlencoded",
560
+ },
561
+ body: new URLSearchParams({ from, to, message }),
562
+ });
563
+ const data = await response.json();
564
+ return jsonResponse(data, response.status);
565
+ }
566
+ catch (e) {
567
+ return jsonResponse({ error: e.message }, 500);
568
+ }
569
+ }),
570
+ });
571
+ // Twilio SMS proxy
572
+ http.route({
573
+ path: "/proxy/twilio",
574
+ method: "POST",
575
+ handler: httpAction(async (ctx, request) => {
576
+ // Validate session and log usage
577
+ await validateAndLogProxyCall(ctx, request, "twilio", "send_sms");
578
+ const TWILIO_SID = process.env.TWILIO_ACCOUNT_SID;
579
+ const TWILIO_TOKEN = process.env.TWILIO_AUTH_TOKEN;
580
+ if (!TWILIO_SID || !TWILIO_TOKEN) {
581
+ return jsonResponse({ error: "Twilio not configured" }, 500);
582
+ }
583
+ try {
584
+ const body = await request.json();
585
+ const { to, message, from } = body;
586
+ if (!from) {
587
+ return jsonResponse({ error: "Twilio requires 'from' number" }, 400);
588
+ }
589
+ const auth = btoa(`${TWILIO_SID}:${TWILIO_TOKEN}`);
590
+ const response = await fetch(`https://api.twilio.com/2010-04-01/Accounts/${TWILIO_SID}/Messages.json`, {
591
+ method: "POST",
592
+ headers: {
593
+ "Authorization": `Basic ${auth}`,
594
+ "Content-Type": "application/x-www-form-urlencoded",
595
+ },
596
+ body: new URLSearchParams({ To: to, From: from, Body: message }),
597
+ });
598
+ const data = await response.json();
599
+ return jsonResponse(data, response.status);
600
+ }
601
+ catch (e) {
602
+ return jsonResponse({ error: e.message }, 500);
603
+ }
604
+ }),
605
+ });
606
+ // CORS for new endpoints
607
+ http.route({
608
+ path: "/proxy/46elks",
609
+ method: "OPTIONS",
610
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
611
+ });
612
+ http.route({
613
+ path: "/proxy/twilio",
614
+ method: "OPTIONS",
615
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
616
+ });
617
+ // GitHub API proxy
618
+ http.route({
619
+ path: "/proxy/github",
620
+ method: "POST",
621
+ handler: httpAction(async (ctx, request) => {
622
+ // Validate session and log usage
623
+ const body = await request.json();
624
+ const action = body.action || "search_repos";
625
+ await validateAndLogProxyCall(ctx, request, "github", action);
626
+ const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
627
+ if (!GITHUB_TOKEN) {
628
+ return jsonResponse({ error: "GitHub not configured" }, 500);
629
+ }
630
+ try {
631
+ const { action, ...params } = body;
632
+ let url;
633
+ let method = "GET";
634
+ let fetchBody;
635
+ // Route based on action
636
+ switch (action) {
637
+ case "search_repos":
638
+ const { query, sort = "stars", limit = 10 } = params;
639
+ url = `https://api.github.com/search/repositories?q=${encodeURIComponent(query)}&sort=${sort}&per_page=${limit}`;
640
+ break;
641
+ case "get_repo":
642
+ const { owner, repo } = params;
643
+ url = `https://api.github.com/repos/${owner}/${repo}`;
644
+ break;
645
+ case "list_issues":
646
+ const { owner: issueOwner, repo: issueRepo, state = "open", limit: issueLimit = 10 } = params;
647
+ url = `https://api.github.com/repos/${issueOwner}/${issueRepo}/issues?state=${state}&per_page=${issueLimit}`;
648
+ break;
649
+ case "create_issue":
650
+ const { owner: createOwner, repo: createRepo, title, body: issueBody = "" } = params;
651
+ url = `https://api.github.com/repos/${createOwner}/${createRepo}/issues`;
652
+ method = "POST";
653
+ fetchBody = JSON.stringify({ title, body: issueBody });
654
+ break;
655
+ case "get_file":
656
+ const { owner: fileOwner, repo: fileRepo, path } = params;
657
+ url = `https://api.github.com/repos/${fileOwner}/${fileRepo}/contents/${path}`;
658
+ break;
659
+ default:
660
+ return jsonResponse({ error: `Unknown action: ${action}` }, 400);
661
+ }
662
+ const response = await fetch(url, {
663
+ method,
664
+ headers: {
665
+ "Authorization": `Bearer ${GITHUB_TOKEN}`,
666
+ "Accept": "application/vnd.github+json",
667
+ "User-Agent": "APIClaw",
668
+ ...(fetchBody ? { "Content-Type": "application/json" } : {}),
669
+ },
670
+ ...(fetchBody ? { body: fetchBody } : {}),
671
+ });
672
+ const data = await response.json();
673
+ return jsonResponse(data, response.status);
674
+ }
675
+ catch (e) {
676
+ return jsonResponse({ error: e.message }, 500);
677
+ }
678
+ }),
679
+ });
680
+ http.route({
681
+ path: "/proxy/github",
682
+ method: "OPTIONS",
683
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
684
+ });
685
+ // ==============================================
686
+ // WORKSPACE / MAGIC LINK ENDPOINTS
687
+ // ==============================================
688
+ // Create magic link and send email
689
+ http.route({
690
+ path: "/workspace/magic-link",
691
+ method: "POST",
692
+ handler: httpAction(async (ctx, request) => {
693
+ try {
694
+ const body = await request.json();
695
+ const { email, fingerprint } = body;
696
+ if (!email || !email.includes("@")) {
697
+ return jsonResponse({ error: "Valid email required" }, 400);
698
+ }
699
+ // Create magic link
700
+ const result = await ctx.runMutation(api.workspaces.createMagicLink, {
701
+ email: email.toLowerCase(),
702
+ fingerprint,
703
+ });
704
+ // Send email directly - SIMPLE HTML (complex tables get stripped by Gmail)
705
+ const verifyUrl = `https://apiclaw.nordsym.com/auth/verify?token=${result.token}`;
706
+ const html = `<div style="font-family:Arial,sans-serif;max-width:500px;margin:0 auto;padding:20px;">
707
+ <h1>🦞 APIClaw</h1>
708
+ <h2>An AI Agent Wants to Connect</h2>
709
+ <p>Click below to verify your email and activate your workspace.</p>
710
+ <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>
711
+ <p style="color:#666;font-size:13px;">Free tier: 50 API calls. This link expires in 1 hour.</p>
712
+ <p style="color:#999;font-size:11px;">Or copy this link: ${verifyUrl}</p>
713
+ </div>`;
714
+ const RESEND_KEY = process.env.RESEND_API_KEY;
715
+ if (!RESEND_KEY) {
716
+ console.error("RESEND_API_KEY not configured");
717
+ return jsonResponse({ error: "Email service not configured" }, 500);
718
+ }
719
+ const emailResponse = await fetch("https://api.resend.com/emails", {
720
+ method: "POST",
721
+ headers: {
722
+ "Authorization": `Bearer ${RESEND_KEY}`,
723
+ "Content-Type": "application/json",
724
+ },
725
+ body: JSON.stringify({
726
+ from: "APIClaw <noreply@apiclaw.nordsym.com>",
727
+ to: email.toLowerCase(),
728
+ subject: "🦞 Verify Your Email — APIClaw",
729
+ html: html,
730
+ }),
731
+ });
732
+ if (!emailResponse.ok) {
733
+ const errorText = await emailResponse.text();
734
+ console.error("Resend error:", emailResponse.status, errorText);
735
+ return jsonResponse({ error: "Failed to send email", details: errorText }, 500);
736
+ }
737
+ const emailResult = await emailResponse.json();
738
+ console.log("Email sent successfully:", emailResult.id);
739
+ return jsonResponse({
740
+ success: true,
741
+ token: result.token,
742
+ expiresAt: result.expiresAt,
743
+ message: "Magic link sent! Check your email.",
744
+ emailId: emailResult.id,
745
+ });
746
+ }
747
+ catch (e) {
748
+ console.error("Magic link error:", e);
749
+ return jsonResponse({ error: e.message || "Failed to create magic link" }, 500);
750
+ }
751
+ }),
752
+ });
753
+ http.route({
754
+ path: "/workspace/magic-link",
755
+ method: "OPTIONS",
756
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
757
+ });
758
+ // Poll magic link status (for agents to check if user clicked)
759
+ http.route({
760
+ path: "/workspace/poll",
761
+ method: "GET",
762
+ handler: httpAction(async (ctx, request) => {
763
+ const url = new URL(request.url);
764
+ const token = url.searchParams.get("token");
765
+ if (!token) {
766
+ return jsonResponse({ error: "token required" }, 400);
767
+ }
768
+ const result = await ctx.runQuery(api.workspaces.pollMagicLink, { token });
769
+ return jsonResponse(result);
770
+ }),
771
+ });
772
+ http.route({
773
+ path: "/workspace/poll",
774
+ method: "OPTIONS",
775
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
776
+ });
777
+ // Verify session token
778
+ http.route({
779
+ path: "/workspace/verify-session",
780
+ method: "GET",
781
+ handler: httpAction(async (ctx, request) => {
782
+ const url = new URL(request.url);
783
+ const sessionToken = url.searchParams.get("sessionToken");
784
+ if (!sessionToken) {
785
+ return jsonResponse({ error: "sessionToken required" }, 400);
786
+ }
787
+ const result = await ctx.runQuery(api.workspaces.verifySession, { sessionToken });
788
+ if (!result) {
789
+ return jsonResponse({ error: "Invalid or expired session" }, 401);
790
+ }
791
+ return jsonResponse(result);
792
+ }),
793
+ });
794
+ http.route({
795
+ path: "/workspace/verify-session",
796
+ method: "OPTIONS",
797
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
798
+ });
799
+ // Get workspace by email
800
+ http.route({
801
+ path: "/workspace/by-email",
802
+ method: "GET",
803
+ handler: httpAction(async (ctx, request) => {
804
+ const url = new URL(request.url);
805
+ const email = url.searchParams.get("email");
806
+ if (!email) {
807
+ return jsonResponse({ error: "email required" }, 400);
808
+ }
809
+ const result = await ctx.runQuery(api.workspaces.getByEmail, { email });
810
+ if (!result) {
811
+ return jsonResponse({ exists: false });
812
+ }
813
+ return jsonResponse({ exists: true, workspace: result });
814
+ }),
815
+ });
816
+ http.route({
817
+ path: "/workspace/by-email",
818
+ method: "OPTIONS",
819
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
820
+ });
821
+ // Send reminder email
822
+ http.route({
823
+ path: "/workspace/send-reminder",
824
+ method: "POST",
825
+ handler: httpAction(async (ctx, request) => {
826
+ try {
827
+ const body = await request.json();
828
+ const { email, token } = body;
829
+ if (!email || !token) {
830
+ return jsonResponse({ error: "email and token required" }, 400);
831
+ }
832
+ await ctx.runAction(api.email.sendReminderEmail, { email, token });
833
+ return jsonResponse({ success: true });
834
+ }
835
+ catch (e) {
836
+ return jsonResponse({ error: e.message }, 500);
837
+ }
838
+ }),
839
+ });
840
+ http.route({
841
+ path: "/workspace/send-reminder",
842
+ method: "OPTIONS",
843
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
844
+ });
845
+ // ==============================================
846
+ // STRIPE BILLING ENDPOINTS
847
+ // ==============================================
848
+ // Create checkout session
849
+ http.route({
850
+ path: "/api/billing/checkout",
851
+ method: "POST",
852
+ handler: createCheckoutSession,
853
+ });
854
+ http.route({
855
+ path: "/api/billing/checkout",
856
+ method: "OPTIONS",
857
+ handler: checkoutOptions,
858
+ });
859
+ // Create billing portal session
860
+ http.route({
861
+ path: "/api/billing/portal",
862
+ method: "POST",
863
+ handler: createPortalSession,
864
+ });
865
+ http.route({
866
+ path: "/api/billing/portal",
867
+ method: "OPTIONS",
868
+ handler: portalOptions,
869
+ });
870
+ // Stripe webhook handler
871
+ http.route({
872
+ path: "/api/webhooks/stripe",
873
+ method: "POST",
874
+ handler: handleStripeWebhook,
875
+ });
876
+ http.route({
877
+ path: "/api/webhooks/stripe",
878
+ method: "OPTIONS",
879
+ handler: webhookOptions,
880
+ });
881
+ // Test endpoint to debug logging
882
+ http.route({
883
+ path: "/proxy/test-logging",
884
+ method: "POST",
885
+ handler: httpAction(async (ctx, request) => {
886
+ const identifier = request.headers.get("X-APIClaw-Identifier");
887
+ try {
888
+ const logId = await ctx.runMutation(api.analytics.log, {
889
+ event: "test_endpoint",
890
+ provider: "test",
891
+ identifier: identifier || "test",
892
+ metadata: { test: true },
893
+ });
894
+ return jsonResponse({
895
+ success: true,
896
+ identifier,
897
+ logId,
898
+ message: "Logged successfully"
899
+ });
900
+ }
901
+ catch (e) {
902
+ return jsonResponse({
903
+ success: false,
904
+ error: e.message,
905
+ stack: e.stack
906
+ }, 500);
907
+ }
908
+ }),
909
+ });