crypto-quant-signal-mcp 1.18.2 → 1.19.0

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 (90) hide show
  1. package/README.md +12 -5
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +230 -10
  4. package/dist/index.js.map +1 -1
  5. package/dist/lib/adapters/binance.d.ts +1 -0
  6. package/dist/lib/adapters/binance.d.ts.map +1 -1
  7. package/dist/lib/adapters/binance.js +9 -1
  8. package/dist/lib/adapters/binance.js.map +1 -1
  9. package/dist/lib/email.d.ts +3 -0
  10. package/dist/lib/email.d.ts.map +1 -1
  11. package/dist/lib/email.js +85 -2
  12. package/dist/lib/email.js.map +1 -1
  13. package/dist/lib/funnel-snapshot.d.ts +104 -0
  14. package/dist/lib/funnel-snapshot.d.ts.map +1 -0
  15. package/dist/lib/funnel-snapshot.js +622 -0
  16. package/dist/lib/funnel-snapshot.js.map +1 -0
  17. package/dist/lib/integrations-data/mcp-clients.d.ts.map +1 -1
  18. package/dist/lib/integrations-data/mcp-clients.js +11 -6
  19. package/dist/lib/integrations-data/mcp-clients.js.map +1 -1
  20. package/dist/lib/license.d.ts +4 -0
  21. package/dist/lib/license.d.ts.map +1 -1
  22. package/dist/lib/license.js +56 -1
  23. package/dist/lib/license.js.map +1 -1
  24. package/dist/lib/performance-db.d.ts +25 -0
  25. package/dist/lib/performance-db.d.ts.map +1 -1
  26. package/dist/lib/performance-db.js +249 -1
  27. package/dist/lib/performance-db.js.map +1 -1
  28. package/dist/lib/pertf-thresholds.d.ts +67 -0
  29. package/dist/lib/pertf-thresholds.d.ts.map +1 -0
  30. package/dist/lib/pertf-thresholds.js +88 -0
  31. package/dist/lib/pertf-thresholds.js.map +1 -0
  32. package/dist/lib/r4-relax-flag.d.ts +47 -0
  33. package/dist/lib/r4-relax-flag.d.ts.map +1 -0
  34. package/dist/lib/r4-relax-flag.js +58 -0
  35. package/dist/lib/r4-relax-flag.js.map +1 -0
  36. package/dist/lib/signup-emails-store.d.ts +47 -0
  37. package/dist/lib/signup-emails-store.d.ts.map +1 -0
  38. package/dist/lib/signup-emails-store.js +109 -0
  39. package/dist/lib/signup-emails-store.js.map +1 -0
  40. package/dist/lib/stripe.d.ts +1 -0
  41. package/dist/lib/stripe.d.ts.map +1 -1
  42. package/dist/lib/stripe.js +4 -2
  43. package/dist/lib/stripe.js.map +1 -1
  44. package/dist/lib/tier-warning.d.ts +1 -1
  45. package/dist/lib/tier-warning.d.ts.map +1 -1
  46. package/dist/lib/tier-warning.js +23 -1
  47. package/dist/lib/tier-warning.js.map +1 -1
  48. package/dist/lib/track-token.d.ts +74 -0
  49. package/dist/lib/track-token.d.ts.map +1 -0
  50. package/dist/lib/track-token.js +145 -0
  51. package/dist/lib/track-token.js.map +1 -0
  52. package/dist/lib/webhook-api.d.ts +15 -0
  53. package/dist/lib/webhook-api.d.ts.map +1 -0
  54. package/dist/lib/webhook-api.js +250 -0
  55. package/dist/lib/webhook-api.js.map +1 -0
  56. package/dist/lib/webhook-delivery.d.ts +71 -0
  57. package/dist/lib/webhook-delivery.d.ts.map +1 -0
  58. package/dist/lib/webhook-delivery.js +261 -0
  59. package/dist/lib/webhook-delivery.js.map +1 -0
  60. package/dist/lib/webhook-events.d.ts +30 -0
  61. package/dist/lib/webhook-events.d.ts.map +1 -0
  62. package/dist/lib/webhook-events.js +158 -0
  63. package/dist/lib/webhook-events.js.map +1 -0
  64. package/dist/lib/webhook-ssrf.d.ts +39 -0
  65. package/dist/lib/webhook-ssrf.d.ts.map +1 -0
  66. package/dist/lib/webhook-ssrf.js +183 -0
  67. package/dist/lib/webhook-ssrf.js.map +1 -0
  68. package/dist/lib/webhooks-store.d.ts +110 -0
  69. package/dist/lib/webhooks-store.d.ts.map +1 -0
  70. package/dist/lib/webhooks-store.js +208 -0
  71. package/dist/lib/webhooks-store.js.map +1 -0
  72. package/dist/lib/welcome-page.d.ts.map +1 -1
  73. package/dist/lib/welcome-page.js +85 -1
  74. package/dist/lib/welcome-page.js.map +1 -1
  75. package/dist/lib/x402-bazaar.d.ts +33 -0
  76. package/dist/lib/x402-bazaar.d.ts.map +1 -0
  77. package/dist/lib/x402-bazaar.js +222 -0
  78. package/dist/lib/x402-bazaar.js.map +1 -0
  79. package/dist/lib/x402-facilitator.d.ts +75 -0
  80. package/dist/lib/x402-facilitator.d.ts.map +1 -0
  81. package/dist/lib/x402-facilitator.js +90 -0
  82. package/dist/lib/x402-facilitator.js.map +1 -0
  83. package/dist/lib/x402.d.ts.map +1 -1
  84. package/dist/lib/x402.js +35 -5
  85. package/dist/lib/x402.js.map +1 -1
  86. package/dist/tools/get-trade-call.d.ts.map +1 -1
  87. package/dist/tools/get-trade-call.js +24 -6
  88. package/dist/tools/get-trade-call.js.map +1 -1
  89. package/package.json +3 -1
  90. package/server.json +1 -1
