caisson-cli 0.0.0-stage → 0.2.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 (215) hide show
  1. package/README.math-mvp.md +28 -0
  2. package/README.md +56 -3
  3. package/dist/admin/adminRoutes.d.ts +10 -0
  4. package/dist/admin/adminRoutes.js +194 -0
  5. package/dist/admin/adminRoutes.js.map +1 -0
  6. package/dist/admin/index.d.ts +2 -0
  7. package/dist/admin/index.js +4 -0
  8. package/dist/admin/index.js.map +1 -0
  9. package/dist/admin/workspaceAdmin.d.ts +417 -0
  10. package/dist/admin/workspaceAdmin.js +569 -0
  11. package/dist/admin/workspaceAdmin.js.map +1 -0
  12. package/dist/analytics/index.d.ts +1 -0
  13. package/dist/analytics/index.js +3 -0
  14. package/dist/analytics/index.js.map +1 -0
  15. package/dist/analytics/metrics.d.ts +105 -0
  16. package/dist/analytics/metrics.js +837 -0
  17. package/dist/analytics/metrics.js.map +1 -0
  18. package/dist/audit/index.d.ts +4 -0
  19. package/dist/audit/index.js +6 -0
  20. package/dist/audit/index.js.map +1 -0
  21. package/dist/audit/pipeline.d.ts +90 -0
  22. package/dist/audit/pipeline.js +424 -0
  23. package/dist/audit/pipeline.js.map +1 -0
  24. package/dist/audit/receiptSchema.d.ts +441 -0
  25. package/dist/audit/receiptSchema.js +208 -0
  26. package/dist/audit/receiptSchema.js.map +1 -0
  27. package/dist/audit/stageA.d.ts +50 -0
  28. package/dist/audit/stageA.js +218 -0
  29. package/dist/audit/stageA.js.map +1 -0
  30. package/dist/audit/stageB.d.ts +48 -0
  31. package/dist/audit/stageB.js +113 -0
  32. package/dist/audit/stageB.js.map +1 -0
  33. package/dist/auth/agentAuth.d.ts +28 -0
  34. package/dist/auth/agentAuth.js +88 -0
  35. package/dist/auth/agentAuth.js.map +1 -0
  36. package/dist/auth/agentCardSigner.d.ts +55 -0
  37. package/dist/auth/agentCardSigner.js +188 -0
  38. package/dist/auth/agentCardSigner.js.map +1 -0
  39. package/dist/billing/billingRoutes.d.ts +11 -0
  40. package/dist/billing/billingRoutes.js +303 -0
  41. package/dist/billing/billingRoutes.js.map +1 -0
  42. package/dist/billing/bountyRoutes.d.ts +9 -0
  43. package/dist/billing/bountyRoutes.js +332 -0
  44. package/dist/billing/bountyRoutes.js.map +1 -0
  45. package/dist/billing/index.d.ts +3 -0
  46. package/dist/billing/index.js +4 -0
  47. package/dist/billing/index.js.map +1 -0
  48. package/dist/billing/subscriptions.d.ts +226 -0
  49. package/dist/billing/subscriptions.js +673 -0
  50. package/dist/billing/subscriptions.js.map +1 -0
  51. package/dist/cli/caissonCli.d.ts +15 -0
  52. package/dist/cli/caissonCli.js +528 -0
  53. package/dist/cli/caissonCli.js.map +1 -0
  54. package/dist/cli/doctor.d.ts +31 -0
  55. package/dist/cli/doctor.js +321 -0
  56. package/dist/cli/doctor.js.map +1 -0
  57. package/dist/cli/inviteCard.d.ts +25 -0
  58. package/dist/cli/inviteCard.js +111 -0
  59. package/dist/cli/inviteCard.js.map +1 -0
  60. package/dist/cli/mcpProxy.d.ts +36 -0
  61. package/dist/cli/mcpProxy.js +292 -0
  62. package/dist/cli/mcpProxy.js.map +1 -0
  63. package/dist/config.d.ts +19 -0
  64. package/dist/config.js +28 -0
  65. package/dist/config.js.map +1 -0
  66. package/dist/db/adapter.d.ts +210 -0
  67. package/dist/db/adapter.js +769 -0
  68. package/dist/db/adapter.js.map +1 -0
  69. package/dist/db/sqlite.d.ts +7 -0
  70. package/dist/db/sqlite.js +60 -0
  71. package/dist/db/sqlite.js.map +1 -0
  72. package/dist/db/telemetry.d.ts +11 -0
  73. package/dist/db/telemetry.js +9 -0
  74. package/dist/db/telemetry.js.map +1 -0
  75. package/dist/economy/bountyEngine.d.ts +248 -0
  76. package/dist/economy/bountyEngine.js +836 -0
  77. package/dist/economy/bountyEngine.js.map +1 -0
  78. package/dist/economy/index.d.ts +5 -0
  79. package/dist/economy/index.js +6 -0
  80. package/dist/economy/index.js.map +1 -0
  81. package/dist/economy/scLedger.d.ts +183 -0
  82. package/dist/economy/scLedger.js +528 -0
  83. package/dist/economy/scLedger.js.map +1 -0
  84. package/dist/economy/scMinting.d.ts +177 -0
  85. package/dist/economy/scMinting.js +659 -0
  86. package/dist/economy/scMinting.js.map +1 -0
  87. package/dist/economy/scSinks.d.ts +135 -0
  88. package/dist/economy/scSinks.js +314 -0
  89. package/dist/economy/scSinks.js.map +1 -0
  90. package/dist/economy/usdLedger.d.ts +211 -0
  91. package/dist/economy/usdLedger.js +604 -0
  92. package/dist/economy/usdLedger.js.map +1 -0
  93. package/dist/mcp/handlers.d.ts +136 -0
  94. package/dist/mcp/handlers.js +809 -0
  95. package/dist/mcp/handlers.js.map +1 -0
  96. package/dist/mcp/httpServer.d.ts +29 -0
  97. package/dist/mcp/httpServer.js +384 -0
  98. package/dist/mcp/httpServer.js.map +1 -0
  99. package/dist/mcp/serverFactory.d.ts +4 -0
  100. package/dist/mcp/serverFactory.js +53 -0
  101. package/dist/mcp/serverFactory.js.map +1 -0
  102. package/dist/mcp/stdioServer.d.ts +2 -0
  103. package/dist/mcp/stdioServer.js +24 -0
  104. package/dist/mcp/stdioServer.js.map +1 -0
  105. package/dist/mcp/toolMetadata.d.ts +15 -0
  106. package/dist/mcp/toolMetadata.js +73 -0
  107. package/dist/mcp/toolMetadata.js.map +1 -0
  108. package/dist/memo/artifactIndex.d.ts +51 -0
  109. package/dist/memo/artifactIndex.js +162 -0
  110. package/dist/memo/artifactIndex.js.map +1 -0
  111. package/dist/memo/dependencyBundle.d.ts +33 -0
  112. package/dist/memo/dependencyBundle.js +86 -0
  113. package/dist/memo/dependencyBundle.js.map +1 -0
  114. package/dist/memo/embeddings.d.ts +110 -0
  115. package/dist/memo/embeddings.js +672 -0
  116. package/dist/memo/embeddings.js.map +1 -0
  117. package/dist/packs/foundryEvm.d.ts +21 -0
  118. package/dist/packs/foundryEvm.js +274 -0
  119. package/dist/packs/foundryEvm.js.map +1 -0
  120. package/dist/packs/index.d.ts +8 -0
  121. package/dist/packs/index.js +19 -0
  122. package/dist/packs/index.js.map +1 -0
  123. package/dist/packs/mathLean4.d.ts +7 -0
  124. package/dist/packs/mathLean4.js +145 -0
  125. package/dist/packs/mathLean4.js.map +1 -0
  126. package/dist/packs/rustKani.d.ts +17 -0
  127. package/dist/packs/rustKani.js +257 -0
  128. package/dist/packs/rustKani.js.map +1 -0
  129. package/dist/packs/sdk.d.ts +314 -0
  130. package/dist/packs/sdk.js +271 -0
  131. package/dist/packs/sdk.js.map +1 -0
  132. package/dist/preflight/leanTripwire.d.ts +19 -0
  133. package/dist/preflight/leanTripwire.js +105 -0
  134. package/dist/preflight/leanTripwire.js.map +1 -0
  135. package/dist/storage/blobStore.d.ts +11 -0
  136. package/dist/storage/blobStore.js +39 -0
  137. package/dist/storage/blobStore.js.map +1 -0
  138. package/dist/storage/gitStore.d.ts +68 -0
  139. package/dist/storage/gitStore.js +228 -0
  140. package/dist/storage/gitStore.js.map +1 -0
  141. package/dist/types/errors.d.ts +16 -0
  142. package/dist/types/errors.js +23 -0
  143. package/dist/types/errors.js.map +1 -0
  144. package/dist/types/schemas.d.ts +453 -0
  145. package/dist/types/schemas.js +197 -0
  146. package/dist/types/schemas.js.map +1 -0
  147. package/dist/web/discoveryRoutes.d.ts +24 -0
  148. package/dist/web/discoveryRoutes.js +532 -0
  149. package/dist/web/discoveryRoutes.js.map +1 -0
  150. package/dist/web/docsRoutes.d.ts +14 -0
  151. package/dist/web/docsRoutes.js +451 -0
  152. package/dist/web/docsRoutes.js.map +1 -0
  153. package/dist/web/explorer/dagLayout.d.ts +41 -0
  154. package/dist/web/explorer/dagLayout.js +183 -0
  155. package/dist/web/explorer/dagLayout.js.map +1 -0
  156. package/dist/web/explorer/index.d.ts +45 -0
  157. package/dist/web/explorer/index.js +512 -0
  158. package/dist/web/explorer/index.js.map +1 -0
  159. package/dist/web/explorer/renderers.d.ts +35 -0
  160. package/dist/web/explorer/renderers.js +399 -0
  161. package/dist/web/explorer/renderers.js.map +1 -0
  162. package/dist/web/landing.d.ts +36 -0
  163. package/dist/web/landing.js +532 -0
  164. package/dist/web/landing.js.map +1 -0
  165. package/dist/web/onboardingRoutes.d.ts +96 -0
  166. package/dist/web/onboardingRoutes.js +629 -0
  167. package/dist/web/onboardingRoutes.js.map +1 -0
  168. package/dist/web/repoBrowser.d.ts +19 -0
  169. package/dist/web/repoBrowser.js +128 -0
  170. package/dist/web/repoBrowser.js.map +1 -0
  171. package/dist/worker/executionAdapter.d.ts +14 -0
  172. package/dist/worker/executionAdapter.js +162 -0
  173. package/dist/worker/executionAdapter.js.map +1 -0
  174. package/dist/worker/finalize.d.ts +21 -0
  175. package/dist/worker/finalize.js +146 -0
  176. package/dist/worker/finalize.js.map +1 -0
  177. package/dist/worker/firecrackerAdapter.d.ts +180 -0
  178. package/dist/worker/firecrackerAdapter.js +421 -0
  179. package/dist/worker/firecrackerAdapter.js.map +1 -0
  180. package/dist/worker/loop.d.ts +56 -0
  181. package/dist/worker/loop.js +239 -0
  182. package/dist/worker/loop.js.map +1 -0
  183. package/dist/worker/postMergeSync.d.ts +17 -0
  184. package/dist/worker/postMergeSync.js +52 -0
  185. package/dist/worker/postMergeSync.js.map +1 -0
  186. package/dist/worker/prepareInput.d.ts +41 -0
  187. package/dist/worker/prepareInput.js +130 -0
  188. package/dist/worker/prepareInput.js.map +1 -0
  189. package/dist/worker/queue.d.ts +83 -0
  190. package/dist/worker/queue.js +278 -0
  191. package/dist/worker/queue.js.map +1 -0
  192. package/dist/worker/sandbox.d.ts +2 -0
  193. package/dist/worker/sandbox.js +3 -0
  194. package/dist/worker/sandbox.js.map +1 -0
  195. package/dist/worker/webhook.d.ts +14 -0
  196. package/dist/worker/webhook.js +110 -0
  197. package/dist/worker/webhook.js.map +1 -0
  198. package/migrations/001_init.sql +193 -0
  199. package/migrations/002_epic3_scale.sql +34 -0
  200. package/migrations/003_swarm_credits.sql +153 -0
  201. package/migrations/004_usd_bounties.sql +216 -0
  202. package/migrations_pg/001_init.sql +229 -0
  203. package/migrations_pg/002_multitenant_rls.sql +63 -0
  204. package/migrations_pg/003_swarm_credits.sql +135 -0
  205. package/migrations_pg/004_usd_bounties.sql +201 -0
  206. package/package.json +58 -6
  207. package/packs/foundry-evm/pack.json +60 -0
  208. package/packs/foundry-evm/verifier/Dockerfile +9 -0
  209. package/packs/foundry-evm/verifier/run.py +160 -0
  210. package/packs/math-lean4/pack.json +68 -0
  211. package/packs/rust-kani/pack.json +53 -0
  212. package/packs/rust-kani/verifier/Dockerfile +7 -0
  213. package/packs/rust-kani/verifier/run.py +159 -0
  214. package/public/.well-known/agent-card.json +162 -0
  215. package/public/llms.txt +40 -0
