caisson-cli 0.0.0-stage → 0.1.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.
- package/README.math-mvp.md +28 -0
- package/README.md +37 -2
- package/dist/admin/adminRoutes.d.ts +10 -0
- package/dist/admin/adminRoutes.js +194 -0
- package/dist/admin/adminRoutes.js.map +1 -0
- package/dist/admin/index.d.ts +2 -0
- package/dist/admin/index.js +4 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/admin/workspaceAdmin.d.ts +417 -0
- package/dist/admin/workspaceAdmin.js +569 -0
- package/dist/admin/workspaceAdmin.js.map +1 -0
- package/dist/analytics/index.d.ts +1 -0
- package/dist/analytics/index.js +3 -0
- package/dist/analytics/index.js.map +1 -0
- package/dist/analytics/metrics.d.ts +105 -0
- package/dist/analytics/metrics.js +837 -0
- package/dist/analytics/metrics.js.map +1 -0
- package/dist/audit/index.d.ts +4 -0
- package/dist/audit/index.js +6 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/audit/pipeline.d.ts +90 -0
- package/dist/audit/pipeline.js +424 -0
- package/dist/audit/pipeline.js.map +1 -0
- package/dist/audit/receiptSchema.d.ts +441 -0
- package/dist/audit/receiptSchema.js +208 -0
- package/dist/audit/receiptSchema.js.map +1 -0
- package/dist/audit/stageA.d.ts +50 -0
- package/dist/audit/stageA.js +218 -0
- package/dist/audit/stageA.js.map +1 -0
- package/dist/audit/stageB.d.ts +48 -0
- package/dist/audit/stageB.js +113 -0
- package/dist/audit/stageB.js.map +1 -0
- package/dist/auth/agentAuth.d.ts +18 -0
- package/dist/auth/agentAuth.js +59 -0
- package/dist/auth/agentAuth.js.map +1 -0
- package/dist/auth/agentCardSigner.d.ts +55 -0
- package/dist/auth/agentCardSigner.js +188 -0
- package/dist/auth/agentCardSigner.js.map +1 -0
- package/dist/billing/billingRoutes.d.ts +11 -0
- package/dist/billing/billingRoutes.js +303 -0
- package/dist/billing/billingRoutes.js.map +1 -0
- package/dist/billing/bountyRoutes.d.ts +9 -0
- package/dist/billing/bountyRoutes.js +332 -0
- package/dist/billing/bountyRoutes.js.map +1 -0
- package/dist/billing/index.d.ts +3 -0
- package/dist/billing/index.js +4 -0
- package/dist/billing/index.js.map +1 -0
- package/dist/billing/subscriptions.d.ts +226 -0
- package/dist/billing/subscriptions.js +673 -0
- package/dist/billing/subscriptions.js.map +1 -0
- package/dist/cli/caissonCli.d.ts +10 -0
- package/dist/cli/caissonCli.js +471 -0
- package/dist/cli/caissonCli.js.map +1 -0
- package/dist/cli/inviteCard.d.ts +12 -0
- package/dist/cli/inviteCard.js +49 -0
- package/dist/cli/inviteCard.js.map +1 -0
- package/dist/cli/mcpProxy.d.ts +36 -0
- package/dist/cli/mcpProxy.js +292 -0
- package/dist/cli/mcpProxy.js.map +1 -0
- package/dist/config.d.ts +19 -0
- package/dist/config.js +28 -0
- package/dist/config.js.map +1 -0
- package/dist/db/adapter.d.ts +210 -0
- package/dist/db/adapter.js +769 -0
- package/dist/db/adapter.js.map +1 -0
- package/dist/db/sqlite.d.ts +7 -0
- package/dist/db/sqlite.js +60 -0
- package/dist/db/sqlite.js.map +1 -0
- package/dist/db/telemetry.d.ts +11 -0
- package/dist/db/telemetry.js +9 -0
- package/dist/db/telemetry.js.map +1 -0
- package/dist/economy/bountyEngine.d.ts +248 -0
- package/dist/economy/bountyEngine.js +836 -0
- package/dist/economy/bountyEngine.js.map +1 -0
- package/dist/economy/index.d.ts +5 -0
- package/dist/economy/index.js +6 -0
- package/dist/economy/index.js.map +1 -0
- package/dist/economy/scLedger.d.ts +183 -0
- package/dist/economy/scLedger.js +528 -0
- package/dist/economy/scLedger.js.map +1 -0
- package/dist/economy/scMinting.d.ts +177 -0
- package/dist/economy/scMinting.js +659 -0
- package/dist/economy/scMinting.js.map +1 -0
- package/dist/economy/scSinks.d.ts +135 -0
- package/dist/economy/scSinks.js +314 -0
- package/dist/economy/scSinks.js.map +1 -0
- package/dist/economy/usdLedger.d.ts +211 -0
- package/dist/economy/usdLedger.js +604 -0
- package/dist/economy/usdLedger.js.map +1 -0
- package/dist/mcp/handlers.d.ts +134 -0
- package/dist/mcp/handlers.js +781 -0
- package/dist/mcp/handlers.js.map +1 -0
- package/dist/mcp/httpServer.d.ts +25 -0
- package/dist/mcp/httpServer.js +368 -0
- package/dist/mcp/httpServer.js.map +1 -0
- package/dist/mcp/serverFactory.d.ts +4 -0
- package/dist/mcp/serverFactory.js +53 -0
- package/dist/mcp/serverFactory.js.map +1 -0
- package/dist/mcp/stdioServer.d.ts +2 -0
- package/dist/mcp/stdioServer.js +24 -0
- package/dist/mcp/stdioServer.js.map +1 -0
- package/dist/mcp/toolMetadata.d.ts +15 -0
- package/dist/mcp/toolMetadata.js +73 -0
- package/dist/mcp/toolMetadata.js.map +1 -0
- package/dist/memo/artifactIndex.d.ts +51 -0
- package/dist/memo/artifactIndex.js +162 -0
- package/dist/memo/artifactIndex.js.map +1 -0
- package/dist/memo/dependencyBundle.d.ts +33 -0
- package/dist/memo/dependencyBundle.js +86 -0
- package/dist/memo/dependencyBundle.js.map +1 -0
- package/dist/memo/embeddings.d.ts +110 -0
- package/dist/memo/embeddings.js +672 -0
- package/dist/memo/embeddings.js.map +1 -0
- package/dist/packs/foundryEvm.d.ts +21 -0
- package/dist/packs/foundryEvm.js +274 -0
- package/dist/packs/foundryEvm.js.map +1 -0
- package/dist/packs/index.d.ts +8 -0
- package/dist/packs/index.js +19 -0
- package/dist/packs/index.js.map +1 -0
- package/dist/packs/mathLean4.d.ts +7 -0
- package/dist/packs/mathLean4.js +145 -0
- package/dist/packs/mathLean4.js.map +1 -0
- package/dist/packs/rustKani.d.ts +17 -0
- package/dist/packs/rustKani.js +257 -0
- package/dist/packs/rustKani.js.map +1 -0
- package/dist/packs/sdk.d.ts +314 -0
- package/dist/packs/sdk.js +271 -0
- package/dist/packs/sdk.js.map +1 -0
- package/dist/preflight/leanTripwire.d.ts +19 -0
- package/dist/preflight/leanTripwire.js +105 -0
- package/dist/preflight/leanTripwire.js.map +1 -0
- package/dist/storage/blobStore.d.ts +11 -0
- package/dist/storage/blobStore.js +39 -0
- package/dist/storage/blobStore.js.map +1 -0
- package/dist/storage/gitStore.d.ts +68 -0
- package/dist/storage/gitStore.js +228 -0
- package/dist/storage/gitStore.js.map +1 -0
- package/dist/types/errors.d.ts +16 -0
- package/dist/types/errors.js +23 -0
- package/dist/types/errors.js.map +1 -0
- package/dist/types/schemas.d.ts +453 -0
- package/dist/types/schemas.js +197 -0
- package/dist/types/schemas.js.map +1 -0
- package/dist/web/discoveryRoutes.d.ts +20 -0
- package/dist/web/discoveryRoutes.js +456 -0
- package/dist/web/discoveryRoutes.js.map +1 -0
- package/dist/web/explorer/dagLayout.d.ts +41 -0
- package/dist/web/explorer/dagLayout.js +183 -0
- package/dist/web/explorer/dagLayout.js.map +1 -0
- package/dist/web/explorer/index.d.ts +45 -0
- package/dist/web/explorer/index.js +512 -0
- package/dist/web/explorer/index.js.map +1 -0
- package/dist/web/explorer/renderers.d.ts +35 -0
- package/dist/web/explorer/renderers.js +397 -0
- package/dist/web/explorer/renderers.js.map +1 -0
- package/dist/web/repoBrowser.d.ts +19 -0
- package/dist/web/repoBrowser.js +128 -0
- package/dist/web/repoBrowser.js.map +1 -0
- package/dist/worker/executionAdapter.d.ts +14 -0
- package/dist/worker/executionAdapter.js +162 -0
- package/dist/worker/executionAdapter.js.map +1 -0
- package/dist/worker/finalize.d.ts +21 -0
- package/dist/worker/finalize.js +146 -0
- package/dist/worker/finalize.js.map +1 -0
- package/dist/worker/firecrackerAdapter.d.ts +180 -0
- package/dist/worker/firecrackerAdapter.js +421 -0
- package/dist/worker/firecrackerAdapter.js.map +1 -0
- package/dist/worker/loop.d.ts +56 -0
- package/dist/worker/loop.js +239 -0
- package/dist/worker/loop.js.map +1 -0
- package/dist/worker/postMergeSync.d.ts +17 -0
- package/dist/worker/postMergeSync.js +52 -0
- package/dist/worker/postMergeSync.js.map +1 -0
- package/dist/worker/prepareInput.d.ts +41 -0
- package/dist/worker/prepareInput.js +130 -0
- package/dist/worker/prepareInput.js.map +1 -0
- package/dist/worker/queue.d.ts +83 -0
- package/dist/worker/queue.js +278 -0
- package/dist/worker/queue.js.map +1 -0
- package/dist/worker/sandbox.d.ts +2 -0
- package/dist/worker/sandbox.js +3 -0
- package/dist/worker/sandbox.js.map +1 -0
- package/dist/worker/webhook.d.ts +14 -0
- package/dist/worker/webhook.js +110 -0
- package/dist/worker/webhook.js.map +1 -0
- package/migrations/001_init.sql +193 -0
- package/migrations/002_epic3_scale.sql +34 -0
- package/migrations/003_swarm_credits.sql +153 -0
- package/migrations/004_usd_bounties.sql +216 -0
- package/migrations_pg/001_init.sql +229 -0
- package/migrations_pg/002_multitenant_rls.sql +63 -0
- package/migrations_pg/003_swarm_credits.sql +135 -0
- package/migrations_pg/004_usd_bounties.sql +201 -0
- package/package.json +55 -4
- package/packs/foundry-evm/pack.json +60 -0
- package/packs/foundry-evm/verifier/Dockerfile +9 -0
- package/packs/foundry-evm/verifier/run.py +160 -0
- package/packs/math-lean4/pack.json +68 -0
- package/packs/rust-kani/pack.json +53 -0
- package/packs/rust-kani/verifier/Dockerfile +7 -0
- package/packs/rust-kani/verifier/run.py +159 -0
- package/public/.well-known/agent-card.json +153 -0
- package/public/llms.txt +35 -0
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
// src/billing/bountyRoutes.ts
|
|
2
|
+
// HTTP endpoints for Prepaid USD Credits (E5-1) and Automated USD Bounty Board (E5-2).
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import express from 'express';
|
|
5
|
+
import { z, ZodError } from 'zod';
|
|
6
|
+
import { authenticateBearerHeader } from '../auth/agentAuth.js';
|
|
7
|
+
import { sha256Hex } from '../db/sqlite.js';
|
|
8
|
+
import { cancelBounty, createAndFundBounty, depositUsdCredits, getAgentSpendCapStatus, getBountyById, getUsdOperatorAccount, listBounties, listBountyPayouts, listBountyStakes, listOperatorUsdLedgerEntries, rejectScToUsdConversion, requestUsdPayout, setAgentSpendCap, verifyUsdLedgerIntegrity, } from '../economy/index.js';
|
|
9
|
+
import { SwarmError } from '../types/errors.js';
|
|
10
|
+
import { createPrepaidUsdTopupSession, HttpStripeClient, } from './subscriptions.js';
|
|
11
|
+
function isAdminMatch(provided, expected) {
|
|
12
|
+
const a = Buffer.from(sha256Hex(provided), 'hex');
|
|
13
|
+
const b = Buffer.from(sha256Hex(expected), 'hex');
|
|
14
|
+
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
15
|
+
}
|
|
16
|
+
function authenticate(db, authHeader, adminToken) {
|
|
17
|
+
if (!authHeader?.startsWith('Bearer ')) {
|
|
18
|
+
throw new SwarmError('UNAUTHORIZED', 'Missing Bearer token');
|
|
19
|
+
}
|
|
20
|
+
const raw = authHeader.slice(7).trim();
|
|
21
|
+
if (adminToken && isAdminMatch(raw, adminToken)) {
|
|
22
|
+
return { kind: 'super_admin' };
|
|
23
|
+
}
|
|
24
|
+
return { kind: 'agent', agent: authenticateBearerHeader(db, authHeader) };
|
|
25
|
+
}
|
|
26
|
+
function optionalAuthenticate(db, authHeader, adminToken) {
|
|
27
|
+
if (!authHeader?.startsWith('Bearer '))
|
|
28
|
+
return null;
|
|
29
|
+
try {
|
|
30
|
+
return authenticate(db, authHeader, adminToken);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function sendErr(res, err) {
|
|
37
|
+
if (err instanceof SwarmError) {
|
|
38
|
+
const status = err.code === 'UNAUTHORIZED'
|
|
39
|
+
? 401
|
|
40
|
+
: err.code === 'NOT_FOUND'
|
|
41
|
+
? 404
|
|
42
|
+
: err.code === 'LEASE_CONFLICT'
|
|
43
|
+
? 409
|
|
44
|
+
: err.code === 'RATE_LIMITED'
|
|
45
|
+
? 429
|
|
46
|
+
: 400;
|
|
47
|
+
res.status(status).json(err.toEnvelope());
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (err instanceof ZodError) {
|
|
51
|
+
res.status(400).json(new SwarmError('INVALID_INPUT', err.issues.map((i) => `${i.path.join('.') || '<root>'}: ${i.message}`).join('; ')).toEnvelope());
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
res.status(400).json(new SwarmError('INVALID_INPUT', err instanceof Error ? err.message : String(err)).toEnvelope());
|
|
55
|
+
}
|
|
56
|
+
const UsdTopupCheckoutSchema = z.object({
|
|
57
|
+
amount_cents: z.number().int().min(100).max(100_000_000),
|
|
58
|
+
success_url: z.string().url(),
|
|
59
|
+
cancel_url: z.string().url(),
|
|
60
|
+
customer_email: z.string().email().optional(),
|
|
61
|
+
});
|
|
62
|
+
const AdminFundUsdSchema = z.object({
|
|
63
|
+
operator_id: z.string().min(1).max(128),
|
|
64
|
+
amount_cents: z.number().int().min(100).max(100_000_000),
|
|
65
|
+
funding_source: z.enum(['stripe_checkout', 'sponsor_grant', 'wire_transfer']).default('sponsor_grant'),
|
|
66
|
+
currency: z.string().default('USD'),
|
|
67
|
+
memo: z.string().max(500).optional(),
|
|
68
|
+
idempotency_key: z.string().max(128).optional(),
|
|
69
|
+
});
|
|
70
|
+
const SpendCapSchema = z.object({
|
|
71
|
+
per_task_spend_cap_cents: z.number().int().min(0).max(100_000_000),
|
|
72
|
+
});
|
|
73
|
+
const PayoutRequestSchema = z.object({
|
|
74
|
+
amount_cents: z.number().int().positive(),
|
|
75
|
+
destination_ref: z.string().max(200).optional(),
|
|
76
|
+
memo: z.string().max(500).optional(),
|
|
77
|
+
idempotency_key: z.string().max(128).optional(),
|
|
78
|
+
});
|
|
79
|
+
const CreateBountySchema = z.object({
|
|
80
|
+
node_id: z.string().min(4),
|
|
81
|
+
sponsor_operator_id: z.string().min(1).max(128).optional(),
|
|
82
|
+
reward_cents: z.number().int().positive(),
|
|
83
|
+
platform_fee_bps: z.number().int().min(1000).max(1500).optional(),
|
|
84
|
+
royalty_pool_bps: z.number().int().min(1000).max(2000).optional(),
|
|
85
|
+
recursive_decay_bps: z.number().int().min(0).max(10000).optional(),
|
|
86
|
+
anti_slop_stake_cents: z.number().int().min(0).optional(),
|
|
87
|
+
slash_recipient: z.enum(['slash_pool', 'sponsor']).optional(),
|
|
88
|
+
expires_at: z.string().datetime().nullable().optional(),
|
|
89
|
+
idempotency_key: z.string().max(128).optional(),
|
|
90
|
+
});
|
|
91
|
+
export function createBountyAndUsdRouter(opts) {
|
|
92
|
+
const router = express.Router();
|
|
93
|
+
const { db, adminToken } = opts;
|
|
94
|
+
const resolveStripeClient = () => {
|
|
95
|
+
if (opts.stripeClient)
|
|
96
|
+
return opts.stripeClient;
|
|
97
|
+
const key = process.env.STRIPE_SECRET_KEY;
|
|
98
|
+
if (!key) {
|
|
99
|
+
throw new SwarmError('INVALID_INPUT', 'Stripe billing is not configured (missing STRIPE_SECRET_KEY)');
|
|
100
|
+
}
|
|
101
|
+
return new HttpStripeClient(key);
|
|
102
|
+
};
|
|
103
|
+
// --- PREPAID USD CREDIT LEDGER (E5-1) ---
|
|
104
|
+
router.get('/v1/usd/balance', (req, res) => {
|
|
105
|
+
try {
|
|
106
|
+
const actor = authenticate(db, req.headers.authorization, adminToken);
|
|
107
|
+
const operatorId = actor.kind === 'agent'
|
|
108
|
+
? actor.agent.operatorId
|
|
109
|
+
: String(req.query.operator_id ?? '');
|
|
110
|
+
if (!operatorId) {
|
|
111
|
+
throw new SwarmError('INVALID_INPUT', 'operator_id query parameter required for super-admin');
|
|
112
|
+
}
|
|
113
|
+
const account = getUsdOperatorAccount(db, operatorId);
|
|
114
|
+
const recentEntries = listOperatorUsdLedgerEntries(db, operatorId, Number(req.query.limit ?? 25));
|
|
115
|
+
const agentCap = actor.kind === 'agent' ? getAgentSpendCapStatus(db, actor.agent.agentId) : null;
|
|
116
|
+
res.status(200).json({
|
|
117
|
+
currency: 'USD',
|
|
118
|
+
convertible_to_sc: false,
|
|
119
|
+
account,
|
|
120
|
+
...(agentCap ? { agent_spend_cap: agentCap } : {}),
|
|
121
|
+
recent_entries: recentEntries,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
sendErr(res, err);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
router.post('/v1/usd/topup/checkout', async (req, res) => {
|
|
129
|
+
try {
|
|
130
|
+
const actor = authenticate(db, req.headers.authorization, adminToken);
|
|
131
|
+
if (actor.kind !== 'agent') {
|
|
132
|
+
throw new SwarmError('INVALID_INPUT', 'USD top-up checkout requires an operator agent bearer token');
|
|
133
|
+
}
|
|
134
|
+
const input = UsdTopupCheckoutSchema.parse(req.body ?? {});
|
|
135
|
+
const session = await createPrepaidUsdTopupSession(db, resolveStripeClient(), {
|
|
136
|
+
operatorId: actor.agent.operatorId,
|
|
137
|
+
amountCents: input.amount_cents,
|
|
138
|
+
successUrl: input.success_url,
|
|
139
|
+
cancelUrl: input.cancel_url,
|
|
140
|
+
customerEmail: input.customer_email,
|
|
141
|
+
});
|
|
142
|
+
res.status(201).json(session);
|
|
143
|
+
}
|
|
144
|
+
catch (err) {
|
|
145
|
+
sendErr(res, err);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
router.post('/v1/usd/fund', (req, res) => {
|
|
149
|
+
try {
|
|
150
|
+
const actor = authenticate(db, req.headers.authorization, adminToken);
|
|
151
|
+
if (actor.kind !== 'super_admin') {
|
|
152
|
+
throw new SwarmError('UNAUTHORIZED', 'Direct USD sponsor/wire funding requires platform admin token');
|
|
153
|
+
}
|
|
154
|
+
const input = AdminFundUsdSchema.parse(req.body ?? {});
|
|
155
|
+
const entry = depositUsdCredits(db, {
|
|
156
|
+
operatorId: input.operator_id,
|
|
157
|
+
amountCents: input.amount_cents,
|
|
158
|
+
fundingSource: input.funding_source,
|
|
159
|
+
currency: input.currency,
|
|
160
|
+
memo: input.memo,
|
|
161
|
+
idempotencyKey: input.idempotency_key,
|
|
162
|
+
});
|
|
163
|
+
res.status(201).json({
|
|
164
|
+
entry,
|
|
165
|
+
account: getUsdOperatorAccount(db, input.operator_id),
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
sendErr(res, err);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
router.post('/v1/usd/payouts', (req, res) => {
|
|
173
|
+
try {
|
|
174
|
+
const actor = authenticate(db, req.headers.authorization, adminToken);
|
|
175
|
+
if (actor.kind !== 'agent') {
|
|
176
|
+
throw new SwarmError('INVALID_INPUT', 'USD payout request requires an operator agent bearer token');
|
|
177
|
+
}
|
|
178
|
+
const input = PayoutRequestSchema.parse(req.body ?? {});
|
|
179
|
+
const entry = requestUsdPayout(db, {
|
|
180
|
+
operatorId: actor.agent.operatorId,
|
|
181
|
+
amountCents: input.amount_cents,
|
|
182
|
+
destinationRef: input.destination_ref,
|
|
183
|
+
memo: input.memo,
|
|
184
|
+
idempotencyKey: input.idempotency_key,
|
|
185
|
+
});
|
|
186
|
+
res.status(201).json({
|
|
187
|
+
entry,
|
|
188
|
+
account: getUsdOperatorAccount(db, actor.agent.operatorId),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
catch (err) {
|
|
192
|
+
sendErr(res, err);
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
router.put('/v1/usd/agents/:agentId/spend-cap', (req, res) => {
|
|
196
|
+
try {
|
|
197
|
+
const actor = authenticate(db, req.headers.authorization, adminToken);
|
|
198
|
+
const input = SpendCapSchema.parse(req.body ?? {});
|
|
199
|
+
const target = getAgentSpendCapStatus(db, req.params.agentId);
|
|
200
|
+
if (actor.kind === 'agent' && actor.agent.operatorId !== target.operator_id) {
|
|
201
|
+
throw new SwarmError('UNAUTHORIZED', 'Cannot modify per_task_spend_cap for another operator agent');
|
|
202
|
+
}
|
|
203
|
+
const updated = setAgentSpendCap(db, req.params.agentId, input.per_task_spend_cap_cents);
|
|
204
|
+
res.status(200).json(updated);
|
|
205
|
+
}
|
|
206
|
+
catch (err) {
|
|
207
|
+
sendErr(res, err);
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
// Dual-Ledger Firewall endpoint explicitly rejecting any USD -> SC conversion
|
|
211
|
+
router.post('/v1/usd/convert-sc', (_req, res) => {
|
|
212
|
+
try {
|
|
213
|
+
rejectScToUsdConversion();
|
|
214
|
+
}
|
|
215
|
+
catch (err) {
|
|
216
|
+
sendErr(res, err);
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
router.get('/v1/usd/integrity', (req, res) => {
|
|
220
|
+
try {
|
|
221
|
+
const actor = authenticate(db, req.headers.authorization, adminToken);
|
|
222
|
+
if (actor.kind !== 'super_admin') {
|
|
223
|
+
throw new SwarmError('UNAUTHORIZED', 'USD ledger integrity audit requires platform admin token');
|
|
224
|
+
}
|
|
225
|
+
res.status(200).json(verifyUsdLedgerIntegrity(db));
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
sendErr(res, err);
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
// --- AUTOMATED USD BOUNTY BOARD (E5-2) ---
|
|
232
|
+
router.get('/v1/bounties', (req, res) => {
|
|
233
|
+
try {
|
|
234
|
+
const actor = optionalAuthenticate(db, req.headers.authorization, adminToken);
|
|
235
|
+
const workspaceId = typeof req.query.workspace_id === 'string' ? req.query.workspace_id : undefined;
|
|
236
|
+
const rawStatus = typeof req.query.status === 'string' ? req.query.status : undefined;
|
|
237
|
+
const status = rawStatus === 'funded' || rawStatus === 'settled' || rawStatus === 'canceled' || rawStatus === 'disputed'
|
|
238
|
+
? rawStatus
|
|
239
|
+
: undefined;
|
|
240
|
+
const limit = Number(req.query.limit ?? 50);
|
|
241
|
+
const bounties = listBounties(db, {
|
|
242
|
+
workspaceId,
|
|
243
|
+
status,
|
|
244
|
+
viewerAgentId: actor?.kind === 'agent' ? actor.agent.agentId : null,
|
|
245
|
+
includeAllForAdmin: actor?.kind === 'super_admin',
|
|
246
|
+
limit: Number.isFinite(limit) ? limit : 50,
|
|
247
|
+
});
|
|
248
|
+
res.status(200).json({
|
|
249
|
+
currency: 'USD',
|
|
250
|
+
count: bounties.length,
|
|
251
|
+
bounties,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
catch (err) {
|
|
255
|
+
sendErr(res, err);
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
router.get('/v1/bounties/:bountyId', (req, res) => {
|
|
259
|
+
try {
|
|
260
|
+
const actor = optionalAuthenticate(db, req.headers.authorization, adminToken);
|
|
261
|
+
const bounty = getBountyById(db, req.params.bountyId);
|
|
262
|
+
if (!bounty) {
|
|
263
|
+
throw new SwarmError('NOT_FOUND', `Bounty '${req.params.bountyId}' not found`);
|
|
264
|
+
}
|
|
265
|
+
const ws = db.prepare('SELECT id, visibility FROM workspaces WHERE id = ?').get(bounty.workspace_id);
|
|
266
|
+
if (ws?.visibility !== 'public' && actor?.kind !== 'super_admin') {
|
|
267
|
+
if (actor?.kind !== 'agent') {
|
|
268
|
+
throw new SwarmError('NOT_FOUND', `Bounty '${req.params.bountyId}' not found`);
|
|
269
|
+
}
|
|
270
|
+
const member = db
|
|
271
|
+
.prepare('SELECT 1 FROM workspace_members WHERE workspace_id = ? AND agent_id = ?')
|
|
272
|
+
.get(ws.id, actor.agent.agentId);
|
|
273
|
+
if (!member) {
|
|
274
|
+
throw new SwarmError('NOT_FOUND', `Bounty '${req.params.bountyId}' not found`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
res.status(200).json({
|
|
278
|
+
bounty,
|
|
279
|
+
payouts: listBountyPayouts(db, bounty.id),
|
|
280
|
+
stakes: listBountyStakes(db, bounty.id),
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
catch (err) {
|
|
284
|
+
sendErr(res, err);
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
router.post('/v1/bounties', (req, res) => {
|
|
288
|
+
try {
|
|
289
|
+
const actor = authenticate(db, req.headers.authorization, adminToken);
|
|
290
|
+
const input = CreateBountySchema.parse(req.body ?? {});
|
|
291
|
+
const sponsorOperatorId = actor.kind === 'agent'
|
|
292
|
+
? actor.agent.operatorId
|
|
293
|
+
: input.sponsor_operator_id ?? '';
|
|
294
|
+
if (!sponsorOperatorId) {
|
|
295
|
+
throw new SwarmError('INVALID_INPUT', 'sponsor_operator_id is required when funding via admin token');
|
|
296
|
+
}
|
|
297
|
+
const result = createAndFundBounty(db, {
|
|
298
|
+
nodeId: input.node_id,
|
|
299
|
+
sponsorOperatorId,
|
|
300
|
+
fundedByAgentId: actor.kind === 'agent' ? actor.agent.agentId : null,
|
|
301
|
+
rewardCents: input.reward_cents,
|
|
302
|
+
platformFeeBps: input.platform_fee_bps,
|
|
303
|
+
royaltyPoolBps: input.royalty_pool_bps,
|
|
304
|
+
recursiveDecayBps: input.recursive_decay_bps,
|
|
305
|
+
antiSlopStakeCents: input.anti_slop_stake_cents,
|
|
306
|
+
slashRecipient: input.slash_recipient,
|
|
307
|
+
expiresAt: input.expires_at ?? null,
|
|
308
|
+
idempotencyKey: input.idempotency_key,
|
|
309
|
+
});
|
|
310
|
+
res.status(201).json(result);
|
|
311
|
+
}
|
|
312
|
+
catch (err) {
|
|
313
|
+
sendErr(res, err);
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
router.post('/v1/bounties/:bountyId/cancel', (req, res) => {
|
|
317
|
+
try {
|
|
318
|
+
const actor = authenticate(db, req.headers.authorization, adminToken);
|
|
319
|
+
const result = cancelBounty(db, {
|
|
320
|
+
bountyId: req.params.bountyId,
|
|
321
|
+
actorOperatorId: actor.kind === 'agent' ? actor.agent.operatorId : undefined,
|
|
322
|
+
isAdmin: actor.kind === 'super_admin',
|
|
323
|
+
});
|
|
324
|
+
res.status(200).json(result);
|
|
325
|
+
}
|
|
326
|
+
catch (err) {
|
|
327
|
+
sendErr(res, err);
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
return router;
|
|
331
|
+
}
|
|
332
|
+
//# sourceMappingURL=bountyRoutes.js.map
|
|
@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AAC,CAAC;QACpB,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,mBAAmB,CAAC"}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import type Database from 'better-sqlite3';
|
|
2
|
+
import { type UsdJournalEntryRecord } from '../economy/usdLedger.js';
|
|
3
|
+
export type PlanTier = 'free' | 'pro_starter' | 'pro_team' | 'enterprise';
|
|
4
|
+
export type SubscriptionStatus = 'active' | 'trialing' | 'past_due' | 'canceled' | 'incomplete';
|
|
5
|
+
export interface PlanDefinition {
|
|
6
|
+
tier: PlanTier;
|
|
7
|
+
name: string;
|
|
8
|
+
monthly_price_usd_cents: number;
|
|
9
|
+
monthly_price_usd: number;
|
|
10
|
+
private_workspace_limit: number;
|
|
11
|
+
hourly_verification_quota: number;
|
|
12
|
+
worker_priority: number;
|
|
13
|
+
concurrency_cap: number;
|
|
14
|
+
rate_limit_tier: 'standard' | 'pro' | 'pro_team' | 'trusted';
|
|
15
|
+
default_stripe_price_env: string | null;
|
|
16
|
+
features: string[];
|
|
17
|
+
}
|
|
18
|
+
export declare const PLAN_CATALOG: Readonly<Record<PlanTier, PlanDefinition>>;
|
|
19
|
+
export interface OperatorSubscriptionRecord {
|
|
20
|
+
id: string;
|
|
21
|
+
operator_id: string;
|
|
22
|
+
plan_tier: PlanTier;
|
|
23
|
+
monthly_price_usd_cents: number;
|
|
24
|
+
status: SubscriptionStatus;
|
|
25
|
+
stripe_customer_id: string | null;
|
|
26
|
+
stripe_subscription_id: string | null;
|
|
27
|
+
stripe_price_id: string | null;
|
|
28
|
+
current_period_start: string | null;
|
|
29
|
+
current_period_end: string | null;
|
|
30
|
+
cancel_at_period_end: boolean;
|
|
31
|
+
private_workspace_limit: number;
|
|
32
|
+
hourly_verification_quota: number;
|
|
33
|
+
worker_priority: number;
|
|
34
|
+
concurrency_cap: number;
|
|
35
|
+
created_at: string;
|
|
36
|
+
updated_at: string;
|
|
37
|
+
}
|
|
38
|
+
export interface OperatorEntitlements {
|
|
39
|
+
operator_id: string;
|
|
40
|
+
plan_tier: PlanTier;
|
|
41
|
+
status: SubscriptionStatus;
|
|
42
|
+
active: boolean;
|
|
43
|
+
monthly_price_usd: number;
|
|
44
|
+
private_workspace_limit: number;
|
|
45
|
+
private_workspaces_used: number;
|
|
46
|
+
can_create_private_workspace: boolean;
|
|
47
|
+
hourly_verification_quota: number;
|
|
48
|
+
worker_priority: number;
|
|
49
|
+
concurrency_cap: number;
|
|
50
|
+
rate_limit_tier: 'standard' | 'pro' | 'pro_team' | 'trusted';
|
|
51
|
+
}
|
|
52
|
+
export interface StripeCheckoutSessionResponse {
|
|
53
|
+
id: string;
|
|
54
|
+
url: string;
|
|
55
|
+
customer_id?: string | null;
|
|
56
|
+
}
|
|
57
|
+
export interface StripePortalSessionResponse {
|
|
58
|
+
id: string;
|
|
59
|
+
url: string;
|
|
60
|
+
}
|
|
61
|
+
export interface StripeBillingClient {
|
|
62
|
+
createCheckoutSession(params: {
|
|
63
|
+
operatorId: string;
|
|
64
|
+
planTier: Exclude<PlanTier, 'free'>;
|
|
65
|
+
priceId: string;
|
|
66
|
+
customerId?: string | null;
|
|
67
|
+
customerEmail?: string;
|
|
68
|
+
successUrl: string;
|
|
69
|
+
cancelUrl: string;
|
|
70
|
+
}): Promise<StripeCheckoutSessionResponse>;
|
|
71
|
+
createBillingPortalSession(params: {
|
|
72
|
+
customerId: string;
|
|
73
|
+
returnUrl: string;
|
|
74
|
+
}): Promise<StripePortalSessionResponse>;
|
|
75
|
+
createUsdTopupCheckoutSession?(params: {
|
|
76
|
+
operatorId: string;
|
|
77
|
+
amountCents: number;
|
|
78
|
+
customerId?: string | null;
|
|
79
|
+
customerEmail?: string;
|
|
80
|
+
successUrl: string;
|
|
81
|
+
cancelUrl: string;
|
|
82
|
+
}): Promise<StripeCheckoutSessionResponse>;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Zero-dependency Stripe REST API client using Node 22 built-in `fetch`.
|
|
86
|
+
*/
|
|
87
|
+
export declare class HttpStripeClient implements StripeBillingClient {
|
|
88
|
+
private readonly secretKey;
|
|
89
|
+
private readonly apiBase;
|
|
90
|
+
constructor(secretKey: string, apiBase?: string);
|
|
91
|
+
private postForm;
|
|
92
|
+
createCheckoutSession(params: {
|
|
93
|
+
operatorId: string;
|
|
94
|
+
planTier: Exclude<PlanTier, 'free'>;
|
|
95
|
+
priceId: string;
|
|
96
|
+
customerId?: string | null;
|
|
97
|
+
customerEmail?: string;
|
|
98
|
+
successUrl: string;
|
|
99
|
+
cancelUrl: string;
|
|
100
|
+
}): Promise<StripeCheckoutSessionResponse>;
|
|
101
|
+
createBillingPortalSession(params: {
|
|
102
|
+
customerId: string;
|
|
103
|
+
returnUrl: string;
|
|
104
|
+
}): Promise<StripePortalSessionResponse>;
|
|
105
|
+
createUsdTopupCheckoutSession(params: {
|
|
106
|
+
operatorId: string;
|
|
107
|
+
amountCents: number;
|
|
108
|
+
customerId?: string | null;
|
|
109
|
+
customerEmail?: string;
|
|
110
|
+
successUrl: string;
|
|
111
|
+
cancelUrl: string;
|
|
112
|
+
}): Promise<StripeCheckoutSessionResponse>;
|
|
113
|
+
}
|
|
114
|
+
export interface StripeWebhookEvent {
|
|
115
|
+
id: string;
|
|
116
|
+
type: string;
|
|
117
|
+
created?: number;
|
|
118
|
+
data: {
|
|
119
|
+
object: Record<string, any>;
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
export interface WebhookProcessResult {
|
|
123
|
+
event_id: string;
|
|
124
|
+
event_type: string;
|
|
125
|
+
duplicate: boolean;
|
|
126
|
+
handled: boolean;
|
|
127
|
+
operator_id: string | null;
|
|
128
|
+
subscription: OperatorSubscriptionRecord | null;
|
|
129
|
+
usd_deposit_entry?: UsdJournalEntryRecord | null;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Generates a valid Stripe `Stripe-Signature` header (`t=<ts>,v1=<hmac_sha256>`).
|
|
133
|
+
* Useful for testing and webhook verification harnesses.
|
|
134
|
+
*/
|
|
135
|
+
export declare function signStripeWebhookPayload(rawPayload: string | Buffer, webhookSecret: string, timestampSeconds?: number): string;
|
|
136
|
+
/**
|
|
137
|
+
* Verifies a Stripe `Stripe-Signature` header using constant-time HMAC-SHA256 comparison
|
|
138
|
+
* and replay-window timestamp enforcement (default 300s).
|
|
139
|
+
*/
|
|
140
|
+
export declare function verifyStripeWebhookSignature(rawPayload: string | Buffer, signatureHeader: string | undefined, webhookSecret: string, opts?: {
|
|
141
|
+
toleranceSeconds?: number;
|
|
142
|
+
nowSeconds?: number;
|
|
143
|
+
}): void;
|
|
144
|
+
/** Resolves a Stripe Price ID to a Caisson PlanTier using env vars or explicit priceMap. */
|
|
145
|
+
export declare function resolvePlanTierFromPriceId(priceId: string | undefined | null, priceMap?: Partial<Record<Exclude<PlanTier, 'free'>, string>>): PlanTier | null;
|
|
146
|
+
/** Resolves the configured Stripe Price ID for a paid plan tier. */
|
|
147
|
+
export declare function getStripePriceIdForPlan(planTier: Exclude<PlanTier, 'free'>, priceMap?: Partial<Record<Exclude<PlanTier, 'free'>, string>>): string;
|
|
148
|
+
/** Returns an operator's stored subscription record, or null if on default Free tier. */
|
|
149
|
+
export declare function getOperatorSubscription(db: Database.Database, operatorId: string): OperatorSubscriptionRecord | null;
|
|
150
|
+
/**
|
|
151
|
+
* Computes effective runtime entitlements for an operator:
|
|
152
|
+
* - Active (`active` | `trialing`) subscriptions unlock private airlocked workspaces,
|
|
153
|
+
* higher hourly verification quotas, and priority worker lanes.
|
|
154
|
+
* - `past_due`, `canceled`, or `incomplete` subscriptions fall back to Free tier limits.
|
|
155
|
+
*/
|
|
156
|
+
export declare function getOperatorEntitlements(db: Database.Database, operatorId: string): OperatorEntitlements;
|
|
157
|
+
/**
|
|
158
|
+
* Enforces that an operator has an active Pro/Enterprise plan with remaining private airlocked workspace capacity.
|
|
159
|
+
*/
|
|
160
|
+
export declare function assertCanCreatePrivateWorkspace(db: Database.Database, operatorId: string): OperatorEntitlements;
|
|
161
|
+
/**
|
|
162
|
+
* Upserts an operator's subscription and synchronizes `agent_identities.rate_limit_tier`
|
|
163
|
+
* for all non-internal agents belonging to that operator so worker priority lanes and
|
|
164
|
+
* hourly quotas take effect immediately.
|
|
165
|
+
*/
|
|
166
|
+
export declare function upsertOperatorSubscription(db: Database.Database, params: {
|
|
167
|
+
operatorId: string;
|
|
168
|
+
planTier: PlanTier;
|
|
169
|
+
status: SubscriptionStatus;
|
|
170
|
+
stripeCustomerId?: string | null;
|
|
171
|
+
stripeSubscriptionId?: string | null;
|
|
172
|
+
stripePriceId?: string | null;
|
|
173
|
+
currentPeriodStart?: string | null;
|
|
174
|
+
currentPeriodEnd?: string | null;
|
|
175
|
+
cancelAtPeriodEnd?: boolean;
|
|
176
|
+
now?: string;
|
|
177
|
+
}): OperatorSubscriptionRecord;
|
|
178
|
+
/** Creates a Stripe Checkout Session for an operator upgrading to `pro_starter` ($29/mo) or `pro_team` ($99/mo). */
|
|
179
|
+
export declare function createProCheckoutSession(db: Database.Database, stripe: StripeBillingClient, params: {
|
|
180
|
+
operatorId: string;
|
|
181
|
+
planTier: Exclude<PlanTier, 'free'>;
|
|
182
|
+
successUrl: string;
|
|
183
|
+
cancelUrl: string;
|
|
184
|
+
customerEmail?: string;
|
|
185
|
+
priceMap?: Partial<Record<Exclude<PlanTier, 'free'>, string>>;
|
|
186
|
+
}): Promise<{
|
|
187
|
+
session_id: string;
|
|
188
|
+
checkout_url: string;
|
|
189
|
+
plan_tier: Exclude<PlanTier, 'free'>;
|
|
190
|
+
monthly_price_usd: number;
|
|
191
|
+
}>;
|
|
192
|
+
/** Creates a Stripe Checkout Session (`mode: 'payment'`) to top up an operator's Prepaid USD Credit balance (E5-1). */
|
|
193
|
+
export declare function createPrepaidUsdTopupSession(db: Database.Database, stripe: StripeBillingClient, params: {
|
|
194
|
+
operatorId: string;
|
|
195
|
+
amountCents: number;
|
|
196
|
+
successUrl: string;
|
|
197
|
+
cancelUrl: string;
|
|
198
|
+
customerEmail?: string;
|
|
199
|
+
}): Promise<{
|
|
200
|
+
session_id: string;
|
|
201
|
+
checkout_url: string;
|
|
202
|
+
currency: 'USD';
|
|
203
|
+
amount_cents: number;
|
|
204
|
+
amount_usd: number;
|
|
205
|
+
}>;
|
|
206
|
+
/** Creates a Stripe Billing Portal session for an operator with an existing Stripe customer ID. */
|
|
207
|
+
export declare function createOperatorPortalSession(db: Database.Database, stripe: StripeBillingClient, params: {
|
|
208
|
+
operatorId: string;
|
|
209
|
+
returnUrl: string;
|
|
210
|
+
}): Promise<{
|
|
211
|
+
portal_url: string;
|
|
212
|
+
session_id: string;
|
|
213
|
+
}>;
|
|
214
|
+
/**
|
|
215
|
+
* Verifies Stripe webhook signature, deduplicates via `billing_webhook_events`,
|
|
216
|
+
* and applies subscription lifecycle transitions atomically.
|
|
217
|
+
*/
|
|
218
|
+
export declare function processStripeWebhook(db: Database.Database, params: {
|
|
219
|
+
rawBody: string | Buffer;
|
|
220
|
+
signatureHeader: string | undefined;
|
|
221
|
+
webhookSecret: string;
|
|
222
|
+
priceMap?: Partial<Record<Exclude<PlanTier, 'free'>, string>>;
|
|
223
|
+
toleranceSeconds?: number;
|
|
224
|
+
nowSeconds?: number;
|
|
225
|
+
now?: string;
|
|
226
|
+
}): WebhookProcessResult;
|