package/README.md CHANGED
@@ -68,7 +68,7 @@ AlgoVault MCP serves Streamable HTTP at `https://api.algovault.com/mcp` — MCP-
68
68
  | Client | Config |
69
69
  |---|---|
70
70
  | **Claude Desktop** | Settings → Integrations → Add custom connector → `https://api.algovault.com/mcp` |
71
- | **Claude Code** (CLI) | `claude mcp add crypto-quant-signal https://api.algovault.com/mcp` |
71
+ | **Claude Code** (CLI) | `claude mcp add crypto-quant-signal https://api.algovault.com/mcp --header "X-AlgoVault-Track-Token:chan-readme"` |
72
72
  | **Cursor** | `~/.cursor/config.json` → `mcpServers` block → `url: "https://api.algovault.com/mcp"` |
73
73
  | **Cline** | VS Code Cline extension → MCP server settings → add Streamable HTTP server |
74
74
  | **Codex** (OpenAI CLI) | `~/.codex/config.toml` → `[mcp_servers.algovault]` table + `url = "https://api.algovault.com/mcp"` (or `codex mcp` CLI) |
@@ -97,12 +97,19 @@ Each demo is runnable as `python examples/<framework>/demo.py BTC 4h` — gets a
97
97
 
98
98
  ---
99
99
 
100
- ## What's new in v1.18.0
100
+ ## What's new in v1.18.2
101
101
 
