@nordsym/apiclaw 2.1.0 → 2.2.1

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 (185) hide show
  1. package/README.md +15 -2
  2. package/dist/bin-http.js +0 -0
  3. package/dist/bin.bundled.js +79288 -0
  4. package/dist/funnel-client.d.ts +24 -0
  5. package/dist/funnel-client.d.ts.map +1 -0
  6. package/dist/funnel-client.js +131 -0
  7. package/dist/funnel-client.js.map +1 -0
  8. package/dist/funnel.test.d.ts +2 -0
  9. package/dist/funnel.test.d.ts.map +1 -0
  10. package/dist/funnel.test.js +145 -0
  11. package/dist/funnel.test.js.map +1 -0
  12. package/dist/gateway-client.d.ts.map +1 -1
  13. package/dist/gateway-client.js +24 -2
  14. package/dist/gateway-client.js.map +1 -1
  15. package/dist/index.bundled.js +61263 -0
  16. package/dist/index.js +161 -74
  17. package/dist/index.js.map +1 -1
  18. package/dist/postinstall.d.ts +0 -5
  19. package/dist/postinstall.d.ts.map +1 -1
  20. package/dist/postinstall.js +24 -3
  21. package/dist/postinstall.js.map +1 -1
  22. package/dist/registration-guard.d.ts +29 -0
  23. package/dist/registration-guard.d.ts.map +1 -0
  24. package/dist/registration-guard.js +87 -0
  25. package/dist/registration-guard.js.map +1 -0
  26. package/package.json +7 -2
  27. package/.claude/settings.local.json +0 -9
  28. package/.env.prod +0 -1
  29. package/apiclaw-README.md +0 -494
  30. package/convex/_generated/api.d.ts +0 -137
  31. package/convex/_generated/api.js +0 -23
  32. package/convex/_generated/dataModel.d.ts +0 -60
  33. package/convex/_generated/server.d.ts +0 -143
  34. package/convex/_generated/server.js +0 -93
  35. package/convex/adminActivate.ts +0 -53
  36. package/convex/adminStats.ts +0 -306
  37. package/convex/agents.ts +0 -939
  38. package/convex/analytics.ts +0 -187
  39. package/convex/apiKeys.ts +0 -220
  40. package/convex/backfillAnalytics.ts +0 -272
  41. package/convex/backfillSearchLogs.ts +0 -35
  42. package/convex/billing.ts +0 -834
  43. package/convex/capabilities.ts +0 -157
  44. package/convex/chains.ts +0 -1318
  45. package/convex/credits.ts +0 -211
  46. package/convex/crons.ts +0 -50
  47. package/convex/debugFilestackLogs.ts +0 -16
  48. package/convex/debugGetToken.ts +0 -18
  49. package/convex/directCall.ts +0 -713
  50. package/convex/earnProgress.ts +0 -753
  51. package/convex/email.ts +0 -329
  52. package/convex/feedback.ts +0 -265
  53. package/convex/http.ts +0 -3430
  54. package/convex/inbound.ts +0 -32
  55. package/convex/logs.ts +0 -701
  56. package/convex/migrateFilestack.ts +0 -81
  57. package/convex/migratePartnersProd.ts +0 -174
  58. package/convex/migratePratham.ts +0 -126
  59. package/convex/migrateProviderWorkspaces.ts +0 -175
  60. package/convex/mou.ts +0 -91
  61. package/convex/providerKeys.ts +0 -289
  62. package/convex/providers.ts +0 -1135
  63. package/convex/purchases.ts +0 -183
  64. package/convex/ratelimit.ts +0 -104
  65. package/convex/schema.ts +0 -869
  66. package/convex/searchLogs.ts +0 -265
  67. package/convex/seedAPILayerAPIs.ts +0 -191
  68. package/convex/seedDirectCallConfigs.ts +0 -336
  69. package/convex/seedPratham.ts +0 -149
  70. package/convex/spendAlerts.ts +0 -442
  71. package/convex/stripeActions.ts +0 -607
  72. package/convex/teams.ts +0 -243
  73. package/convex/telemetry.ts +0 -81
  74. package/convex/tsconfig.json +0 -25
  75. package/convex/updateAPIStatus.ts +0 -44
  76. package/convex/usage.ts +0 -260
  77. package/convex/usageReports.ts +0 -357
  78. package/convex/waitlist.ts +0 -55
  79. package/convex/webhooks.ts +0 -494
  80. package/convex/workspaceSettings.ts +0 -143
  81. package/convex/workspaces.ts +0 -1331
  82. package/convex.json +0 -3
  83. package/direct-test.mjs +0 -51
  84. package/email-templates/filestack-provider-outreach.html +0 -162
  85. package/email-templates/partnership-template.html +0 -116
  86. package/email-templates/pratham-draft-preview.txt +0 -57
  87. package/email-templates/pratham-partnership-draft.html +0 -141
  88. package/reports/APIClaw-Session-Report-2026-04-05.pdf +0 -0
  89. package/reports/pipeline/PIPELINE-REPORT.json +0 -153
  90. package/reports/pipeline/acquire_apisguru.json +0 -17
  91. package/reports/pipeline/capabilities.json +0 -38
  92. package/reports/pipeline/discover_azure_recursive.json +0 -1551
  93. package/reports/pipeline/discover_github.json +0 -25
  94. package/reports/pipeline/discover_github_repos.json +0 -49
  95. package/reports/pipeline/discover_swaggerhub.json +0 -24
  96. package/reports/pipeline/discover_well_known.json +0 -23
  97. package/reports/pipeline/fetch_specs.json +0 -19
  98. package/reports/pipeline/generate_providers.json +0 -14
  99. package/reports/pipeline/match_registry.json +0 -11
  100. package/reports/pipeline/parse_specs.json +0 -17
  101. package/reports/pipeline/promote_candidates.json +0 -34
  102. package/reports/pipeline/validate.json +0 -30
  103. package/reports/pipeline/validate_smoke_details.json +0 -3835
  104. package/reports/session-report-2026-04-05.html +0 -433
  105. package/seed-apis-direct.mjs +0 -106
  106. package/src/access-control.ts +0 -174
  107. package/src/adapters/base.ts +0 -364
  108. package/src/adapters/claude-desktop.ts +0 -41
  109. package/src/adapters/cline.ts +0 -88
  110. package/src/adapters/continue.ts +0 -91
  111. package/src/adapters/cursor.ts +0 -43
  112. package/src/adapters/custom.ts +0 -188
  113. package/src/adapters/detect.ts +0 -202
  114. package/src/adapters/index.ts +0 -47
  115. package/src/adapters/windsurf.ts +0 -44
  116. package/src/bin-http.ts +0 -45
  117. package/src/bin.ts +0 -34
  118. package/src/capability-router.ts +0 -331
  119. package/src/chainExecutor.ts +0 -730
  120. package/src/chainResolver.test.ts +0 -246
  121. package/src/chainResolver.ts +0 -658
  122. package/src/cli/commands/demo.ts +0 -109
  123. package/src/cli/commands/doctor.ts +0 -435
  124. package/src/cli/commands/index.ts +0 -9
  125. package/src/cli/commands/login.ts +0 -203
  126. package/src/cli/commands/mcp-install.ts +0 -373
  127. package/src/cli/commands/restore.ts +0 -333
  128. package/src/cli/commands/setup.ts +0 -297
  129. package/src/cli/commands/uninstall.ts +0 -240
  130. package/src/cli/index.ts +0 -148
  131. package/src/cli.ts +0 -370
  132. package/src/confirmation.ts +0 -296
  133. package/src/credentials.ts +0 -455
  134. package/src/credits.ts +0 -329
  135. package/src/crypto.ts +0 -75
  136. package/src/discovery.ts +0 -568
  137. package/src/enterprise/env.ts +0 -156
  138. package/src/enterprise/index.ts +0 -7
  139. package/src/enterprise/script-generator.ts +0 -481
  140. package/src/execute-dynamic.ts +0 -617
  141. package/src/execute.ts +0 -2386
  142. package/src/gateway-client.ts +0 -192
  143. package/src/hivr-whitelist.ts +0 -110
  144. package/src/http-api.ts +0 -286
  145. package/src/http-server-minimal.ts +0 -154
  146. package/src/index.ts +0 -2611
  147. package/src/intelligent-gateway.ts +0 -339
  148. package/src/mcp-analytics.ts +0 -156
  149. package/src/metered.ts +0 -149
  150. package/src/open-apis-generated.ts +0 -157
  151. package/src/open-apis.ts +0 -558
  152. package/src/postinstall.ts +0 -18
  153. package/src/product-whitelist.ts +0 -246
  154. package/src/proxy.ts +0 -36
  155. package/src/session.ts +0 -129
  156. package/src/stripe.ts +0 -497
  157. package/src/telemetry.ts +0 -71
  158. package/src/test.ts +0 -135
  159. package/src/types/convex-api.d.ts +0 -20
  160. package/src/types/convex-api.ts +0 -21
  161. package/src/types.ts +0 -109
  162. package/src/ui/colors.ts +0 -219
  163. package/src/ui/errors.ts +0 -394
  164. package/src/ui/index.ts +0 -17
  165. package/src/ui/prompts.ts +0 -390
  166. package/src/ui/spinner.ts +0 -325
  167. package/src/utils/backup.ts +0 -224
  168. package/src/utils/config.ts +0 -318
  169. package/src/utils/os.ts +0 -124
  170. package/src/utils/paths.ts +0 -203
  171. package/src/webhook.ts +0 -107
  172. package/test-10-working.cjs +0 -97
  173. package/test-14-final.cjs +0 -96
  174. package/test-actual-handlers.ts +0 -92
  175. package/test-apilayer-all-14.ts +0 -249
  176. package/test-apilayer-fixed.ts +0 -248
  177. package/test-direct-endpoints.ts +0 -174
  178. package/test-exact-endpoints.ts +0 -144
  179. package/test-final.ts +0 -83
  180. package/test-full-routing.ts +0 -100
  181. package/test-handlers-correct.ts +0 -217
  182. package/test-numverify-key.ts +0 -41
  183. package/test-via-handlers.ts +0 -92
  184. package/test-worldnews.mjs +0 -26
  185. package/tsconfig.json +0 -20
