@nordsym/apiclaw 1.5.17 → 1.5.19

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 (228) hide show
  1. package/convex/http.js.map +1 -1
  2. package/convex/http.ts +516 -0
  3. package/dist/analytics.d.ts +0 -4
  4. package/dist/analytics.d.ts.map +1 -1
  5. package/dist/analytics.js +0 -1
  6. package/dist/analytics.js.map +1 -1
  7. package/dist/bin.js +1 -1
  8. package/dist/cli/commands/mcp-install.d.ts.map +1 -1
  9. package/dist/cli/commands/mcp-install.js +8 -87
  10. package/dist/cli/commands/mcp-install.js.map +1 -1
  11. package/dist/cli/index.js +0 -7
  12. package/dist/credentials.d.ts.map +1 -1
  13. package/dist/credentials.js +38 -43
  14. package/dist/credentials.js.map +1 -1
  15. package/dist/discovery.d.ts.map +1 -1
  16. package/dist/discovery.js +82 -191
  17. package/dist/discovery.js.map +1 -1
  18. package/dist/http-api.d.ts.map +1 -1
  19. package/dist/http-api.js +33 -17
  20. package/dist/http-api.js.map +1 -1
  21. package/dist/proxy.js +1 -1
  22. package/dist/proxy.js.map +1 -1
  23. package/landing/next-env.d.ts +0 -1
  24. package/landing/src/app/api/auth/magic-link/route.ts +1 -1
  25. package/landing/src/app/auth/verify/page.tsx +0 -6
  26. package/landing/src/app/dashboard/verify/page.tsx +0 -6
  27. package/landing/src/app/join/page.tsx +0 -6
  28. package/landing/src/app/layout.tsx +2 -2
  29. package/landing/src/app/login/page.tsx +1 -1
  30. package/landing/src/app/mou/[partnerId]/page.tsx +0 -6
  31. package/landing/src/app/page.tsx +18 -39
  32. package/landing/src/app/providers/dashboard/[apiId]/actions/[actionId]/edit/page.tsx +0 -6
  33. package/landing/src/app/providers/dashboard/[apiId]/actions/new/page.tsx +0 -5
  34. package/landing/src/app/providers/dashboard/[apiId]/actions/page.tsx +0 -5
  35. package/landing/src/app/providers/dashboard/[apiId]/direct-call/page.tsx +1 -6
  36. package/landing/src/app/providers/dashboard/[apiId]/page.tsx +0 -5
  37. package/landing/src/app/providers/dashboard/[apiId]/test/page.tsx +0 -5
  38. package/landing/src/app/providers/dashboard/layout.tsx +6 -6
  39. package/landing/src/app/providers/dashboard/login/page.tsx +1 -1
  40. package/landing/src/app/providers/dashboard/page.tsx +1 -1
  41. package/landing/src/app/providers/dashboard/verify/page.tsx +0 -6
  42. package/landing/src/app/providers/layout.tsx +1 -1
  43. package/landing/src/app/upgrade/page.tsx +0 -6
  44. package/landing/src/app/workspace/page.tsx +0 -6
  45. package/landing/src/components/HeroTabs.tsx +2 -2
  46. package/landing/src/components/{Workspace.tsx → ProviderDashboard.tsx} +2 -2
  47. package/landing/src/components/VideoDemo.tsx +10 -21
  48. package/landing/src/lib/mock-data.ts +1 -1
  49. package/landing/src/lib/stats.json +1 -1
  50. package/package.json +3 -8
  51. package/src/analytics.ts +0 -5
  52. package/src/bin.ts +1 -1
  53. package/src/cli/commands/mcp-install.ts +8 -90
  54. package/src/cli/index.ts +0 -8
  55. package/src/credentials.ts +39 -44
  56. package/src/discovery.ts +82 -191
  57. package/src/http-api.ts +34 -18
  58. package/src/proxy.ts +1 -1
  59. package/APILAYER_STATUS_2026-03-24.md +0 -38
  60. package/CHANGELOG-WHITELIST-V2.md +0 -269
  61. package/HIVR-WHITELIST-STATUS.md +0 -205
  62. package/HIVR-WHITELIST.md +0 -148
  63. package/TERMINOLOGY-AUDIT.md +0 -99
  64. package/TERMINOLOGY-FIXED.md +0 -74
  65. package/VIDEO-DEMO-GUIDE.md +0 -82
  66. package/WHITELIST-ARCHITECTURE.md +0 -379
  67. package/api/discover.ts +0 -71
  68. package/api/health.ts +0 -20
  69. package/convex/adminActivate.d.ts +0 -3
  70. package/convex/adminActivate.js +0 -47
  71. package/convex/adminStats.d.ts +0 -3
  72. package/convex/adminStats.js +0 -42
  73. package/convex/agents.d.ts +0 -54
  74. package/convex/agents.js +0 -499
  75. package/convex/analytics.d.ts +0 -5
  76. package/convex/analytics.js +0 -166
  77. package/convex/billing.d.ts +0 -88
  78. package/convex/billing.js +0 -655
  79. package/convex/capabilities.d.ts +0 -9
  80. package/convex/capabilities.js +0 -145
  81. package/convex/chains.d.ts +0 -67
  82. package/convex/chains.js +0 -1042
  83. package/convex/credits.d.ts +0 -25
  84. package/convex/credits.js +0 -186
  85. package/convex/crons.d.ts +0 -3
  86. package/convex/crons.js +0 -17
  87. package/convex/directCall.d.ts +0 -72
  88. package/convex/directCall.js +0 -627
  89. package/convex/earnProgress.d.ts +0 -58
  90. package/convex/earnProgress.js +0 -649
  91. package/convex/email.d.ts +0 -14
  92. package/convex/email.js +0 -300
  93. package/convex/feedback.d.ts +0 -7
  94. package/convex/feedback.js +0 -227
  95. package/convex/http.d.ts +0 -3
  96. package/convex/http.js +0 -910
  97. package/convex/logs.d.ts +0 -38
  98. package/convex/logs.js +0 -487
  99. package/convex/mou.d.ts +0 -6
  100. package/convex/mou.js +0 -82
  101. package/convex/providerKeys.d.ts +0 -31
  102. package/convex/providerKeys.js +0 -257
  103. package/convex/providers.d.ts +0 -29
  104. package/convex/providers.js +0 -756
  105. package/convex/purchases.d.ts +0 -7
  106. package/convex/purchases.js +0 -157
  107. package/convex/ratelimit.d.ts +0 -4
  108. package/convex/ratelimit.js +0 -91
  109. package/convex/searchLogs.d.ts +0 -4
  110. package/convex/searchLogs.js +0 -129
  111. package/convex/spendAlerts.d.ts +0 -36
  112. package/convex/spendAlerts.js +0 -380
  113. package/convex/stripeActions.d.ts +0 -19
  114. package/convex/stripeActions.js +0 -411
  115. package/convex/teams.d.ts +0 -21
  116. package/convex/teams.js +0 -215
  117. package/convex/telemetry.d.ts +0 -4
  118. package/convex/telemetry.js +0 -74
  119. package/convex/usage.d.ts +0 -27
  120. package/convex/usage.js +0 -229
  121. package/convex/waitlist.d.ts +0 -4
  122. package/convex/waitlist.js +0 -49
  123. package/convex/webhooks.d.ts +0 -12
  124. package/convex/webhooks.js +0 -410
  125. package/convex/workspaces.d.ts +0 -29
  126. package/convex/workspaces.js +0 -880
  127. package/direct-test.mjs +0 -51
  128. package/dist/access-control.d.ts +0 -45
  129. package/dist/access-control.d.ts.map +0 -1
  130. package/dist/access-control.js +0 -142
  131. package/dist/access-control.js.map +0 -1
  132. package/dist/chain-types.d.ts +0 -187
  133. package/dist/chain-types.d.ts.map +0 -1
  134. package/dist/chain-types.js +0 -33
  135. package/dist/chain-types.js.map +0 -1
  136. package/dist/convex/adminActivate.js +0 -46
  137. package/dist/convex/adminStats.js +0 -41
  138. package/dist/convex/agents.js +0 -498
  139. package/dist/convex/analytics.js +0 -165
  140. package/dist/convex/billing.js +0 -654
  141. package/dist/convex/capabilities.js +0 -144
  142. package/dist/convex/chains.js +0 -1041
  143. package/dist/convex/credits.js +0 -185
  144. package/dist/convex/crons.js +0 -16
  145. package/dist/convex/directCall.js +0 -626
  146. package/dist/convex/earnProgress.js +0 -648
  147. package/dist/convex/email.js +0 -299
  148. package/dist/convex/feedback.js +0 -226
  149. package/dist/convex/http.js +0 -909
  150. package/dist/convex/logs.js +0 -486
  151. package/dist/convex/mou.js +0 -81
  152. package/dist/convex/providerKeys.js +0 -256
  153. package/dist/convex/providers.js +0 -755
  154. package/dist/convex/purchases.js +0 -156
  155. package/dist/convex/ratelimit.js +0 -90
  156. package/dist/convex/schema.js +0 -709
  157. package/dist/convex/searchLogs.js +0 -128
  158. package/dist/convex/spendAlerts.js +0 -379
  159. package/dist/convex/stripeActions.js +0 -410
  160. package/dist/convex/teams.js +0 -214
  161. package/dist/convex/telemetry.js +0 -73
  162. package/dist/convex/usage.js +0 -228
  163. package/dist/convex/waitlist.js +0 -48
  164. package/dist/convex/webhooks.js +0 -409
  165. package/dist/convex/workspaces.js +0 -879
  166. package/dist/hivr-whitelist.d.ts +0 -18
  167. package/dist/hivr-whitelist.d.ts.map +0 -1
  168. package/dist/hivr-whitelist.js +0 -95
  169. package/dist/hivr-whitelist.js.map +0 -1
  170. package/dist/http-server-minimal.d.ts +0 -7
  171. package/dist/http-server-minimal.d.ts.map +0 -1
  172. package/dist/http-server-minimal.js +0 -126
  173. package/dist/http-server-minimal.js.map +0 -1
  174. package/dist/product-whitelist.d.ts +0 -37
  175. package/dist/product-whitelist.d.ts.map +0 -1
  176. package/dist/product-whitelist.js +0 -203
  177. package/dist/product-whitelist.js.map +0 -1
  178. package/dist/src/analytics.js +0 -129
  179. package/dist/src/bin.js +0 -17
  180. package/dist/src/capability-router.js +0 -240
  181. package/dist/src/chainExecutor.js +0 -451
  182. package/dist/src/chainResolver.js +0 -518
  183. package/dist/src/cli/commands/doctor.js +0 -324
  184. package/dist/src/cli/commands/mcp-install.js +0 -255
  185. package/dist/src/cli/commands/restore.js +0 -259
  186. package/dist/src/cli/commands/setup.js +0 -205
  187. package/dist/src/cli/commands/uninstall.js +0 -188
  188. package/dist/src/cli/index.js +0 -111
  189. package/dist/src/cli.js +0 -302
  190. package/dist/src/confirmation.js +0 -240
  191. package/dist/src/credentials.js +0 -357
  192. package/dist/src/credits.js +0 -260
  193. package/dist/src/crypto.js +0 -66
  194. package/dist/src/discovery.js +0 -504
  195. package/dist/src/enterprise/env.js +0 -123
  196. package/dist/src/enterprise/script-generator.js +0 -460
  197. package/dist/src/execute-dynamic.js +0 -473
  198. package/dist/src/execute.js +0 -1727
  199. package/dist/src/index.js +0 -2062
  200. package/dist/src/metered.js +0 -80
  201. package/dist/src/open-apis.js +0 -276
  202. package/dist/src/proxy.js +0 -28
  203. package/dist/src/session.js +0 -86
  204. package/dist/src/stripe.js +0 -407
  205. package/dist/src/telemetry.js +0 -49
  206. package/dist/src/types.js +0 -2
  207. package/dist/src/utils/backup.js +0 -181
  208. package/dist/src/utils/config.js +0 -220
  209. package/dist/src/utils/os.js +0 -105
  210. package/dist/src/utils/paths.js +0 -159
  211. package/landing/pages/api/discover.ts +0 -43
  212. package/landing/pages/api/health.ts +0 -20
  213. package/scripts/test-whitelist-v2.sh +0 -128
  214. package/src/access-control.ts +0 -174
  215. package/src/hivr-whitelist.ts +0 -110
  216. package/src/http-server-minimal.ts +0 -154
  217. package/src/product-whitelist.ts +0 -246
  218. package/test-actual-handlers.ts +0 -92
  219. package/test-apilayer-all-14.ts +0 -249
  220. package/test-apilayer-fixed.ts +0 -248
  221. package/test-direct-endpoints.ts +0 -174
  222. package/test-exact-endpoints.ts +0 -144
  223. package/test-final.ts +0 -83
  224. package/test-full-routing.ts +0 -100
  225. package/test-handlers-correct.ts +0 -217
  226. package/test-numverify-key.ts +0 -41
  227. package/test-via-handlers.ts +0 -92
  228. package/test-worldnews.mjs +0 -26