102
- Live since 2026-05-23:
102
+ Live since 2026-05-25:
103
+
104
+ - **🔌 Two new platform integration examples.** The `algovault-integrations` mono-repo now ships 5 reference implementations total (was 3 at v1.18.0):
105
+ - **QuantDinger** (reference-architecture doc) — cross-MCP IDE-mediated orchestration. AlgoVault MCP and QuantDinger MCP connect through the user's IDE (Claude Desktop / Cursor / Codex CLI); no transformer code.
106
+ - **Cryptohopper** (TypeScript) — Signaler webhook with HMAC-sha512 signed payloads. First HMAC-authed transport in the integrations repo.
107
+ - **🧭 "Connect Your Trading Platform" section** added to [algovault.com/integrations](https://algovault.com/integrations). Discoverable tiles for the 5 platform examples; "Why integrate with AlgoVault?" framing replaces the prior exchange-kit framing.
108
+
109
+ ### v1.18.0 highlights (recap)
103
110
 
104
111
  - **⏱️ 3-minute timeframe goes LIVE on the public Live Track Record.** The 3m card and Methodology > Evaluation Windows row are now visible at [algovault.com/track-record](https://algovault.com/track-record). The 9th evaluated timeframe is live. (The `3m` key shipped to `/api/performance-public.byTimeframe` in v1.16.0; v1.18.0 completes the dashboard-display chain.)
105
- - **🔌 Platform integration examples.** New public repo at [github.com/AlgoVaultLabs/algovault-integrations](https://github.com/AlgoVaultLabs/algovault-integrations) ships reference implementations of the Verifiable-Signal v1.0 spec (introduced in v1.17.0). Three platforms in this release:
112
+ - **🔌 Platform integration examples.** New public repo at [github.com/AlgoVaultLabs/algovault-integrations](https://github.com/AlgoVaultLabs/algovault-integrations) ships reference implementations of the Verifiable-Signal v1.0 spec (introduced in v1.17.0). Three platforms in v1.18.0:
106
113
  - **AI4Trade** (TypeScript) — REST POST with token-in-body auth.
107
114
  - **Nautilus Trader** (Python) — Subclass of Nautilus's `Data` abstract base.
108
115
  - **3Commas** (TypeScript) — Signal Bot webhook via per-bot curry-pattern factory.
@@ -439,7 +446,7 @@ npx -y crypto-quant-signal-mcp
439
446
  ### Claude Code CLI
440
447
 
441
448
  ```bash
442
- claude mcp add crypto-quant-signal https://api.algovault.com/mcp
449
+ claude mcp add crypto-quant-signal https://api.algovault.com/mcp --header "X-AlgoVault-Track-Token:chan-readme"
443
450
  ```
444
451
 
445
452
  ### npm install
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAWA,OAAO,EAAE,SAAS,EAAoB,MAAM,yCAAyC,CAAC;AAo7FtF,wBAAgB,mBAAmB,cAElC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAWA,OAAO,EAAE,SAAS,EAAoB,MAAM,yCAAyC,CAAC;AAqpGtF,wBAAgB,mBAAmB,cAElC"}
package/dist/index.js CHANGED
@@ -57,6 +57,8 @@ const get_market_regime_js_1 = require("./tools/get-market-regime.js");
57
57
  const signal_performance_js_1 = require("./resources/signal-performance.js");
58
58
  const cross_asset_grid_js_1 = require("./lib/cross-asset-grid.js");
59
59
  const performance_db_js_1 = require("./lib/performance-db.js");
60
+ const webhook_api_js_1 = require("./lib/webhook-api.js");
61
+ const webhook_delivery_js_1 = require("./lib/webhook-delivery.js");
60
62
  const pkg_version_js_1 = require("./lib/pkg-version.js");
61
63
  const erc8004_reputation_js_1 = require("./lib/erc8004-reputation.js");
62
64
  const merkle_js_1 = require("./lib/merkle.js");
@@ -66,9 +68,15 @@ const license_js_1 = require("./lib/license.js");
66
68
  const x402_js_1 = require("./lib/x402.js");
67
69
  const analytics_js_1 = require("./lib/analytics.js");
68
70
  const stripe_events_store_js_1 = require("./lib/stripe-events-store.js");
71
+ const signup_emails_store_js_1 = require("./lib/signup-emails-store.js");
72
+ const email_js_1 = require("./lib/email.js");
73
+ const stripe_js_1 = require("./lib/stripe.js");
69
74
  const analytics_summary_js_1 = require("./resources/analytics-summary.js");
70
75
  const skills_analytics_js_1 = require("./resources/skills-analytics.js");
71
- const stripe_js_1 = require("./lib/stripe.js");
76
+ const funnel_snapshot_js_1 = require("./lib/funnel-snapshot.js");
77
+ const performance_db_js_2 = require("./lib/performance-db.js");
78
+ const track_token_js_1 = require("./lib/track-token.js");
79
+ const stripe_js_2 = require("./lib/stripe.js");
72
80
  const errors_js_1 = require("./lib/errors.js");
73
81
  const venue_store_js_1 = require("./lib/venue-store.js");
74
82
  const bot_auth_js_1 = require("./lib/bot-auth.js");
@@ -693,7 +701,7 @@ async function startHttp() {
693
701
  app.use((_req, res, next) => {
694
702
  res.setHeader('Access-Control-Allow-Origin', process.env.CORS_ORIGIN || 'https://api.algovault.com');
695
703
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
696
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-payment, mcp-session-id, x-algovault-skill-slug');
704
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-payment, mcp-session-id, x-algovault-skill-slug, x-algovault-track-token');
697
705
  if (_req.method === 'OPTIONS')
698
706
  return res.sendStatus(204);
699
707
  next();
@@ -730,7 +738,7 @@ async function startHttp() {
730
738
  });
731
739
  // Health check
732
740
  app.get('/health', (_req, res) => {
733
- res.json({ status: 'ok', server: 'crypto-quant-signal-mcp', version: pkg_version_js_1.PKG_VERSION, stripe: (0, stripe_js_1.isStripeConfigured)() });
741
+ res.json({ status: 'ok', server: 'crypto-quant-signal-mcp', version: pkg_version_js_1.PKG_VERSION, stripe: (0, stripe_js_2.isStripeConfigured)() });
734
742
  });
735
743
  // ── Integration tutorial mirrors ──
736
744
  // Static HTML pre-rendered from algovault-skills/docs/integrations/<x>.md
@@ -830,19 +838,19 @@ async function startHttp() {
830
838
  if (!sig)
831
839
  return res.status(400).json({ error: 'Missing stripe-signature header' });
832
840
  try {
833
- const event = (0, stripe_js_1.constructWebhookEvent)(req.body, sig);
841
+ const event = (0, stripe_js_2.constructWebhookEvent)(req.body, sig);
834
842
  if (!event)
835
843
  return res.status(400).json({ error: 'Stripe not configured' });
836
844
  switch (event.type) {
837
845
  case 'customer.subscription.created':
838
- await (0, stripe_js_1.handleSubscriptionCreated)(event);
846
+ await (0, stripe_js_2.handleSubscriptionCreated)(event);
839
847
  break;
840
848
  case 'customer.subscription.deleted':
841
- await (0, stripe_js_1.handleSubscriptionDeleted)(event);
849
+ await (0, stripe_js_2.handleSubscriptionDeleted)(event);
842
850
  break;
843
851
  case 'checkout.session.completed': {
844
852
  // ACTIVATION-PAYWALL-W1: structured tier promotion + UTM round-trip.
845
- const summary = (0, stripe_js_1.summarizeCheckoutCompleted)(event);
853
+ const summary = (0, stripe_js_2.summarizeCheckoutCompleted)(event);
846
854
  if (!summary) {
847
855
  console.warn(`Stripe webhook: checkout.session.completed with unparseable session payload (event ${event.id})`);
848
856
  break;
@@ -911,10 +919,36 @@ async function startHttp() {
911
919
  const baseUrl = `${req.protocol}://${req.get('host')}`;
912
920
  const utmSource = typeof req.query.utm_source === 'string' ? req.query.utm_source : undefined;
913
921
  const utmCampaign = typeof req.query.utm_campaign === 'string' ? req.query.utm_campaign : undefined;
922
+ const upgradeFrom = typeof req.query.upgrade_from === 'string' ? req.query.upgrade_from : undefined;
914
923
  // Derive a session-unique client_reference_id for downstream attribution
915
924
  // join even when UTM tags are absent (e.g. direct /signup typing).
916
925
  const clientReferenceId = `${utmSource ?? 'direct'}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`;
917
- const url = await (0, stripe_js_1.createCheckoutSession)(plan, baseUrl, {
926
+ // ACTIVATION-FUNNEL-AUDIT-W1 (2026-05-28): captures `upgrade_cta_clicked`
927
+ // (stage 7) when traffic carries `?upgrade_from=quota` attribution from
928
+ // tier-warning CTAs / quota-block error envelopes. Recorded BEFORE Stripe
929
+ // redirect so we capture clicks that never complete checkout (funnel
930
+ // diff stage 7 → 8). Lazy-import + fail-open.
931
+ if (upgradeFrom && upgradeFrom.length > 0) {
932
+ try {
933
+ const { recordFunnelEvent } = await import('./lib/performance-db.js');
934
+ recordFunnelEvent({
935
+ eventType: 'upgrade_cta_clicked',
936
+ sessionId: clientReferenceId,
937
+ licenseTier: 'free',
938
+ meta: {
939
+ plan,
940
+ upgrade_from: upgradeFrom,
941
+ utm_source: utmSource ?? null,
942
+ utm_campaign: utmCampaign ?? null,
943
+ },
944
+ });
945
+ }
946
+ catch (err) {
947
+ // Fail-open per CLAUDE.md `## Automation-first recovery → fail-open`.
948
+ console.warn('[upgrade_cta_clicked] recordFunnelEvent failed:', err instanceof Error ? err.message : err);
949
+ }
950
+ }
951
+ const url = await (0, stripe_js_2.createCheckoutSession)(plan, baseUrl, {
918
952
  utmSource,
919
953
  utmCampaign,
920
954
  clientReferenceId,
@@ -942,7 +976,7 @@ async function startHttp() {
942
976
  return res.send((0, welcome_page_js_1.getWelcomePageHtml)(null, null, null, { utmSource, utmCampaign }));
943
977
  }
944
978
  try {
945
- const { apiKey, tier, email } = await (0, stripe_js_1.getCustomerApiKey)(sessionId);
979
+ const { apiKey, tier, email } = await (0, stripe_js_2.getCustomerApiKey)(sessionId);
946
980
  res.send((0, welcome_page_js_1.getWelcomePageHtml)(apiKey, tier, email, { utmSource, utmCampaign }));
947
981
  }
948
982
  catch (err) {
@@ -1067,6 +1101,47 @@ async function startHttp() {
1067
1101
  res.status(500).json({ error: 'Failed to fetch skills analytics' });
1068
1102
  }
1069
1103
  });
1104
+ // ACTIVATION-FUNNEL-AUDIT-W1 (2026-05-28): admin-only 14-stage funnel snapshot.
1105
+ // Wraps the same `generateFunnelSnapshot()` library function used by the
1106
+ // weekly systemd-timer snapshot pipeline (scripts/funnel-snapshot.ts CLI +
1107
+ // commit-funnel-snapshot.sh). Window selectable via ?window=24h|7d|14d|30d|all_time
1108
+ // (default 14d). Returns full FunnelSnapshot JSON with all 14 stages +
1109
+ // stage_retentions + weakest_stage_transition. Same admin-auth pattern as
1110
+ // /dashboard/api/skills-analytics. window_label echo so clients verify the
1111
+ // server interpreted ?window correctly.
1112
+ app.get('/api/admin/funnel-snapshot', async (req, res) => {
1113
+ if (!isAdminAuthorized(req)) {
1114
+ return res.status(401).json({ error: 'Unauthorized' });
1115
+ }
1116
+ try {
1117
+ const windowRaw = String(req.query.window ?? '14d').trim().toLowerCase();
1118
+ const windowToDays = {
1119
+ '24h': 1,
1120
+ '7d': 7,
1121
+ '14d': 14,
1122
+ '30d': 30,
1123
+ 'all_time': 3650,
1124
+ };
1125
+ const days = windowToDays[windowRaw];
1126
+ if (days === undefined) {
1127
+ return res.status(400).json({
1128
+ error: 'Invalid window',
1129
+ allowed: Object.keys(windowToDays),
1130
+ got: windowRaw,
1131
+ });
1132
+ }
1133
+ const snapshot = await (0, funnel_snapshot_js_1.generateFunnelSnapshot)({ days });
1134
+ res.setHeader('Cache-Control', 'no-store');
1135
+ res.json({
1136
+ window_label: windowRaw,
1137
+ ...snapshot,
1138
+ });
1139
+ }
1140
+ catch (err) {
1141
+ console.error(`[/api/admin/funnel-snapshot] internal error: ${err instanceof Error ? err.message : err}`);
1142
+ res.status(500).json({ error: 'Failed to generate funnel snapshot' });
1143
+ }
1144
+ });
1070
1145
  // CHAT-USAGE-ANALYTICS-W1 (2026-05-18): admin-only chat analytics dashboard.
1071
1146
  // PII-safe (SHA256 hash + length only; no raw question text). Surfaces
1072
1147
  // LLM-PROVIDER-A/B-W1 trigger status (≥100 queries/day × 7 consecutive
@@ -1274,6 +1349,50 @@ async function startHttp() {
1274
1349
  // ── Merkle verification endpoints (public, no auth) ──
1275
1350
  const MERKLE_CONTRACT_ADDR = process.env.MERKLE_CONTRACT_ADDRESS || '';
1276
1351
  app.get('/api/verify-signal', async (req, res) => {
1352
+ // WEBHOOK-HARDENING-W1 C3: dual lookup — `?hash=<signal_hash>` (the form
1353
+ // baked into every webhook verify_url) OR the existing `?signalId=<int>`.
1354
+ // The signalId path below is byte-for-byte unchanged.
1355
+ const hashParam = typeof req.query.hash === 'string' ? req.query.hash.trim() : '';
1356
+ if (hashParam) {
1357
+ if (!/^0x[0-9a-fA-F]{64}$/.test(hashParam)) {
1358
+ return res.status(400).json({ error: 'invalid hash (expected 0x + 64 hex chars)' });
1359
+ }
1360
+ try {
1361
+ const s = await (0, performance_db_js_1.getSignalByHash)(hashParam);
1362
+ if (!s) {
1363
+ return res.status(404).json({ error: 'Signal not found', hash: hashParam, hint: 'No trade call matches this hash. Check the value from your webhook payload.' });
1364
+ }
1365
+ if (!s.signal_hash || !s.merkle_batch_id) {
1366
+ return res.json({
1367
+ verified: false,
1368
+ reason: 'Trade call recorded, awaiting next daily Merkle batch (00:05 UTC)',
1369
+ // PUBLIC allow-list only (no Phase-E keys). Calls-not-signals public names + existing render-compat names.
1370
+ signal: { id: s.id, coin: s.coin, call: s.signal, direction: s.signal, confidence: s.confidence, timeframe: s.timeframe, exchange: s.exchange, regime: s.regime },
1371
+ });
1372
+ }
1373
+ const proof = typeof s.merkle_proof === 'string' ? JSON.parse(s.merkle_proof) : s.merkle_proof;
1374
+ const isValid = (0, merkle_js_1.verifyProof)(s.signal_hash, proof, s.merkle_root);
1375
+ return res.json({
1376
+ verified: isValid,
1377
+ signal: {
1378
+ id: s.id, coin: s.coin, call: s.signal, direction: s.signal, confidence: s.confidence,
1379
+ timeframe: s.timeframe, exchange: s.exchange, regime: s.regime,
1380
+ price_at_call: s.price_at_signal, price: s.price_at_signal, timestamp: s.created_at, hash: s.signal_hash,
1381
+ },
1382
+ batch: {
1383
+ id: s.merkle_batch_id, root: s.merkle_root, signalCount: s.signal_count,
1384
+ txHash: s.tx_hash, blockNumber: s.block_number, publishedAt: s.published_at,
1385
+ basescanUrl: `https://basescan.org/tx/${s.tx_hash}`,
1386
+ },
1387
+ proof,
1388
+ contractAddress: MERKLE_CONTRACT_ADDR,
1389
+ howToVerify: 'Check the Merkle root on-chain at the contract address on Base. The call hash + proof should reconstruct the published root.',
1390
+ });
1391
+ }
1392
+ catch {
1393
+ return res.status(500).json({ error: 'Verification failed' });
1394
+ }
1395
+ }
1277
1396
  const signalId = parseInt(req.query.signalId);
1278
1397
  if (!signalId || isNaN(signalId)) {
1279
1398
  return res.status(400).json({ error: 'signalId required (integer)' });
@@ -1478,6 +1597,66 @@ async function startHttp() {
1478
1597
  res.status(500).json({ code: 'INTERNAL_ERROR', message: 'search engine path failed' });
1479
1598
  }
1480
1599
  });
1600
+ // ── POWER-USER-OUTREACH-W1-V2 (2026-05-28): /api/signup-email ──
1601
+ // Free-tier email opt-in capture from /welcome paywall CTA. Distinct from
1602
+ // GET /signup (Stripe Checkout redirect for paid tiers). Insert idempotent
1603
+ // via signup_emails.email UNIQUE constraint + processed_signup_email_events
1604
+ // claim. Confirmation email fire-and-forget so a Resend outage never 500s
1605
+ // the request. Public-shape: see audits/signup-email-shape-snapshot-2026-05-28.json
1606
+ // CALL-REGIME-WEBHOOK-LAYER-W1 (2026-05-29): outbound webhook subscription API
1607
+ // (POST/GET/DELETE /api/webhooks + POST /api/webhooks/:id/test). Universal
1608
+ // access gated only by the monthly call quota; ships dark — the delivery worker
1609
+ // only runs when WEBHOOK_DELIVERY_ENABLED=true (registration routes are always
1610
+ // mounted so subscribers can pre-register, but nothing is delivered until the
1611
+ // flag is on).
1612
+ (0, webhook_api_js_1.registerWebhookRoutes)(app);
1613
+ app.post('/api/signup-email', express.json({ limit: '2kb' }), async (req, res) => {
1614
+ try {
1615
+ const body = (req.body ?? {});
1616
+ const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
1617
+ const source = typeof body.source === 'string' ? body.source : 'welcome-paywall';
1618
+ const optinConsent = body.optin_consent === true;
1619
+ if (!email || !stripe_js_1.EMAIL_RE.test(email) || email.length > 254) {
1620
+ return res.status(400).json({ ok: false, error: 'invalid_email' });
1621
+ }
1622
+ if (!optinConsent) {
1623
+ return res.status(400).json({ ok: false, error: 'consent_required' });
1624
+ }
1625
+ const allowedSources = new Set(['welcome-paywall', 'outreach-reply', 'manual']);
1626
+ const safeSource = allowedSources.has(source) ? source : 'welcome-paywall';
1627
+ const claim = await (0, signup_emails_store_js_1.tryClaimSignupEmailEvent)(email, 'optin');
1628
+ const result = await (0, signup_emails_store_js_1.upsertSignupEmail)({
1629
+ email,
1630
+ source: safeSource,
1631
+ optin_consent: true,
1632
+ });
1633
+ const optinAt = new Date().toISOString();
1634
+ // Fire-and-forget confirmation email. Only send on a fresh claim — if a
1635
+ // retry hits within the same second, the claim returns false and we skip
1636
+ // re-sending (caller protection). Resend outage logs but does not 500.
1637
+ if (claim.claimed) {
1638
+ (0, email_js_1.sendOptinConfirmationEmail)(email)
1639
+ .then(async (sent) => {
1640
+ if (sent?.id) {
1641
+ await (0, signup_emails_store_js_1.markConfirmationSent)(email);
1642
+ console.log(`[/api/signup-email] confirmation sent to ${email[0]}***@*** id=${sent.id}`);
1643
+ }
1644
+ })
1645
+ .catch((err) => {
1646
+ console.error(`[/api/signup-email] confirmation send failed: ${err instanceof Error ? err.message : err}`);
1647
+ });
1648
+ }
1649
+ return res.status(200).json({
1650
+ ok: true,
1651
+ optin_at: optinAt,
1652
+ inserted: result.inserted,
1653
+ });
1654
+ }
1655
+ catch (err) {
1656
+ console.error(`[/api/signup-email] internal error: ${err instanceof Error ? err.message : err}`);
1657
+ return res.status(500).json({ ok: false, error: 'internal_error' });
1658
+ }
1659
+ });
1481
1660
  // ── AV-CHAT-MCP-W1 (C3, 2026-05-18): /api/chat HTTP endpoint ──
1482
1661
  // LLM-synthesized answer with citations. Quota tracked separately from
1483
1662
  // tool quotas via ChatRateLimit + chat_usage_monthly table. Falls back
@@ -1604,7 +1783,7 @@ async function startHttp() {
1604
1783
  if (!apiKey) {
1605
1784
  return res.status(400).json({ error: 'api_key_required' });
1606
1785
  }
1607
- const result = await (0, stripe_js_1.validateApiKey)(apiKey);
1786
+ const result = await (0, stripe_js_2.validateApiKey)(apiKey);
1608
1787
  if (!result.valid || !result.tier) {
1609
1788
  return res.status(404).json({ valid: false });
1610
1789
  }
@@ -1649,6 +1828,34 @@ async function startHttp() {
1649
1828
  catch { /* best-effort */ }
1650
1829
  }
1651
1830
  }
1831
+ // TG-BROADCAST-STACK-W1 CH6 (2026-05-28): track-token capture for the
1832
+ // /unlock_premium_alerts npm-install verification path β. Header
1833
+ // `X-AlgoVault-Track-Token` (set by stdio-client wrapper) takes
1834
+ // precedence over `--track-token=` argv (process-wide fallback).
1835
+ // Idempotent per (session_id, token); first tools/call emits one
1836
+ // funnel_events row, subsequent calls suppressed. The bot's */10 cron
1837
+ // polls funnel_events for matching tokens. Fire-and-forget; non-blocking.
1838
+ if (req.method === 'POST' && req.body && typeof req.body === 'object' && license.tier !== 'internal') {
1839
+ const body = req.body;
1840
+ if (body.method === 'tools/call' && typeof body.params?.name === 'string') {
1841
+ const trackToken = (0, track_token_js_1.resolveTrackTokenForRequest)(req.headers);
1842
+ if (trackToken && (0, track_token_js_1.shouldEmitForRequest)(sessionId ?? null, trackToken)) {
1843
+ try {
1844
+ (0, performance_db_js_2.recordFunnelEvent)({
1845
+ eventType: 'first_tool_call_with_track_token',
1846
+ sessionId: sessionId ?? null,
1847
+ licenseTier: license.tier,
1848
+ meta: {
1849
+ track_token: trackToken,
1850
+ tool_name: body.params.name,
1851
+ source: (req.headers['x-algovault-track-token'] ? 'header' : 'argv'),
1852
+ },
1853
+ });
1854
+ }
1855
+ catch { /* best-effort; never blocks request */ }
1856
+ }
1857
+ }
1858
+ }
1652
1859
  // Run the entire request handling inside AsyncLocalStorage context
1653
1860
  // so tool handlers read the correct per-request license
1654
1861
  await license_js_1.requestContext.run({ license, sessionId, ipHash }, async () => {
@@ -1725,6 +1932,15 @@ async function startHttp() {
1725
1932
  console.log('[backfill] Auto-backfill enabled: every 5 minutes');
1726
1933
  setTimeout(() => (0, signal_performance_js_1.runBackfill)().catch(() => { }), 10_000); // first run after 10s
1727
1934
  setInterval(() => (0, signal_performance_js_1.runBackfill)().catch(() => { }), 300_000); // then every 5 min
1935
+ // CALL-REGIME-WEBHOOK-LAYER-W1 (2026-05-29): outbound webhook delivery worker.
1936
+ // Ships DARK — only starts when WEBHOOK_DELIVERY_ENABLED=true. Flag-off = zero
1937
+ // new behavior (worker never starts; the post-insert detection hook in
1938
+ // recordSignal is also flag-gated). Registration routes stay mounted either
1939
+ // way so subscribers can pre-register. Mirrors the backfill setInterval above.
1940
+ if (process.env.WEBHOOK_DELIVERY_ENABLED === 'true') {
1941
+ console.log('[webhook-delivery] WEBHOOK_DELIVERY_ENABLED=true — starting outbound delivery worker');
1942
+ (0, webhook_delivery_js_1.startDeliveryWorker)();
1943
+ }
1728
1944
  // LATENCY-W1 C3: background grid warmer.
1729
1945
  // Pre-empts the 60s GRID_TTL_MS so user-facing get_trade_signal calls
1730
1946
  // ALWAYS hit warm cache (cuts p95 from ~27s → <2s; cache-miss tail
@@ -2957,6 +3173,10 @@ function getSignupPageHtml() {
2957
3173
  </html>`;
2958
3174
  }
2959
3175
  // ── Entry Point ──
3176
+ // TG-BROADCAST-STACK-W1 CH6 (2026-05-28): capture `--track-token=` from
3177
+ // process.argv at startup (no-op if absent). Used by the /unlock_premium_alerts
3178
+ // viral mechanic — see src/lib/track-token.ts for full semantics.
3179
+ (0, track_token_js_1.captureArgvTrackToken)();
2960
3180
  const transport = (process.env.TRANSPORT || 'http').toLowerCase();
2961
3181
  if (transport === 'stdio') {
2962
3182
  startStdio().catch((err) => {