package/src/cli.ts DELETED
@@ -1,370 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * APIClaw Interactive CLI
4
- * Run with: npx @nordsym/apiclaw --cli
5
- */
6
-
7
- import * as readline from 'readline';
8
- import { ConvexHttpClient } from 'convex/browser';
9
- import { discoverAPIs, getAPIDetails, getCategories } from './discovery.js';
10
- import { executeAPICall, getConnectedProviders } from './execute.js';
11
- import { readSession, writeSession, clearSession, getMachineFingerprint } from './session.js';
12
-
13
- const CONVEX_URL = process.env.CONVEX_URL || 'https://brilliant-puffin-712.eu-west-1.convex.cloud';
14
- const convex = new ConvexHttpClient(CONVEX_URL);
15
-
16
- // Colors for terminal
17
- const colors = {
18
- reset: '\x1b[0m',
19
- bright: '\x1b[1m',
20
- red: '\x1b[31m',
21
- green: '\x1b[32m',
22
- yellow: '\x1b[33m',
23
- blue: '\x1b[34m',
24
- magenta: '\x1b[35m',
25
- cyan: '\x1b[36m',
26
- };
27
-
28
- function log(msg: string) {
29
- console.log(msg);
30
- }
31
-
32
- function success(msg: string) {
33
- console.log(`${colors.green}✓${colors.reset} ${msg}`);
34
- }
35
-
36
- function error(msg: string) {
37
- console.log(`${colors.red}✗${colors.reset} ${msg}`);
38
- }
39
-
40
- function info(msg: string) {
41
- console.log(`${colors.cyan}ℹ${colors.reset} ${msg}`);
42
- }
43
-
44
- interface WorkspaceContext {
45
- sessionToken: string;
46
- workspaceId: string;
47
- email: string;
48
- tier: string;
49
- usageRemaining: number;
50
- }
51
-
52
- let workspaceContext: WorkspaceContext | null = null;
53
-
54
- async function validateSession(): Promise<boolean> {
55
- const session = readSession();
56
- if (!session) return false;
57
-
58
- try {
59
- const result = await convex.query("workspaces:getWorkspaceStatus" as any, {
60
- sessionToken: session.sessionToken,
61
- }) as any;
62
-
63
- if (!result?.authenticated || result?.status !== 'active') {
64
- clearSession();
65
- return false;
66
- }
67
-
68
- workspaceContext = {
69
- sessionToken: session.sessionToken,
70
- workspaceId: session.workspaceId,
71
- email: result.email ?? '',
72
- tier: result.tier ?? 'free',
73
- usageRemaining: result.usageRemaining ?? 0,
74
- };
75
- return true;
76
- } catch {
77
- return false;
78
- }
79
- }
80
-
81
- async function registerOwner(email: string): Promise<void> {
82
- info(`Sending magic link to ${email}...`);
83
-
84
- try {
85
- const fingerprint = getMachineFingerprint();
86
-
87
- // Use HTTP endpoint for magic link
88
- const response = await fetch(`${CONVEX_URL.replace('.cloud', '.site')}/workspace/magic-link`, {
89
- method: 'POST',
90
- headers: { 'Content-Type': 'application/json' },
91
- body: JSON.stringify({ email, fingerprint }),
92
- });
93
-
94
- const result = await response.json() as { success?: boolean; token?: string; error?: string };
95
-
96
- if (result?.success && result?.token) {
97
- success(`Magic link sent to ${email}`);
98
- log(`\n📧 Check your email and click the link to authenticate.`);
99
-
100
- // Start polling for verification
101
- log(`\n⏳ Waiting for you to click the link...`);
102
- log(` (Press Ctrl+C to cancel)\n`);
103
-
104
- await pollForVerification(result.token, fingerprint);
105
- } else {
106
- error(`Failed: ${result?.error || 'Unknown error'}`);
107
- }
108
- } catch (err) {
109
- error(`Failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
110
- }
111
- }
112
-
113
- async function pollForVerification(token: string, fingerprint: string): Promise<void> {
114
- const maxAttempts = 60; // 5 minutes
115
- for (let i = 0; i < maxAttempts; i++) {
116
- await new Promise(r => setTimeout(r, 5000)); // Poll every 5 seconds
117
-
118
- try {
119
- const response = await fetch(`${CONVEX_URL.replace('.cloud', '.site')}/workspace/poll?token=${token}`);
120
- const result = await response.json() as {
121
- verified?: boolean;
122
- sessionToken?: string;
123
- workspaceId?: string;
124
- email?: string;
125
- };
126
-
127
- if (result?.verified && result?.sessionToken) {
128
- // Save the real session
129
- writeSession(
130
- result.sessionToken,
131
- result.workspaceId || '',
132
- result.email || ''
133
- );
134
-
135
- success(`Authenticated as ${result.email}!`);
136
-
137
- // Reload workspace context
138
- await validateSession();
139
- return;
140
- }
141
- } catch {
142
- // Continue polling
143
- }
144
-
145
- // Show progress dot
146
- process.stdout.write('.');
147
- }
148
-
149
- log('\n');
150
- error('Verification timed out. Please try again.');
151
- }
152
-
153
- async function showStatus(): Promise<void> {
154
- const valid = await validateSession();
155
-
156
- log(`\n${colors.bright}APIClaw Status${colors.reset}`);
157
- log(`${'─'.repeat(40)}`);
158
-
159
- if (valid && workspaceContext) {
160
- success(`Authenticated as ${workspaceContext.email}`);
161
- log(` Tier: ${workspaceContext.tier}`);
162
- log(` Remaining calls: ${workspaceContext.usageRemaining}`);
163
- } else {
164
- error(`Not authenticated`);
165
- log(` Run: ${colors.cyan}register <email>${colors.reset}`);
166
- }
167
- log('');
168
- }
169
-
170
- async function discover(query: string): Promise<void> {
171
- info(`Searching for: "${query}"`);
172
-
173
- try {
174
- const results = discoverAPIs(query, { maxResults: 5 });
175
-
176
- if (!results || results.length === 0) {
177
- log(`No APIs found for "${query}"`);
178
- return;
179
- }
180
-
181
- log(`\n${colors.bright}Found ${results.length} APIs:${colors.reset}\n`);
182
-
183
- // Get connected providers for Direct Call detection
184
- const connected = getConnectedProviders().map(p => p.provider.toLowerCase());
185
-
186
- for (const result of results) {
187
- const api = result.provider;
188
- const isDirectCall = connected.includes(api.id?.toLowerCase() || api.name.toLowerCase().replace(/\s+/g, '_'));
189
- const directCallBadge = isDirectCall ? `${colors.green}[Direct Call]${colors.reset}` : '';
190
- log(`${colors.cyan}${api.name}${colors.reset} ${directCallBadge}`);
191
- log(` ${api.description}`);
192
- log(` Category: ${api.category}`);
193
- log(` Pricing: ${api.pricing?.model || 'See docs'}`);
194
- log('');
195
- }
196
- } catch (err) {
197
- error(`Search failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
198
- }
199
- }
200
-
201
- async function listConnected(): Promise<void> {
202
- try {
203
- const providers = getConnectedProviders();
204
-
205
- log(`\n${colors.bright}Direct Call Providers (no API key needed):${colors.reset}\n`);
206
-
207
- for (const p of providers) {
208
- log(`${colors.cyan}${p.provider}${colors.reset}`);
209
- log(` Actions: ${p.actions?.join(', ') || 'See docs'}`);
210
- log('');
211
- }
212
- } catch (err) {
213
- error(`Failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
214
- }
215
- }
216
-
217
- async function callApi(provider: string, action: string, params: Record<string, any>): Promise<void> {
218
- if (!workspaceContext) {
219
- error('Not authenticated. Run: register <email>');
220
- return;
221
- }
222
-
223
- info(`Calling ${provider}.${action}...`);
224
-
225
- try {
226
- const result = await executeAPICall(
227
- provider,
228
- action,
229
- params,
230
- workspaceContext.workspaceId
231
- );
232
-
233
- log(`\n${colors.bright}Result:${colors.reset}\n`);
234
- log(JSON.stringify(result, null, 2));
235
- log('');
236
- } catch (err) {
237
- error(`Call failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
238
- }
239
- }
240
-
241
- function showHelp(): void {
242
- log(`
243
- ${colors.bright}🦞 APIClaw CLI${colors.reset}
244
-
245
- ${colors.cyan}Commands:${colors.reset}
246
- register <email> Send magic link to authenticate
247
- status Check authentication status
248
- discover <query> Search for APIs by capability
249
- list Show Direct Call providers
250
- call <provider> <action> <json-params>
251
- Call an API (e.g., call brave_search search {"q":"test"})
252
- help Show this help
253
- exit Quit
254
-
255
- ${colors.cyan}Examples:${colors.reset}
256
- discover send SMS
257
- discover image generation
258
- list
259
- call brave_search search {"q":"hello world"}
260
- `);
261
- }
262
-
263
- function parseCallCommand(args: string): { provider: string; action: string; params: Record<string, any> } | null {
264
- // Format: provider action {json}
265
- const match = args.match(/^(\S+)\s+(\S+)\s+(.+)$/);
266
- if (!match) return null;
267
-
268
- try {
269
- const params = JSON.parse(match[3]);
270
- return { provider: match[1], action: match[2], params };
271
- } catch {
272
- return null;
273
- }
274
- }
275
-
276
- export async function startCLI(): Promise<void> {
277
- log(`
278
- ${colors.bright}🦞 APIClaw CLI v1.1.5${colors.reset}
279
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
280
-
281
- Type ${colors.cyan}help${colors.reset} for commands, ${colors.cyan}exit${colors.reset} to quit.
282
- `);
283
-
284
- // Check session on startup
285
- const valid = await validateSession();
286
- if (valid && workspaceContext) {
287
- success(`Authenticated as ${workspaceContext.email}`);
288
- } else {
289
- info(`Not authenticated. Run: ${colors.cyan}register <email>${colors.reset}`);
290
- }
291
- log('');
292
-
293
- const rl = readline.createInterface({
294
- input: process.stdin,
295
- output: process.stdout,
296
- prompt: `${colors.red}apiclaw${colors.reset}> `,
297
- });
298
-
299
- rl.prompt();
300
-
301
- rl.on('line', async (line) => {
302
- const input = line.trim();
303
- const [cmd, ...args] = input.split(/\s+/);
304
- const argsStr = args.join(' ');
305
-
306
- switch (cmd.toLowerCase()) {
307
- case '':
308
- break;
309
-
310
- case 'help':
311
- case '?':
312
- showHelp();
313
- break;
314
-
315
- case 'exit':
316
- case 'quit':
317
- case 'q':
318
- log('Bye! 🦞');
319
- process.exit(0);
320
- break;
321
-
322
- case 'register':
323
- if (!argsStr) {
324
- error('Usage: register <email>');
325
- } else {
326
- await registerOwner(argsStr);
327
- }
328
- break;
329
-
330
- case 'status':
331
- await showStatus();
332
- break;
333
-
334
- case 'discover':
335
- case 'search':
336
- if (!argsStr) {
337
- error('Usage: discover <query>');
338
- } else {
339
- await discover(argsStr);
340
- }
341
- break;
342
-
343
- case 'list':
344
- case 'connected':
345
- await listConnected();
346
- break;
347
-
348
- case 'call':
349
- const parsed = parseCallCommand(argsStr);
350
- if (!parsed) {
351
- error('Usage: call <provider> <action> {"param":"value"}');
352
- log('Example: call brave_search search {"q":"hello"}');
353
- } else {
354
- await callApi(parsed.provider, parsed.action, parsed.params);
355
- }
356
- break;
357
-
358
- default:
359
- error(`Unknown command: ${cmd}`);
360
- log(`Type ${colors.cyan}help${colors.reset} for available commands.`);
361
- }
362
-
363
- rl.prompt();
364
- });
365
-
366
- rl.on('close', () => {
367
- log('\nBye! 🦞');
368
- process.exit(0);
369
- });
370
- }
@@ -1,296 +0,0 @@
1
- /**
2
- * APIClaw Confirmation System
3
- * For actions that cost money or have side effects
4
- *
5
- * Flow:
6
- * 1. Agent calls action → gets preview + token
7
- * 2. Agent shows preview to user
8
- * 3. User confirms → agent calls confirm with token
9
- * 4. APIClaw executes the actual action
10
- */
11
-
12
- import { randomBytes } from 'crypto';
13
-
14
- export interface PendingAction {
15
- token: string;
16
- provider: string;
17
- action: string;
18
- params: Record<string, any>;
19
- preview: Record<string, any>;
20
- createdAt: number;
21
- expiresAt: number;
22
- userId?: string;
23
- }
24
-
25
- // In-memory store for pending confirmations (in production, use Redis)
26
- const pendingActions = new Map<string, PendingAction>();
27
-
28
- // Actions that require confirmation before execution
29
- export const CONFIRMATION_REQUIRED: Record<string, string[]> = {
30
- // Invoicing - costs money per send
31
- coaccept: ['send_invoice', 'send_reminder'],
32
-
33
- // SMS - costs money per message
34
- '46elks': ['send_sms'],
35
- twilio: ['send_sms'],
36
-
37
- // Email sends (less critical but still good to confirm)
38
- resend: ['send_email'],
39
- };
40
-
41
- // Token expiry time (5 minutes)
42
- const TOKEN_EXPIRY_MS = 5 * 60 * 1000;
43
-
44
- /**
45
- * Check if an action requires confirmation (hardcoded list only)
46
- * For dynamic providers, use requiresConfirmationAsync
47
- */
48
- export function requiresConfirmation(provider: string, action: string): boolean {
49
- const actions = CONFIRMATION_REQUIRED[provider];
50
- return actions?.includes(action) ?? false;
51
- }
52
-
53
- /**
54
- * Check if a dynamic provider action requires confirmation
55
- * This is imported dynamically to avoid circular deps
56
- */
57
- export async function requiresConfirmationAsync(
58
- provider: string,
59
- action: string
60
- ): Promise<{ required: boolean; estimatedCost?: string; isDynamic?: boolean }> {
61
- // First check hardcoded list
62
- if (requiresConfirmation(provider, action)) {
63
- return { required: true, isDynamic: false };
64
- }
65
-
66
- // Then check dynamic provider config
67
- try {
68
- const { getDynamicConfirmationConfig } = await import('./execute-dynamic.js');
69
- const config = await getDynamicConfirmationConfig(provider, action);
70
- if (config.required) {
71
- return {
72
- required: true,
73
- estimatedCost: config.estimatedCost,
74
- isDynamic: true
75
- };
76
- }
77
- } catch (e) {
78
- // Dynamic config not available, that's ok
79
- }
80
-
81
- return { required: false };
82
- }
83
-
84
- /**
85
- * Generate a confirmation token and store the pending action
86
- */
87
- export function createPendingAction(
88
- provider: string,
89
- action: string,
90
- params: Record<string, any>,
91
- preview: Record<string, any>,
92
- userId?: string
93
- ): PendingAction {
94
- // Clean up expired tokens
95
- cleanupExpired();
96
-
97
- const token = randomBytes(16).toString('hex');
98
- const now = Date.now();
99
-
100
- const pending: PendingAction = {
101
- token,
102
- provider,
103
- action,
104
- params,
105
- preview,
106
- createdAt: now,
107
- expiresAt: now + TOKEN_EXPIRY_MS,
108
- userId,
109
- };
110
-
111
- pendingActions.set(token, pending);
112
- return pending;
113
- }
114
-
115
- /**
116
- * Get a pending action by token (and validate it)
117
- */
118
- export function getPendingAction(token: string): PendingAction | null {
119
- const pending = pendingActions.get(token);
120
-
121
- if (!pending) {
122
- return null;
123
- }
124
-
125
- if (Date.now() > pending.expiresAt) {
126
- pendingActions.delete(token);
127
- return null;
128
- }
129
-
130
- return pending;
131
- }
132
-
133
- /**
134
- * Consume a pending action (use it and remove from store)
135
- */
136
- export function consumePendingAction(token: string): PendingAction | null {
137
- const pending = getPendingAction(token);
138
-
139
- if (pending) {
140
- pendingActions.delete(token);
141
- }
142
-
143
- return pending;
144
- }
145
-
146
- /**
147
- * Clean up expired tokens
148
- */
149
- function cleanupExpired(): void {
150
- const now = Date.now();
151
- for (const [token, pending] of pendingActions.entries()) {
152
- if (now > pending.expiresAt) {
153
- pendingActions.delete(token);
154
- }
155
- }
156
- }
157
-
158
- /**
159
- * Generate a human-readable preview for an action
160
- */
161
- export function generatePreview(
162
- provider: string,
163
- action: string,
164
- params: Record<string, any>
165
- ): Record<string, any> {
166
- // Provider-specific preview generators
167
- switch (provider) {
168
- case 'coaccept':
169
- return generateCoAcceptPreview(action, params);
170
- case '46elks':
171
- case 'twilio':
172
- return generateSMSPreview(params);
173
- case 'resend':
174
- return generateEmailPreview(params);
175
- default:
176
- return { action, params };
177
- }
178
- }
179
-
180
- function generateCoAcceptPreview(action: string, params: Record<string, any>): Record<string, any> {
181
- if (action === 'send_invoice') {
182
- const items = params.items || [];
183
- const totalAmount = items.reduce((sum: number, item: any) => sum + (item.amount || 0), 0);
184
-
185
- return {
186
- type: 'invoice',
187
- recipient: {
188
- name: params.recipient_name,
189
- email: params.recipient_email,
190
- org_number: params.recipient_org_nr,
191
- },
192
- amount: {
193
- subtotal: totalAmount,
194
- vat_rate: params.vat_rate || 25,
195
- vat_amount: totalAmount * ((params.vat_rate || 25) / 100),
196
- total: totalAmount * (1 + (params.vat_rate || 25) / 100),
197
- currency: params.currency || 'SEK',
198
- },
199
- due_date: params.due_date,
200
- items: items.map((item: any) => ({
201
- description: item.description,
202
- quantity: item.quantity || 1,
203
- unit_price: item.unit_price || item.amount,
204
- amount: item.amount,
205
- })),
206
- payment_method: 'SMS + Swish/Card (CoAccept)',
207
- estimated_cost: '~2-5 SEK per invoice',
208
- };
209
- }
210
-
211
- return { action, params };
212
- }
213
-
214
- function generateSMSPreview(params: Record<string, any>): Record<string, any> {
215
- const messageLength = (params.message || '').length;
216
- const segments = Math.ceil(messageLength / 160);
217
-
218
- return {
219
- type: 'sms',
220
- to: params.to,
221
- from: params.from || 'NordSym',
222
- message: params.message,
223
- message_length: messageLength,
224
- segments,
225
- estimated_cost: `~${(segments * 0.35).toFixed(2)} SEK`,
226
- };
227
- }
228
-
229
- function generateEmailPreview(params: Record<string, any>): Record<string, any> {
230
- return {
231
- type: 'email',
232
- to: params.to,
233
- from: params.from || 'noreply@nordsym.com',
234
- subject: params.subject,
235
- preview: (params.message || params.html || '').substring(0, 200) + '...',
236
- };
237
- }
238
-
239
- /**
240
- * Validate params before creating preview
241
- * Returns { valid: true } or { valid: false, errors: [...] }
242
- */
243
- export function validateParams(
244
- provider: string,
245
- action: string,
246
- params: Record<string, any>
247
- ): { valid: boolean; errors?: string[] } {
248
- const errors: string[] = [];
249
-
250
- switch (provider) {
251
- case 'coaccept':
252
- if (action === 'send_invoice') {
253
- if (!params.recipient_name) errors.push('Missing: recipient_name');
254
- if (!params.recipient_email) errors.push('Missing: recipient_email');
255
- if (!params.items || !Array.isArray(params.items) || params.items.length === 0) {
256
- errors.push('Missing: items (at least one invoice item required)');
257
- }
258
- if (!params.due_date) errors.push('Missing: due_date (YYYY-MM-DD)');
259
-
260
- // Validate email format
261
- if (params.recipient_email && !params.recipient_email.includes('@')) {
262
- errors.push('Invalid: recipient_email format');
263
- }
264
-
265
- // Validate due date is not in past
266
- if (params.due_date) {
267
- const dueDate = new Date(params.due_date);
268
- const today = new Date();
269
- today.setHours(0, 0, 0, 0);
270
- if (dueDate < today) {
271
- errors.push('Invalid: due_date cannot be in the past');
272
- }
273
- }
274
- }
275
- break;
276
-
277
- case '46elks':
278
- case 'twilio':
279
- if (!params.to) errors.push('Missing: to (phone number)');
280
- if (!params.message) errors.push('Missing: message');
281
-
282
- // Validate phone format (basic check)
283
- if (params.to && !params.to.startsWith('+')) {
284
- errors.push('Invalid: phone number must start with + (e.g., +46701234567)');
285
- }
286
- break;
287
-
288
- case 'resend':
289
- if (!params.to) errors.push('Missing: to (email address)');
290
- if (!params.subject) errors.push('Missing: subject');
291
- if (!params.message && !params.html) errors.push('Missing: message or html content');
292
- break;
293
- }
294
-
295
- return errors.length > 0 ? { valid: false, errors } : { valid: true };
296
- }