@@ -0,0 +1,673 @@
1
+ // src/billing/subscriptions.ts
2
+ // Pro Tier Plans & Stripe Billing Integration ($29–$99/mo) (Epic 4 / E4-4)
3
+ // Reference: docs/01-vision-strategy-business-plan.md §6 & docs/08 §2
4
+ //
5
+ // Unlocks:
6
+ // - Private airlocked workspaces (Free: 0, Pro Starter $29/mo: 3, Pro Team $99/mo: 20, Enterprise: 1000)
7
+ // - Higher hourly verification quotas (Free: 20/hr, Pro Starter: 120/hr, Pro Team: 500/hr, Enterprise: 2000/hr)
8
+ // - Priority worker lanes (Pro Starter: priority 50 / cap 6; Pro Team: priority 100 / cap 12)
9
+ //
10
+ // Dual-Ledger Firewall Note:
11
+ // Stripe subscriptions pay for SaaS workspace/compute entitlements in USD and NEVER mint,
12
+ // sell, or convert Swarm Credits (SC).
13
+ import crypto from 'node:crypto';
14
+ import { newId, nowIso, sha256Hex } from '../db/sqlite.js';
15
+ import { centsToUsd, depositUsdCredits, MAX_USD_DEPOSIT_CENTS, MIN_USD_DEPOSIT_CENTS, } from '../economy/usdLedger.js';
16
+ import { SwarmError } from '../types/errors.js';
17
+ export const PLAN_CATALOG = {
18
+ free: {
19
+ tier: 'free',
20
+ name: 'Community Free',
21
+ monthly_price_usd_cents: 0,
22
+ monthly_price_usd: 0,
23
+ private_workspace_limit: 0,
24
+ hourly_verification_quota: 20,
25
+ worker_priority: 0,
26
+ concurrency_cap: 2,
27
+ rate_limit_tier: 'standard',
28
+ default_stripe_price_env: null,
29
+ features: [
30
+ 'Unlimited public verifier-gated workspaces',
31
+ '20 server verifications/hour',
32
+ 'Standard worker queue lane (concurrency cap 2)',
33
+ 'Earn & barter Swarm Credits on audited public workspaces',
34
+ ],
35
+ },
36
+ pro_starter: {
37
+ tier: 'pro_starter',
38
+ name: 'Pro Starter',
39
+ monthly_price_usd_cents: 2900,
40
+ monthly_price_usd: 29,
41
+ private_workspace_limit: 3,
42
+ hourly_verification_quota: 120,
43
+ worker_priority: 50,
44
+ concurrency_cap: 6,
45
+ rate_limit_tier: 'pro',
46
+ default_stripe_price_env: 'STRIPE_PRICE_PRO_STARTER',
47
+ features: [
48
+ 'Up to 3 private airlocked workspaces',
49
+ '120 server verifications/hour (6x Free)',
50
+ 'Priority worker lane (concurrency cap 6)',
51
+ 'Private zero-sum Swarm Credit transfers',
52
+ ],
53
+ },
54
+ pro_team: {
55
+ tier: 'pro_team',
56
+ name: 'Pro Team',
57
+ monthly_price_usd_cents: 9900,
58
+ monthly_price_usd: 99,
59
+ private_workspace_limit: 20,
60
+ hourly_verification_quota: 500,
61
+ worker_priority: 100,
62
+ concurrency_cap: 12,
63
+ rate_limit_tier: 'pro_team',
64
+ default_stripe_price_env: 'STRIPE_PRICE_PRO_TEAM',
65
+ features: [
66
+ 'Up to 20 private airlocked workspaces',
67
+ '500 server verifications/hour (25x Free)',
68
+ 'Top-priority Pro worker lane (concurrency cap 12)',
69
+ 'Multi-agent team coordination & private zero-sum SC transfers',
70
+ ],
71
+ },
72
+ enterprise: {
73
+ tier: 'enterprise',
74
+ name: 'Enterprise Airlocked Swarm',
75
+ monthly_price_usd_cents: 0,
76
+ monthly_price_usd: 0,
77
+ private_workspace_limit: 1000,
78
+ hourly_verification_quota: 2000,
79
+ worker_priority: 200,
80
+ concurrency_cap: 24,
81
+ rate_limit_tier: 'trusted',
82
+ default_stripe_price_env: 'STRIPE_PRICE_ENTERPRISE',
83
+ features: [
84
+ 'Airlocked VPC/on-prem private workspaces',
85
+ '2,000+ server verifications/hour',
86
+ 'Dedicated priority worker fleet',
87
+ ],
88
+ },
89
+ };
90
+ /**
91
+ * Zero-dependency Stripe REST API client using Node 22 built-in `fetch`.
92
+ */
93
+ export class HttpStripeClient {
94
+ secretKey;
95
+ apiBase;
96
+ constructor(secretKey, apiBase = 'https://api.stripe.com/v1') {
97
+ this.secretKey = secretKey;
98
+ this.apiBase = apiBase;
99
+ if (!secretKey.trim()) {
100
+ throw new SwarmError('INVALID_INPUT', 'Stripe secret key is required');
101
+ }
102
+ }
103
+ async postForm(endpoint, fields) {
104
+ const body = new URLSearchParams(fields);
105
+ const res = await fetch(`${this.apiBase}${endpoint}`, {
106
+ method: 'POST',
107
+ headers: {
108
+ Authorization: `Bearer ${this.secretKey}`,
109
+ 'Content-Type': 'application/x-www-form-urlencoded',
110
+ },
111
+ body: body.toString(),
112
+ });
113
+ const text = await res.text();
114
+ let parsed;
115
+ try {
116
+ parsed = JSON.parse(text);
117
+ }
118
+ catch {
119
+ parsed = { raw: text };
120
+ }
121
+ if (!res.ok) {
122
+ throw new SwarmError('INVALID_INPUT', `Stripe API error (${res.status}): ${parsed?.error?.message ?? text.slice(0, 300)}`);
123
+ }
124
+ return parsed;
125
+ }
126
+ async createCheckoutSession(params) {
127
+ const fields = {
128
+ mode: 'subscription',
129
+ success_url: params.successUrl,
130
+ cancel_url: params.cancelUrl,
131
+ client_reference_id: params.operatorId,
132
+ 'line_items[0][price]': params.priceId,
133
+ 'line_items[0][quantity]': '1',
134
+ 'metadata[operator_id]': params.operatorId,
135
+ 'metadata[plan_tier]': params.planTier,
136
+ 'subscription_data[metadata][operator_id]': params.operatorId,
137
+ 'subscription_data[metadata][plan_tier]': params.planTier,
138
+ };
139
+ if (params.customerId) {
140
+ fields.customer = params.customerId;
141
+ }
142
+ else if (params.customerEmail) {
143
+ fields.customer_email = params.customerEmail;
144
+ }
145
+ const res = await this.postForm('/checkout/sessions', fields);
146
+ return { id: res.id, url: res.url, customer_id: res.customer ?? null };
147
+ }
148
+ async createBillingPortalSession(params) {
149
+ const res = await this.postForm('/billing_portal/sessions', {
150
+ customer: params.customerId,
151
+ return_url: params.returnUrl,
152
+ });
153
+ return { id: res.id, url: res.url };
154
+ }
155
+ async createUsdTopupCheckoutSession(params) {
156
+ const fields = {
157
+ mode: 'payment',
158
+ success_url: params.successUrl,
159
+ cancel_url: params.cancelUrl,
160
+ client_reference_id: params.operatorId,
161
+ 'line_items[0][price_data][currency]': 'usd',
162
+ 'line_items[0][price_data][unit_amount]': String(params.amountCents),
163
+ 'line_items[0][price_data][product_data][name]': 'Caisson Prepaid USD Credits (Bounty & Staking Balance)',
164
+ 'line_items[0][quantity]': '1',
165
+ 'metadata[operator_id]': params.operatorId,
166
+ 'metadata[purpose]': 'usd_prepaid_topup',
167
+ 'metadata[amount_cents]': String(params.amountCents),
168
+ 'payment_intent_data[metadata][operator_id]': params.operatorId,
169
+ 'payment_intent_data[metadata][purpose]': 'usd_prepaid_topup',
170
+ };
171
+ if (params.customerId) {
172
+ fields.customer = params.customerId;
173
+ }
174
+ else if (params.customerEmail) {
175
+ fields.customer_email = params.customerEmail;
176
+ }
177
+ const res = await this.postForm('/checkout/sessions', fields);
178
+ return { id: res.id, url: res.url, customer_id: res.customer ?? null };
179
+ }
180
+ }
181
+ /**
182
+ * Generates a valid Stripe `Stripe-Signature` header (`t=<ts>,v1=<hmac_sha256>`).
183
+ * Useful for testing and webhook verification harnesses.
184
+ */
185
+ export function signStripeWebhookPayload(rawPayload, webhookSecret, timestampSeconds = Math.floor(Date.now() / 1000)) {
186
+ const payloadStr = Buffer.isBuffer(rawPayload) ? rawPayload.toString('utf8') : rawPayload;
187
+ const sig = crypto
188
+ .createHmac('sha256', webhookSecret)
189
+ .update(`${timestampSeconds}.${payloadStr}`)
190
+ .digest('hex');
191
+ return `t=${timestampSeconds},v1=${sig}`;
192
+ }
193
+ /**
194
+ * Verifies a Stripe `Stripe-Signature` header using constant-time HMAC-SHA256 comparison
195
+ * and replay-window timestamp enforcement (default 300s).
196
+ */
197
+ export function verifyStripeWebhookSignature(rawPayload, signatureHeader, webhookSecret, opts = {}) {
198
+ if (!signatureHeader?.trim()) {
199
+ throw new SwarmError('UNAUTHORIZED', 'Missing Stripe-Signature header');
200
+ }
201
+ if (!webhookSecret?.trim()) {
202
+ throw new SwarmError('UNAUTHORIZED', 'Stripe webhook secret is not configured');
203
+ }
204
+ let timestamp = null;
205
+ const v1Sigs = [];
206
+ for (const part of signatureHeader.split(',')) {
207
+ const idx = part.indexOf('=');
208
+ if (idx <= 0)
209
+ continue;
210
+ const key = part.slice(0, idx).trim();
211
+ const val = part.slice(idx + 1).trim();
212
+ if (key === 't') {
213
+ const parsed = Number(val);
214
+ if (Number.isFinite(parsed))
215
+ timestamp = parsed;
216
+ }
217
+ else if (key === 'v1' && /^[a-f0-9]{64}$/i.test(val)) {
218
+ v1Sigs.push(val.toLowerCase());
219
+ }
220
+ }
221
+ if (timestamp === null || v1Sigs.length === 0) {
222
+ throw new SwarmError('UNAUTHORIZED', 'Malformed Stripe-Signature header');
223
+ }
224
+ const tolerance = opts.toleranceSeconds ?? 300;
225
+ const nowSec = opts.nowSeconds ?? Math.floor(Date.now() / 1000);
226
+ if (tolerance > 0 && Math.abs(nowSec - timestamp) > tolerance) {
227
+ throw new SwarmError('UNAUTHORIZED', 'Stripe webhook signature timestamp outside tolerance window');
228
+ }
229
+ const payloadStr = Buffer.isBuffer(rawPayload) ? rawPayload.toString('utf8') : rawPayload;
230
+ const expectedHex = crypto
231
+ .createHmac('sha256', webhookSecret)
232
+ .update(`${timestamp}.${payloadStr}`)
233
+ .digest('hex');
234
+ const expectedBuf = Buffer.from(expectedHex, 'hex');
235
+ const matched = v1Sigs.some((sig) => {
236
+ const providedBuf = Buffer.from(sig, 'hex');
237
+ return providedBuf.length === expectedBuf.length && crypto.timingSafeEqual(providedBuf, expectedBuf);
238
+ });
239
+ if (!matched) {
240
+ throw new SwarmError('UNAUTHORIZED', 'Invalid Stripe webhook signature');
241
+ }
242
+ }
243
+ function hydrateSubscription(row) {
244
+ return {
245
+ id: String(row.id),
246
+ operator_id: String(row.operator_id),
247
+ plan_tier: row.plan_tier,
248
+ monthly_price_usd_cents: Number(row.monthly_price_usd_cents),
249
+ status: row.status,
250
+ stripe_customer_id: row.stripe_customer_id ? String(row.stripe_customer_id) : null,
251
+ stripe_subscription_id: row.stripe_subscription_id ? String(row.stripe_subscription_id) : null,
252
+ stripe_price_id: row.stripe_price_id ? String(row.stripe_price_id) : null,
253
+ current_period_start: row.current_period_start ? String(row.current_period_start) : null,
254
+ current_period_end: row.current_period_end ? String(row.current_period_end) : null,
255
+ cancel_at_period_end: Number(row.cancel_at_period_end) === 1,
256
+ private_workspace_limit: Number(row.private_workspace_limit),
257
+ hourly_verification_quota: Number(row.hourly_verification_quota),
258
+ worker_priority: Number(row.worker_priority),
259
+ concurrency_cap: Number(row.concurrency_cap),
260
+ created_at: String(row.created_at),
261
+ updated_at: String(row.updated_at),
262
+ };
263
+ }
264
+ /** Resolves a Stripe Price ID to a Caisson PlanTier using env vars or explicit priceMap. */
265
+ export function resolvePlanTierFromPriceId(priceId, priceMap = {}) {
266
+ if (!priceId)
267
+ return null;
268
+ const starterPrice = priceMap.pro_starter ?? process.env.STRIPE_PRICE_PRO_STARTER ?? 'price_pro_starter_29';
269
+ const teamPrice = priceMap.pro_team ?? process.env.STRIPE_PRICE_PRO_TEAM ?? 'price_pro_team_99';
270
+ const entPrice = priceMap.enterprise ?? process.env.STRIPE_PRICE_ENTERPRISE;
271
+ if (priceId === starterPrice)
272
+ return 'pro_starter';
273
+ if (priceId === teamPrice)
274
+ return 'pro_team';
275
+ if (entPrice && priceId === entPrice)
276
+ return 'enterprise';
277
+ return null;
278
+ }
279
+ /** Resolves the configured Stripe Price ID for a paid plan tier. */
280
+ export function getStripePriceIdForPlan(planTier, priceMap = {}) {
281
+ if (priceMap[planTier])
282
+ return priceMap[planTier];
283
+ if (planTier === 'pro_starter')
284
+ return process.env.STRIPE_PRICE_PRO_STARTER ?? 'price_pro_starter_29';
285
+ if (planTier === 'pro_team')
286
+ return process.env.STRIPE_PRICE_PRO_TEAM ?? 'price_pro_team_99';
287
+ return process.env.STRIPE_PRICE_ENTERPRISE ?? 'price_enterprise_custom';
288
+ }
289
+ /** Returns an operator's stored subscription record, or null if on default Free tier. */
290
+ export function getOperatorSubscription(db, operatorId) {
291
+ const row = db
292
+ .prepare('SELECT * FROM operator_subscriptions WHERE operator_id = ?')
293
+ .get(operatorId);
294
+ return row ? hydrateSubscription(row) : null;
295
+ }
296
+ /**
297
+ * Computes effective runtime entitlements for an operator:
298
+ * - Active (`active` | `trialing`) subscriptions unlock private airlocked workspaces,
299
+ * higher hourly verification quotas, and priority worker lanes.
300
+ * - `past_due`, `canceled`, or `incomplete` subscriptions fall back to Free tier limits.
301
+ */
302
+ export function getOperatorEntitlements(db, operatorId) {
303
+ const sub = getOperatorSubscription(db, operatorId);
304
+ const isActive = Boolean(sub && (sub.status === 'active' || sub.status === 'trialing'));
305
+ const effectiveTier = isActive && sub ? sub.plan_tier : 'free';
306
+ const def = PLAN_CATALOG[effectiveTier];
307
+ const privRow = db
308
+ .prepare(`
309
+ SELECT COUNT(*) AS cnt
310
+ FROM workspaces
311
+ WHERE owner_operator_id = ? AND visibility = 'private'
312
+ `)
313
+ .get(operatorId);
314
+ const privateUsed = Number(privRow?.cnt ?? 0);
315
+ const privateLimit = isActive && sub ? sub.private_workspace_limit : def.private_workspace_limit;
316
+ return {
317
+ operator_id: operatorId,
318
+ plan_tier: effectiveTier,
319
+ status: sub?.status ?? 'active',
320
+ active: isActive || effectiveTier === 'free',
321
+ monthly_price_usd: def.monthly_price_usd,
322
+ private_workspace_limit: privateLimit,
323
+ private_workspaces_used: privateUsed,
324
+ can_create_private_workspace: privateLimit > 0 && privateUsed < privateLimit,
325
+ hourly_verification_quota: isActive && sub ? sub.hourly_verification_quota : def.hourly_verification_quota,
326
+ worker_priority: isActive && sub ? sub.worker_priority : def.worker_priority,
327
+ concurrency_cap: isActive && sub ? sub.concurrency_cap : def.concurrency_cap,
328
+ rate_limit_tier: def.rate_limit_tier,
329
+ };
330
+ }
331
+ /**
332
+ * Enforces that an operator has an active Pro/Enterprise plan with remaining private airlocked workspace capacity.
333
+ */
334
+ export function assertCanCreatePrivateWorkspace(db, operatorId) {
335
+ const ent = getOperatorEntitlements(db, operatorId);
336
+ if (!ent.can_create_private_workspace) {
337
+ throw new SwarmError('UNAUTHORIZED', ent.private_workspace_limit === 0
338
+ ? `Private airlocked workspaces require a Pro Starter ($29/mo) or Pro Team ($99/mo) plan (current plan: ${ent.plan_tier})`
339
+ : `Private workspace limit reached (${ent.private_workspaces_used}/${ent.private_workspace_limit} on ${ent.plan_tier} plan)`, false, {
340
+ plan_tier: ent.plan_tier,
341
+ private_workspaces_used: ent.private_workspaces_used,
342
+ private_workspace_limit: ent.private_workspace_limit,
343
+ upgrade_plans: ['pro_starter', 'pro_team'],
344
+ });
345
+ }
346
+ return ent;
347
+ }
348
+ /**
349
+ * Upserts an operator's subscription and synchronizes `agent_identities.rate_limit_tier`
350
+ * for all non-internal agents belonging to that operator so worker priority lanes and
351
+ * hourly quotas take effect immediately.
352
+ */
353
+ export function upsertOperatorSubscription(db, params) {
354
+ const ts = params.now ?? nowIso();
355
+ const def = PLAN_CATALOG[params.planTier];
356
+ if (!def) {
357
+ throw new SwarmError('INVALID_INPUT', `Unknown plan tier '${params.planTier}'`);
358
+ }
359
+ const isEntitled = params.status === 'active' || params.status === 'trialing';
360
+ const effectiveDef = isEntitled ? def : PLAN_CATALOG.free;
361
+ const tx = db.transaction(() => {
362
+ const existing = db
363
+ .prepare('SELECT id FROM operator_subscriptions WHERE operator_id = ?')
364
+ .get(params.operatorId);
365
+ const subId = existing?.id ?? newId('sub');
366
+ db.prepare(`
367
+ INSERT INTO operator_subscriptions (
368
+ id, operator_id, plan_tier, monthly_price_usd_cents, status,
369
+ stripe_customer_id, stripe_subscription_id, stripe_price_id,
370
+ current_period_start, current_period_end, cancel_at_period_end,
371
+ private_workspace_limit, hourly_verification_quota, worker_priority, concurrency_cap,
372
+ created_at, updated_at
373
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
374
+ ON CONFLICT(operator_id) DO UPDATE SET
375
+ plan_tier = excluded.plan_tier,
376
+ monthly_price_usd_cents = excluded.monthly_price_usd_cents,
377
+ status = excluded.status,
378
+ stripe_customer_id = COALESCE(excluded.stripe_customer_id, operator_subscriptions.stripe_customer_id),
379
+ stripe_subscription_id = COALESCE(excluded.stripe_subscription_id, operator_subscriptions.stripe_subscription_id),
380
+ stripe_price_id = COALESCE(excluded.stripe_price_id, operator_subscriptions.stripe_price_id),
381
+ current_period_start = COALESCE(excluded.current_period_start, operator_subscriptions.current_period_start),
382
+ current_period_end = COALESCE(excluded.current_period_end, operator_subscriptions.current_period_end),
383
+ cancel_at_period_end = excluded.cancel_at_period_end,
384
+ private_workspace_limit = excluded.private_workspace_limit,
385
+ hourly_verification_quota = excluded.hourly_verification_quota,
386
+ worker_priority = excluded.worker_priority,
387
+ concurrency_cap = excluded.concurrency_cap,
388
+ updated_at = excluded.updated_at
389
+ `).run(subId, params.operatorId, params.planTier, def.monthly_price_usd_cents, params.status, params.stripeCustomerId ?? null, params.stripeSubscriptionId ?? null, params.stripePriceId ?? null, params.currentPeriodStart ?? null, params.currentPeriodEnd ?? null, params.cancelAtPeriodEnd ? 1 : 0, effectiveDef.private_workspace_limit, effectiveDef.hourly_verification_quota, effectiveDef.worker_priority, effectiveDef.concurrency_cap, ts, ts);
390
+ // Sync non-internal agent rate_limit_tier for priority worker lanes & quotas
391
+ db.prepare(`
392
+ UPDATE agent_identities
393
+ SET rate_limit_tier = ?
394
+ WHERE operator_id = ? AND rate_limit_tier <> 'internal'
395
+ `).run(effectiveDef.rate_limit_tier, params.operatorId);
396
+ const row = db
397
+ .prepare('SELECT * FROM operator_subscriptions WHERE operator_id = ?')
398
+ .get(params.operatorId);
399
+ return hydrateSubscription(row);
400
+ });
401
+ return tx.immediate();
402
+ }
403
+ /** Creates a Stripe Checkout Session for an operator upgrading to `pro_starter` ($29/mo) or `pro_team` ($99/mo). */
404
+ export async function createProCheckoutSession(db, stripe, params) {
405
+ const existing = getOperatorSubscription(db, params.operatorId);
406
+ const priceId = getStripePriceIdForPlan(params.planTier, params.priceMap);
407
+ const session = await stripe.createCheckoutSession({
408
+ operatorId: params.operatorId,
409
+ planTier: params.planTier,
410
+ priceId,
411
+ customerId: existing?.stripe_customer_id ?? null,
412
+ customerEmail: params.customerEmail,
413
+ successUrl: params.successUrl,
414
+ cancelUrl: params.cancelUrl,
415
+ });
416
+ return {
417
+ session_id: session.id,
418
+ checkout_url: session.url,
419
+ plan_tier: params.planTier,
420
+ monthly_price_usd: PLAN_CATALOG[params.planTier].monthly_price_usd,
421
+ };
422
+ }
423
+ /** Creates a Stripe Checkout Session (`mode: 'payment'`) to top up an operator's Prepaid USD Credit balance (E5-1). */
424
+ export async function createPrepaidUsdTopupSession(db, stripe, params) {
425
+ if (!Number.isInteger(params.amountCents) || params.amountCents < MIN_USD_DEPOSIT_CENTS) {
426
+ throw new SwarmError('INVALID_INPUT', `Prepaid USD top-up must be an integer >= ${MIN_USD_DEPOSIT_CENTS} cents ($${centsToUsd(MIN_USD_DEPOSIT_CENTS).toFixed(2)})`);
427
+ }
428
+ if (params.amountCents > MAX_USD_DEPOSIT_CENTS) {
429
+ throw new SwarmError('INVALID_INPUT', `Prepaid USD top-up exceeds single-transaction ceiling (${MAX_USD_DEPOSIT_CENTS} cents)`);
430
+ }
431
+ if (!stripe.createUsdTopupCheckoutSession) {
432
+ throw new SwarmError('INVALID_INPUT', 'Configured Stripe client does not support Prepaid USD top-up sessions');
433
+ }
434
+ const existing = getOperatorSubscription(db, params.operatorId);
435
+ const session = await stripe.createUsdTopupCheckoutSession({
436
+ operatorId: params.operatorId,
437
+ amountCents: params.amountCents,
438
+ customerId: existing?.stripe_customer_id ?? null,
439
+ customerEmail: params.customerEmail,
440
+ successUrl: params.successUrl,
441
+ cancelUrl: params.cancelUrl,
442
+ });
443
+ return {
444
+ session_id: session.id,
445
+ checkout_url: session.url,
446
+ currency: 'USD',
447
+ amount_cents: params.amountCents,
448
+ amount_usd: centsToUsd(params.amountCents),
449
+ };
450
+ }
451
+ /** Creates a Stripe Billing Portal session for an operator with an existing Stripe customer ID. */
452
+ export async function createOperatorPortalSession(db, stripe, params) {
453
+ const sub = getOperatorSubscription(db, params.operatorId);
454
+ if (!sub?.stripe_customer_id) {
455
+ throw new SwarmError('NOT_FOUND', `No Stripe customer found for operator '${params.operatorId}'`);
456
+ }
457
+ const session = await stripe.createBillingPortalSession({
458
+ customerId: sub.stripe_customer_id,
459
+ returnUrl: params.returnUrl,
460
+ });
461
+ return { portal_url: session.url, session_id: session.id };
462
+ }
463
+ function unixToIso(sec) {
464
+ if (typeof sec !== 'number' || !Number.isFinite(sec))
465
+ return null;
466
+ return new Date(sec * 1000).toISOString();
467
+ }
468
+ function mapStripeStatus(raw) {
469
+ const s = String(raw ?? 'active');
470
+ if (s === 'active' || s === 'trialing' || s === 'past_due' || s === 'canceled' || s === 'incomplete') {
471
+ return s;
472
+ }
473
+ if (s === 'unpaid' || s === 'incomplete_expired')
474
+ return 'canceled';
475
+ return 'past_due';
476
+ }
477
+ function findOperatorByStripeIds(db, customerId, subscriptionId) {
478
+ if (subscriptionId) {
479
+ const row = db
480
+ .prepare('SELECT operator_id FROM operator_subscriptions WHERE stripe_subscription_id = ?')
481
+ .get(subscriptionId);
482
+ if (row)
483
+ return row.operator_id;
484
+ }
485
+ if (customerId) {
486
+ const row = db
487
+ .prepare('SELECT operator_id FROM operator_subscriptions WHERE stripe_customer_id = ?')
488
+ .get(customerId);
489
+ if (row)
490
+ return row.operator_id;
491
+ }
492
+ return null;
493
+ }
494
+ /**
495
+ * Verifies Stripe webhook signature, deduplicates via `billing_webhook_events`,
496
+ * and applies subscription lifecycle transitions atomically.
497
+ */
498
+ export function processStripeWebhook(db, params) {
499
+ verifyStripeWebhookSignature(params.rawBody, params.signatureHeader, params.webhookSecret, {
500
+ toleranceSeconds: params.toleranceSeconds,
501
+ nowSeconds: params.nowSeconds,
502
+ });
503
+ const payloadStr = Buffer.isBuffer(params.rawBody) ? params.rawBody.toString('utf8') : params.rawBody;
504
+ let event;
505
+ try {
506
+ event = JSON.parse(payloadStr);
507
+ }
508
+ catch {
509
+ throw new SwarmError('INVALID_INPUT', 'Stripe webhook payload is not valid JSON');
510
+ }
511
+ if (!event?.id || !event?.type || !event?.data?.object) {
512
+ throw new SwarmError('INVALID_INPUT', 'Malformed Stripe webhook event structure');
513
+ }
514
+ const ts = params.now ?? nowIso();
515
+ const existing = db
516
+ .prepare('SELECT event_id, operator_id FROM billing_webhook_events WHERE event_id = ?')
517
+ .get(event.id);
518
+ if (existing) {
519
+ const sub = existing.operator_id ? getOperatorSubscription(db, existing.operator_id) : null;
520
+ return {
521
+ event_id: event.id,
522
+ event_type: event.type,
523
+ duplicate: true,
524
+ handled: true,
525
+ operator_id: existing.operator_id,
526
+ subscription: sub,
527
+ };
528
+ }
529
+ const obj = event.data.object;
530
+ let operatorId = (typeof obj.metadata?.operator_id === 'string' && obj.metadata.operator_id) ||
531
+ (typeof obj.client_reference_id === 'string' && obj.client_reference_id) ||
532
+ findOperatorByStripeIds(db, typeof obj.customer === 'string' ? obj.customer : null, typeof obj.subscription === 'string' ? obj.subscription : typeof obj.id === 'string' && event.type.startsWith('customer.subscription') ? obj.id : null);
533
+ let subscription = null;
534
+ let usdDepositEntry = null;
535
+ let handled = false;
536
+ const tx = db.transaction(() => {
537
+ if (event.type === 'checkout.session.completed') {
538
+ if (operatorId) {
539
+ const isUsdTopup = obj.mode === 'payment' || obj.metadata?.purpose === 'usd_prepaid_topup';
540
+ if (isUsdTopup) {
541
+ const rawCurrency = String(obj.currency ?? 'usd').toUpperCase();
542
+ if (rawCurrency !== 'USD') {
543
+ throw new SwarmError('UNAUTHORIZED', `DUAL_LEDGER_FIREWALL: Prepaid USD top-up webhook rejected non-USD currency '${rawCurrency}'`);
544
+ }
545
+ if (obj.payment_status && obj.payment_status !== 'paid') {
546
+ handled = false;
547
+ }
548
+ else {
549
+ const amountCents = Number(obj.amount_total ?? obj.metadata?.amount_cents ?? 0);
550
+ usdDepositEntry = depositUsdCredits(db, {
551
+ operatorId,
552
+ amountCents,
553
+ fundingSource: 'stripe_checkout',
554
+ currency: 'USD',
555
+ stripeSessionId: typeof obj.id === 'string' ? obj.id : null,
556
+ stripePaymentIntentId: typeof obj.payment_intent === 'string' ? obj.payment_intent : null,
557
+ idempotencyKey: `stripe_evt:${event.id}`,
558
+ memo: `Stripe Prepaid USD top-up (${event.id})`,
559
+ metadata: { stripe_event_id: event.id },
560
+ now: ts,
561
+ });
562
+ handled = true;
563
+ }
564
+ }
565
+ else {
566
+ const metaTier = obj.metadata?.plan_tier;
567
+ const planTier = metaTier && metaTier in PLAN_CATALOG ? metaTier : 'pro_starter';
568
+ subscription = upsertOperatorSubscription(db, {
569
+ operatorId,
570
+ planTier,
571
+ status: 'active',
572
+ stripeCustomerId: typeof obj.customer === 'string' ? obj.customer : null,
573
+ stripeSubscriptionId: typeof obj.subscription === 'string' ? obj.subscription : null,
574
+ stripePriceId: typeof obj.metadata?.price_id === 'string'
575
+ ? obj.metadata.price_id
576
+ : planTier !== 'free'
577
+ ? getStripePriceIdForPlan(planTier, params.priceMap)
578
+ : null,
579
+ now: ts,
580
+ });
581
+ handled = true;
582
+ }
583
+ }
584
+ }
585
+ else if (event.type === 'customer.subscription.created' ||
586
+ event.type === 'customer.subscription.updated') {
587
+ if (operatorId) {
588
+ const priceId = obj.items?.data?.[0]?.price?.id;
589
+ const metaTier = obj.metadata?.plan_tier;
590
+ const resolvedTier = (metaTier && metaTier in PLAN_CATALOG ? metaTier : null) ??
591
+ resolvePlanTierFromPriceId(priceId, params.priceMap) ??
592
+ getOperatorSubscription(db, operatorId)?.plan_tier ??
593
+ 'pro_starter';
594
+ subscription = upsertOperatorSubscription(db, {
595
+ operatorId,
596
+ planTier: resolvedTier,
597
+ status: mapStripeStatus(obj.status),
598
+ stripeCustomerId: typeof obj.customer === 'string' ? obj.customer : null,
599
+ stripeSubscriptionId: typeof obj.id === 'string' ? obj.id : null,
600
+ stripePriceId: priceId ?? null,
601
+ currentPeriodStart: unixToIso(obj.current_period_start),
602
+ currentPeriodEnd: unixToIso(obj.current_period_end),
603
+ cancelAtPeriodEnd: Boolean(obj.cancel_at_period_end),
604
+ now: ts,
605
+ });
606
+ handled = true;
607
+ }
608
+ }
609
+ else if (event.type === 'customer.subscription.deleted') {
610
+ if (operatorId) {
611
+ subscription = upsertOperatorSubscription(db, {
612
+ operatorId,
613
+ planTier: 'free',
614
+ status: 'canceled',
615
+ stripeCustomerId: typeof obj.customer === 'string' ? obj.customer : null,
616
+ stripeSubscriptionId: typeof obj.id === 'string' ? obj.id : null,
617
+ cancelAtPeriodEnd: false,
618
+ now: ts,
619
+ });
620
+ handled = true;
621
+ }
622
+ }
623
+ else if (event.type === 'invoice.payment_failed') {
624
+ if (operatorId) {
625
+ const cur = getOperatorSubscription(db, operatorId);
626
+ if (cur) {
627
+ subscription = upsertOperatorSubscription(db, {
628
+ operatorId,
629
+ planTier: cur.plan_tier,
630
+ status: 'past_due',
631
+ stripeCustomerId: cur.stripe_customer_id,
632
+ stripeSubscriptionId: cur.stripe_subscription_id,
633
+ stripePriceId: cur.stripe_price_id,
634
+ now: ts,
635
+ });
636
+ handled = true;
637
+ }
638
+ }
639
+ }
640
+ else if (event.type === 'invoice.paid') {
641
+ if (operatorId) {
642
+ const cur = getOperatorSubscription(db, operatorId);
643
+ if (cur && cur.plan_tier !== 'free') {
644
+ subscription = upsertOperatorSubscription(db, {
645
+ operatorId,
646
+ planTier: cur.plan_tier,
647
+ status: 'active',
648
+ stripeCustomerId: cur.stripe_customer_id,
649
+ stripeSubscriptionId: cur.stripe_subscription_id,
650
+ stripePriceId: cur.stripe_price_id,
651
+ now: ts,
652
+ });
653
+ handled = true;
654
+ }
655
+ }
656
+ }
657
+ db.prepare(`
658
+ INSERT INTO billing_webhook_events (event_id, event_type, operator_id, payload_hash, processed_at)
659
+ VALUES (?, ?, ?, ?, ?)
660
+ `).run(event.id, event.type, operatorId, sha256Hex(payloadStr), ts);
661
+ });
662
+ tx.immediate();
663
+ return {
664
+ event_id: event.id,
665
+ event_type: event.type,
666
+ duplicate: false,
667
+ handled,
668
+ operator_id: operatorId,
669
+ subscription,
670
+ ...(usdDepositEntry ? { usd_deposit_entry: usdDepositEntry } : {}),
671
+ };
672
+ }
673
+ //# sourceMappingURL=subscriptions.js.map