@@ -1,228 +0,0 @@
1
- import { v } from "convex/values";
2
- import { mutation, query } from "./_generated/server";
3
- // ============================================
4
- // MUTATIONS
5
- // ============================================
6
- /**
7
- * Log an API call usage
8
- */
9
- export const logUsage = mutation({
10
- args: {
11
- userId: v.string(),
12
- providerId: v.id("providers"),
13
- directCallId: v.id("providerDirectCall"),
14
- actionName: v.string(),
15
- success: v.boolean(),
16
- latencyMs: v.number(),
17
- creditsUsed: v.number(),
18
- errorMessage: v.optional(v.string()),
19
- },
20
- handler: async (ctx, args) => {
21
- return await ctx.db.insert("usageLog", {
22
- userId: args.userId,
23
- providerId: args.providerId,
24
- directCallId: args.directCallId,
25
- actionName: args.actionName,
26
- timestamp: Date.now(),
27
- success: args.success,
28
- latencyMs: args.latencyMs,
29
- creditsUsed: args.creditsUsed,
30
- errorMessage: args.errorMessage,
31
- });
32
- },
33
- });
34
- // ============================================
35
- // QUERIES
36
- // ============================================
37
- /**
38
- * Get user usage stats for rate limiting
39
- * Returns counts for last minute and last day
40
- */
41
- export const getUserUsage = query({
42
- args: {
43
- userId: v.string(),
44
- providerId: v.id("providers"),
45
- },
46
- handler: async (ctx, args) => {
47
- const now = Date.now();
48
- const oneMinuteAgo = now - 60 * 1000;
49
- const oneDayAgo = now - 24 * 60 * 60 * 1000;
50
- // Get all usage for this user + provider in the last 24h
51
- const recentUsage = await ctx.db
52
- .query("usageLog")
53
- .withIndex("by_userId_providerId", (q) => q.eq("userId", args.userId).eq("providerId", args.providerId))
54
- .filter((q) => q.gte(q.field("timestamp"), oneDayAgo))
55
- .collect();
56
- // Calculate counts
57
- const minuteCount = recentUsage.filter((u) => u.timestamp >= oneMinuteAgo).length;
58
- const dayCount = recentUsage.length;
59
- const totalCredits = recentUsage.reduce((sum, u) => sum + u.creditsUsed, 0);
60
- return {
61
- minute: minuteCount,
62
- day: dayCount,
63
- totalCreditsUsed: totalCredits,
64
- };
65
- },
66
- });
67
- /**
68
- * Get provider usage stats for analytics
69
- */
70
- export const getProviderUsage = query({
71
- args: {
72
- providerId: v.id("providers"),
73
- periodDays: v.optional(v.number()), // default 30
74
- },
75
- handler: async (ctx, args) => {
76
- const periodDays = args.periodDays ?? 30;
77
- const now = Date.now();
78
- const periodStart = now - periodDays * 24 * 60 * 60 * 1000;
79
- const usage = await ctx.db
80
- .query("usageLog")
81
- .withIndex("by_providerId", (q) => q.eq("providerId", args.providerId))
82
- .filter((q) => q.gte(q.field("timestamp"), periodStart))
83
- .collect();
84
- // Aggregate stats
85
- const totalCalls = usage.length;
86
- const successfulCalls = usage.filter((u) => u.success).length;
87
- const failedCalls = totalCalls - successfulCalls;
88
- const totalCredits = usage.reduce((sum, u) => sum + u.creditsUsed, 0);
89
- const totalLatency = usage.reduce((sum, u) => sum + u.latencyMs, 0);
90
- const avgLatency = totalCalls > 0 ? Math.round(totalLatency / totalCalls) : 0;
91
- // Group by action
92
- const byAction = {};
93
- for (const u of usage) {
94
- if (!byAction[u.actionName]) {
95
- byAction[u.actionName] = { calls: 0, credits: 0 };
96
- }
97
- byAction[u.actionName].calls++;
98
- byAction[u.actionName].credits += u.creditsUsed;
99
- }
100
- // Group by day for chart
101
- const byDay = {};
102
- for (const u of usage) {
103
- const day = new Date(u.timestamp).toISOString().split("T")[0];
104
- if (!byDay[day]) {
105
- byDay[day] = { calls: 0, credits: 0 };
106
- }
107
- byDay[day].calls++;
108
- byDay[day].credits += u.creditsUsed;
109
- }
110
- // Unique users
111
- const uniqueUsers = new Set(usage.map((u) => u.userId)).size;
112
- return {
113
- periodDays,
114
- totalCalls,
115
- successfulCalls,
116
- failedCalls,
117
- successRate: totalCalls > 0 ? (successfulCalls / totalCalls) * 100 : 0,
118
- totalCredits,
119
- avgLatencyMs: avgLatency,
120
- uniqueUsers,
121
- byAction,
122
- byDay,
123
- };
124
- },
125
- });
126
- /**
127
- * Get Direct Call specific usage stats
128
- */
129
- export const getDirectCallUsage = query({
130
- args: {
131
- directCallId: v.id("providerDirectCall"),
132
- periodDays: v.optional(v.number()),
133
- },
134
- handler: async (ctx, args) => {
135
- const periodDays = args.periodDays ?? 30;
136
- const now = Date.now();
137
- const periodStart = now - periodDays * 24 * 60 * 60 * 1000;
138
- const usage = await ctx.db
139
- .query("usageLog")
140
- .withIndex("by_directCallId", (q) => q.eq("directCallId", args.directCallId))
141
- .filter((q) => q.gte(q.field("timestamp"), periodStart))
142
- .collect();
143
- const totalCalls = usage.length;
144
- const successfulCalls = usage.filter((u) => u.success).length;
145
- const totalCredits = usage.reduce((sum, u) => sum + u.creditsUsed, 0);
146
- const totalLatency = usage.reduce((sum, u) => sum + u.latencyMs, 0);
147
- return {
148
- periodDays,
149
- totalCalls,
150
- successfulCalls,
151
- failedCalls: totalCalls - successfulCalls,
152
- successRate: totalCalls > 0 ? (successfulCalls / totalCalls) * 100 : 0,
153
- totalCredits,
154
- avgLatencyMs: totalCalls > 0 ? Math.round(totalLatency / totalCalls) : 0,
155
- uniqueUsers: new Set(usage.map((u) => u.userId)).size,
156
- };
157
- },
158
- });
159
- /**
160
- * Get recent usage logs (for dashboard/debugging)
161
- */
162
- export const getRecentLogs = query({
163
- args: {
164
- providerId: v.optional(v.id("providers")),
165
- directCallId: v.optional(v.id("providerDirectCall")),
166
- limit: v.optional(v.number()),
167
- },
168
- handler: async (ctx, args) => {
169
- const limit = args.limit ?? 50;
170
- const { directCallId, providerId } = args;
171
- if (directCallId !== undefined) {
172
- return await ctx.db
173
- .query("usageLog")
174
- .withIndex("by_directCallId", (q) => q.eq("directCallId", directCallId))
175
- .order("desc")
176
- .take(limit);
177
- }
178
- if (providerId !== undefined) {
179
- return await ctx.db
180
- .query("usageLog")
181
- .withIndex("by_providerId", (q) => q.eq("providerId", providerId))
182
- .order("desc")
183
- .take(limit);
184
- }
185
- return await ctx.db
186
- .query("usageLog")
187
- .withIndex("by_timestamp")
188
- .order("desc")
189
- .take(limit);
190
- },
191
- });
192
- /**
193
- * Check if user is within rate limits
194
- * Returns { allowed: boolean, reason?: string }
195
- */
196
- export const checkRateLimit = query({
197
- args: {
198
- userId: v.string(),
199
- providerId: v.id("providers"),
200
- rateLimitPerUser: v.number(),
201
- rateLimitPerDay: v.number(),
202
- },
203
- handler: async (ctx, args) => {
204
- const now = Date.now();
205
- const oneMinuteAgo = now - 60 * 1000;
206
- const oneDayAgo = now - 24 * 60 * 60 * 1000;
207
- const recentUsage = await ctx.db
208
- .query("usageLog")
209
- .withIndex("by_userId_providerId", (q) => q.eq("userId", args.userId).eq("providerId", args.providerId))
210
- .filter((q) => q.gte(q.field("timestamp"), oneDayAgo))
211
- .collect();
212
- const minuteCount = recentUsage.filter((u) => u.timestamp >= oneMinuteAgo).length;
213
- const dayCount = recentUsage.length;
214
- if (minuteCount >= args.rateLimitPerUser) {
215
- return {
216
- allowed: false,
217
- reason: `Rate limit exceeded: ${minuteCount}/${args.rateLimitPerUser} requests per minute`,
218
- };
219
- }
220
- if (dayCount >= args.rateLimitPerDay) {
221
- return {
222
- allowed: false,
223
- reason: `Daily limit exceeded: ${dayCount}/${args.rateLimitPerDay} requests per day`,
224
- };
225
- }
226
- return { allowed: true };
227
- },
228
- });
@@ -1,48 +0,0 @@
1
- import { mutation, query } from "./_generated/server";
2
- import { v } from "convex/values";
3
- export const join = mutation({
4
- args: {
5
- email: v.string(),
6
- type: v.optional(v.string()),
7
- source: v.optional(v.string()),
8
- },
9
- handler: async (ctx, args) => {
10
- const email = args.email.toLowerCase().trim();
11
- // Check if already on waitlist
12
- const existing = await ctx.db
13
- .query("waitlist")
14
- .withIndex("by_email", (q) => q.eq("email", email))
15
- .first();
16
- if (existing) {
17
- return { success: true, alreadyExists: true };
18
- }
19
- await ctx.db.insert("waitlist", {
20
- email,
21
- type: args.type || "provider",
22
- source: args.source || "landing",
23
- createdAt: Date.now(),
24
- });
25
- return { success: true, alreadyExists: false };
26
- },
27
- });
28
- export const count = query({
29
- args: {},
30
- handler: async (ctx) => {
31
- const all = await ctx.db.query("waitlist").collect();
32
- return all.length;
33
- },
34
- });
35
- export const list = query({
36
- args: {
37
- type: v.optional(v.string()),
38
- },
39
- handler: async (ctx, args) => {
40
- if (args.type) {
41
- return await ctx.db
42
- .query("waitlist")
43
- .withIndex("by_type", (q) => q.eq("type", args.type))
44
- .collect();
45
- }
46
- return await ctx.db.query("waitlist").collect();
47
- },
48
- });
@@ -1,409 +0,0 @@
1
- import { v } from "convex/values";
2
- import { mutation, query, action, internalAction, internalQuery, internalMutation } from "./_generated/server";
3
- import { internal } from "./_generated/api";
4
- // Event types available for webhooks
5
- export const WEBHOOK_EVENTS = [
6
- "usage.threshold.80",
7
- "usage.threshold.100",
8
- "api.error",
9
- "agent.connected",
10
- "agent.revoked",
11
- ];
12
- // Generate a random secret for webhook signature verification
13
- function generateSecret() {
14
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
15
- let result = "whsec_";
16
- for (let i = 0; i < 32; i++) {
17
- result += chars.charAt(Math.floor(Math.random() * chars.length));
18
- }
19
- return result;
20
- }
21
- // ============================================
22
- // QUERIES
23
- // ============================================
24
- export const getWebhooks = query({
25
- args: { token: v.string() },
26
- handler: async (ctx, args) => {
27
- // Verify session
28
- const session = await ctx.db
29
- .query("agentSessions")
30
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
31
- .first();
32
- if (!session) {
33
- return { error: "Invalid session" };
34
- }
35
- // Get webhooks for workspace
36
- const webhooks = await ctx.db
37
- .query("webhooks")
38
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
39
- .collect();
40
- // Return webhooks without exposing full secret
41
- return {
42
- webhooks: webhooks.map((wh) => ({
43
- id: wh._id,
44
- url: wh.url,
45
- events: wh.events,
46
- enabled: wh.enabled,
47
- lastTriggeredAt: wh.lastTriggeredAt,
48
- lastStatus: wh.lastStatus,
49
- failCount: wh.failCount,
50
- createdAt: wh.createdAt,
51
- // Only show hint of secret
52
- secretHint: wh.secret.slice(0, 10) + "..." + wh.secret.slice(-4),
53
- })),
54
- };
55
- },
56
- });
57
- // ============================================
58
- // MUTATIONS
59
- // ============================================
60
- export const createWebhook = mutation({
61
- args: {
62
- token: v.string(),
63
- url: v.string(),
64
- events: v.array(v.string()),
65
- },
66
- handler: async (ctx, args) => {
67
- // Verify session
68
- const session = await ctx.db
69
- .query("agentSessions")
70
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
71
- .first();
72
- if (!session) {
73
- return { error: "Invalid session" };
74
- }
75
- // Validate URL
76
- try {
77
- new URL(args.url);
78
- }
79
- catch {
80
- return { error: "Invalid URL format" };
81
- }
82
- // Validate URL is HTTPS
83
- if (!args.url.startsWith("https://")) {
84
- return { error: "Webhook URL must use HTTPS" };
85
- }
86
- // Validate events
87
- const validEvents = args.events.filter((e) => WEBHOOK_EVENTS.includes(e));
88
- if (validEvents.length === 0) {
89
- return { error: "At least one valid event is required" };
90
- }
91
- // Check webhook limit (max 5 per workspace)
92
- const existingWebhooks = await ctx.db
93
- .query("webhooks")
94
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
95
- .collect();
96
- if (existingWebhooks.length >= 5) {
97
- return { error: "Maximum 5 webhooks per workspace" };
98
- }
99
- // Check for duplicate URL
100
- const duplicate = existingWebhooks.find((wh) => wh.url === args.url);
101
- if (duplicate) {
102
- return { error: "A webhook with this URL already exists" };
103
- }
104
- // Generate secret
105
- const secret = generateSecret();
106
- // Create webhook
107
- const webhookId = await ctx.db.insert("webhooks", {
108
- workspaceId: session.workspaceId,
109
- url: args.url,
110
- events: validEvents,
111
- secret,
112
- enabled: true,
113
- failCount: 0,
114
- createdAt: Date.now(),
115
- });
116
- return {
117
- success: true,
118
- webhookId,
119
- secret, // Return secret only once on creation
120
- };
121
- },
122
- });
123
- export const updateWebhook = mutation({
124
- args: {
125
- token: v.string(),
126
- webhookId: v.id("webhooks"),
127
- enabled: v.optional(v.boolean()),
128
- events: v.optional(v.array(v.string())),
129
- },
130
- handler: async (ctx, args) => {
131
- // Verify session
132
- const session = await ctx.db
133
- .query("agentSessions")
134
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
135
- .first();
136
- if (!session) {
137
- return { error: "Invalid session" };
138
- }
139
- // Get webhook
140
- const webhook = await ctx.db.get(args.webhookId);
141
- if (!webhook || webhook.workspaceId !== session.workspaceId) {
142
- return { error: "Webhook not found" };
143
- }
144
- // Build update object
145
- const updates = {};
146
- if (args.enabled !== undefined) {
147
- updates.enabled = args.enabled;
148
- }
149
- if (args.events !== undefined) {
150
- const validEvents = args.events.filter((e) => WEBHOOK_EVENTS.includes(e));
151
- if (validEvents.length === 0) {
152
- return { error: "At least one valid event is required" };
153
- }
154
- updates.events = validEvents;
155
- }
156
- // Update webhook
157
- await ctx.db.patch(args.webhookId, updates);
158
- return { success: true };
159
- },
160
- });
161
- export const deleteWebhook = mutation({
162
- args: {
163
- token: v.string(),
164
- webhookId: v.id("webhooks"),
165
- },
166
- handler: async (ctx, args) => {
167
- // Verify session
168
- const session = await ctx.db
169
- .query("agentSessions")
170
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
171
- .first();
172
- if (!session) {
173
- return { error: "Invalid session" };
174
- }
175
- // Get webhook
176
- const webhook = await ctx.db.get(args.webhookId);
177
- if (!webhook || webhook.workspaceId !== session.workspaceId) {
178
- return { error: "Webhook not found" };
179
- }
180
- // Delete webhook
181
- await ctx.db.delete(args.webhookId);
182
- return { success: true };
183
- },
184
- });
185
- export const regenerateSecret = mutation({
186
- args: {
187
- token: v.string(),
188
- webhookId: v.id("webhooks"),
189
- },
190
- handler: async (ctx, args) => {
191
- // Verify session
192
- const session = await ctx.db
193
- .query("agentSessions")
194
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
195
- .first();
196
- if (!session) {
197
- return { error: "Invalid session" };
198
- }
199
- // Get webhook
200
- const webhook = await ctx.db.get(args.webhookId);
201
- if (!webhook || webhook.workspaceId !== session.workspaceId) {
202
- return { error: "Webhook not found" };
203
- }
204
- // Generate new secret
205
- const newSecret = generateSecret();
206
- // Update webhook
207
- await ctx.db.patch(args.webhookId, { secret: newSecret });
208
- return {
209
- success: true,
210
- secret: newSecret, // Return new secret
211
- };
212
- },
213
- });
214
- // ============================================
215
- // ACTIONS (for HTTP calls)
216
- // ============================================
217
- export const testWebhook = action({
218
- args: {
219
- token: v.string(),
220
- webhookId: v.id("webhooks"),
221
- },
222
- returns: v.union(v.object({ error: v.string() }), v.object({ success: v.literal(true), status: v.number(), message: v.string() }), v.object({ success: v.literal(false), status: v.optional(v.number()), message: v.string() })),
223
- handler: async (ctx, args) => {
224
- // Get webhook from database
225
- const queryResult = await ctx.runQuery(internal.webhooks.getWebhookInternal, {
226
- token: args.token,
227
- webhookId: args.webhookId,
228
- });
229
- if (!queryResult || "error" in queryResult) {
230
- return { error: queryResult?.error || "Webhook not found" };
231
- }
232
- const webhook = queryResult.webhook;
233
- // Create test payload
234
- const payload = {
235
- event: "test",
236
- workspace: webhook.workspaceId,
237
- timestamp: new Date().toISOString(),
238
- data: {
239
- message: "This is a test webhook from APIClaw",
240
- webhookId: args.webhookId,
241
- },
242
- };
243
- // Sign the payload
244
- const signature = await signPayload(JSON.stringify(payload), webhook.secret);
245
- try {
246
- const response = await fetch(webhook.url, {
247
- method: "POST",
248
- headers: {
249
- "Content-Type": "application/json",
250
- "X-APIClaw-Signature": signature,
251
- "X-APIClaw-Event": "test",
252
- "X-APIClaw-Timestamp": payload.timestamp,
253
- },
254
- body: JSON.stringify(payload),
255
- });
256
- if (response.ok) {
257
- return {
258
- success: true,
259
- status: response.status,
260
- message: "Webhook delivered successfully",
261
- };
262
- }
263
- else {
264
- return {
265
- success: false,
266
- status: response.status,
267
- message: `Webhook returned status ${response.status}`,
268
- };
269
- }
270
- }
271
- catch (error) {
272
- return {
273
- success: false,
274
- message: error instanceof Error ? error.message : "Failed to deliver webhook",
275
- };
276
- }
277
- },
278
- });
279
- // Internal action to trigger webhooks (called from other parts of the system)
280
- export const triggerWebhooks = internalAction({
281
- args: {
282
- workspaceId: v.id("workspaces"),
283
- event: v.string(),
284
- data: v.any(),
285
- },
286
- returns: v.object({ triggered: v.number(), total: v.optional(v.number()) }),
287
- handler: async (ctx, args) => {
288
- // Get all enabled webhooks for this workspace that subscribe to this event
289
- const webhooksResult = await ctx.runQuery(internal.webhooks.getWebhooksForEvent, {
290
- workspaceId: args.workspaceId,
291
- event: args.event,
292
- });
293
- if (!webhooksResult || webhooksResult.length === 0) {
294
- return { triggered: 0 };
295
- }
296
- const payload = {
297
- event: args.event,
298
- workspace: args.workspaceId,
299
- timestamp: new Date().toISOString(),
300
- data: args.data,
301
- };
302
- const payloadString = JSON.stringify(payload);
303
- let successCount = 0;
304
- // Send to each webhook
305
- for (const webhook of webhooksResult) {
306
- const signature = await signPayload(payloadString, webhook.secret);
307
- try {
308
- const response = await fetch(webhook.url, {
309
- method: "POST",
310
- headers: {
311
- "Content-Type": "application/json",
312
- "X-APIClaw-Signature": signature,
313
- "X-APIClaw-Event": args.event,
314
- "X-APIClaw-Timestamp": payload.timestamp,
315
- },
316
- body: payloadString,
317
- });
318
- // Update webhook status
319
- await ctx.runMutation(internal.webhooks.updateWebhookStatus, {
320
- webhookId: webhook._id,
321
- success: response.ok,
322
- });
323
- if (response.ok) {
324
- successCount++;
325
- }
326
- }
327
- catch {
328
- // Update webhook with failure
329
- await ctx.runMutation(internal.webhooks.updateWebhookStatus, {
330
- webhookId: webhook._id,
331
- success: false,
332
- });
333
- }
334
- }
335
- return { triggered: successCount, total: webhooksResult.length };
336
- },
337
- });
338
- // ============================================
339
- // INTERNAL QUERIES/MUTATIONS (for actions)
340
- // ============================================
341
- export const getWebhookInternal = internalQuery({
342
- args: {
343
- token: v.string(),
344
- webhookId: v.id("webhooks"),
345
- },
346
- handler: async (ctx, args) => {
347
- // Verify session
348
- const session = await ctx.db
349
- .query("agentSessions")
350
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
351
- .first();
352
- if (!session) {
353
- return { error: "Invalid session" };
354
- }
355
- // Get webhook
356
- const webhook = await ctx.db.get(args.webhookId);
357
- if (!webhook || webhook.workspaceId !== session.workspaceId) {
358
- return { error: "Webhook not found" };
359
- }
360
- return { webhook };
361
- },
362
- });
363
- export const getWebhooksForEvent = internalQuery({
364
- args: {
365
- workspaceId: v.id("workspaces"),
366
- event: v.string(),
367
- },
368
- handler: async (ctx, args) => {
369
- const webhooks = await ctx.db
370
- .query("webhooks")
371
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", args.workspaceId))
372
- .collect();
373
- // Filter for enabled webhooks that subscribe to this event
374
- return webhooks.filter((wh) => wh.enabled && wh.events.includes(args.event));
375
- },
376
- });
377
- export const updateWebhookStatus = internalMutation({
378
- args: {
379
- webhookId: v.id("webhooks"),
380
- success: v.boolean(),
381
- },
382
- handler: async (ctx, args) => {
383
- const webhook = await ctx.db.get(args.webhookId);
384
- if (!webhook)
385
- return;
386
- await ctx.db.patch(args.webhookId, {
387
- lastTriggeredAt: Date.now(),
388
- lastStatus: args.success ? "success" : "failed",
389
- failCount: args.success ? 0 : webhook.failCount + 1,
390
- });
391
- // Disable webhook after 5 consecutive failures
392
- if (!args.success && webhook.failCount + 1 >= 5) {
393
- await ctx.db.patch(args.webhookId, { enabled: false });
394
- }
395
- },
396
- });
397
- // ============================================
398
- // HELPERS
399
- // ============================================
400
- async function signPayload(payload, secret) {
401
- // Simple HMAC-like signature using SHA-256
402
- // In a production environment, use proper crypto
403
- const encoder = new TextEncoder();
404
- const data = encoder.encode(payload + secret);
405
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
406
- const hashArray = Array.from(new Uint8Array(hashBuffer));
407
- const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
408
- return `sha256=${hashHex}`;
409
- }