@wopr-network/platform-core 1.42.3 → 1.44.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 (63) hide show
  1. package/.github/workflows/key-server-image.yml +35 -0
  2. package/Dockerfile.key-server +20 -0
  3. package/GATEWAY_BILLING_RESEARCH.md +430 -0
  4. package/biome.json +2 -9
  5. package/dist/billing/crypto/__tests__/key-server.test.js +240 -0
  6. package/dist/billing/crypto/btc/watcher.d.ts +2 -0
  7. package/dist/billing/crypto/btc/watcher.js +1 -1
  8. package/dist/billing/crypto/charge-store.d.ts +7 -1
  9. package/dist/billing/crypto/charge-store.js +7 -1
  10. package/dist/billing/crypto/client.d.ts +68 -30
  11. package/dist/billing/crypto/client.js +63 -46
  12. package/dist/billing/crypto/client.test.js +66 -83
  13. package/dist/billing/crypto/index.d.ts +8 -8
  14. package/dist/billing/crypto/index.js +4 -5
  15. package/dist/billing/crypto/key-server-entry.js +84 -0
  16. package/dist/billing/crypto/key-server-webhook.d.ts +33 -0
  17. package/dist/billing/crypto/key-server-webhook.js +73 -0
  18. package/dist/billing/crypto/key-server.d.ts +20 -0
  19. package/dist/billing/crypto/key-server.js +263 -0
  20. package/dist/billing/crypto/watcher-service.d.ts +33 -0
  21. package/dist/billing/crypto/watcher-service.js +295 -0
  22. package/dist/billing/index.js +1 -1
  23. package/dist/db/schema/crypto.d.ts +464 -2
  24. package/dist/db/schema/crypto.js +60 -6
  25. package/dist/monetization/crypto/__tests__/webhook.test.js +57 -92
  26. package/dist/monetization/crypto/index.d.ts +4 -4
  27. package/dist/monetization/crypto/index.js +2 -2
  28. package/dist/monetization/crypto/webhook.d.ts +13 -14
  29. package/dist/monetization/crypto/webhook.js +12 -83
  30. package/dist/monetization/index.d.ts +2 -2
  31. package/dist/monetization/index.js +1 -1
  32. package/drizzle/migrations/0014_crypto_key_server.sql +60 -0
  33. package/drizzle/migrations/0015_callback_url.sql +32 -0
  34. package/drizzle/migrations/meta/_journal.json +28 -0
  35. package/package.json +2 -1
  36. package/src/billing/crypto/__tests__/key-server.test.ts +262 -0
  37. package/src/billing/crypto/btc/watcher.ts +3 -1
  38. package/src/billing/crypto/charge-store.ts +13 -1
  39. package/src/billing/crypto/client.test.ts +70 -98
  40. package/src/billing/crypto/client.ts +118 -59
  41. package/src/billing/crypto/index.ts +19 -14
  42. package/src/billing/crypto/key-server-entry.ts +96 -0
  43. package/src/billing/crypto/key-server-webhook.ts +119 -0
  44. package/src/billing/crypto/key-server.ts +343 -0
  45. package/src/billing/crypto/watcher-service.ts +381 -0
  46. package/src/billing/index.ts +1 -1
  47. package/src/db/schema/crypto.ts +75 -6
  48. package/src/monetization/crypto/__tests__/webhook.test.ts +61 -104
  49. package/src/monetization/crypto/index.ts +9 -11
  50. package/src/monetization/crypto/webhook.ts +25 -99
  51. package/src/monetization/index.ts +3 -7
  52. package/dist/billing/crypto/checkout.d.ts +0 -18
  53. package/dist/billing/crypto/checkout.js +0 -35
  54. package/dist/billing/crypto/checkout.test.js +0 -71
  55. package/dist/billing/crypto/webhook.d.ts +0 -34
  56. package/dist/billing/crypto/webhook.js +0 -107
  57. package/dist/billing/crypto/webhook.test.js +0 -266
  58. package/src/billing/crypto/checkout.test.ts +0 -93
  59. package/src/billing/crypto/checkout.ts +0 -48
  60. package/src/billing/crypto/webhook.test.ts +0 -340
  61. package/src/billing/crypto/webhook.ts +0 -136
  62. /package/dist/billing/crypto/{checkout.test.d.ts → __tests__/key-server.test.d.ts} +0 -0
  63. /package/dist/billing/crypto/{webhook.test.d.ts → key-server-entry.d.ts} +0 -0
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Crypto Key Server — shared address derivation + charge management.
3
+ *
4
+ * Deploys on the chain server (pay.wopr.bot) alongside bitcoind.
5
+ * Products don't run watchers or hold xpubs. They request addresses
6
+ * and receive webhooks.
7
+ *
8
+ * ~200 lines of new code wrapping platform-core's existing crypto modules.
9
+ */
10
+ import { eq, sql } from "drizzle-orm";
11
+ import { Hono } from "hono";
12
+ import type { DrizzleDb } from "../../db/index.js";
13
+ import { derivedAddresses, pathAllocations, paymentMethods } from "../../db/schema/crypto.js";
14
+ import { deriveAddress, deriveP2pkhAddress } from "./btc/address-gen.js";
15
+ import type { ICryptoChargeRepository } from "./charge-store.js";
16
+ import { deriveDepositAddress } from "./evm/address-gen.js";
17
+ import { centsToNative } from "./oracle/convert.js";
18
+ import type { IPriceOracle } from "./oracle/types.js";
19
+ import type { IPaymentMethodStore } from "./payment-method-store.js";
20
+
21
+ export interface KeyServerDeps {
22
+ db: DrizzleDb;
23
+ chargeStore: ICryptoChargeRepository;
24
+ methodStore: IPaymentMethodStore;
25
+ oracle: IPriceOracle;
26
+ /** Bearer token for product API routes. If unset, auth is disabled. */
27
+ serviceKey?: string;
28
+ /** Bearer token for admin routes. If unset, admin routes are disabled. */
29
+ adminToken?: string;
30
+ }
31
+
32
+ /**
33
+ * Derive the next unused address for a chain.
34
+ * Atomically increments next_index and records address in a single transaction.
35
+ */
36
+ async function deriveNextAddress(
37
+ db: DrizzleDb,
38
+ chainId: string,
39
+ tenantId?: string,
40
+ ): Promise<{ address: string; index: number; chain: string; token: string }> {
41
+ // Wrap in transaction: if the address insert fails, next_index is not consumed.
42
+ return (db as unknown as { transaction: (fn: (tx: DrizzleDb) => Promise<unknown>) => Promise<unknown> }).transaction(
43
+ async (tx: DrizzleDb) => {
44
+ // Atomic increment: UPDATE ... SET next_index = next_index + 1 RETURNING *
45
+ const [method] = await tx
46
+ .update(paymentMethods)
47
+ .set({ nextIndex: sql`${paymentMethods.nextIndex} + 1` })
48
+ .where(eq(paymentMethods.id, chainId))
49
+ .returning();
50
+
51
+ if (!method) throw new Error(`Chain not found: ${chainId}`);
52
+ if (!method.xpub) throw new Error(`No xpub configured for chain: ${chainId}`);
53
+
54
+ // The index we use is the value BEFORE increment (returned value - 1)
55
+ const index = method.nextIndex - 1;
56
+
57
+ // Route to the right derivation function
58
+ let address: string;
59
+ if (method.type === "native" && method.chain === "dogecoin") {
60
+ address = deriveP2pkhAddress(method.xpub, index, "dogecoin");
61
+ } else if (method.type === "native" && (method.chain === "bitcoin" || method.chain === "litecoin")) {
62
+ address = deriveAddress(method.xpub, index, "mainnet", method.chain as "bitcoin" | "litecoin");
63
+ } else {
64
+ // EVM (all ERC20 + native ETH) — same derivation
65
+ address = deriveDepositAddress(method.xpub, index);
66
+ }
67
+
68
+ // Record in immutable log (inside same transaction)
69
+ await tx.insert(derivedAddresses).values({
70
+ chainId,
71
+ derivationIndex: index,
72
+ address: address.toLowerCase(),
73
+ tenantId,
74
+ });
75
+
76
+ return { address, index, chain: method.chain, token: method.token };
77
+ },
78
+ ) as Promise<{ address: string; index: number; chain: string; token: string }>;
79
+ }
80
+
81
+ /** Validate Bearer token from Authorization header. */
82
+ function requireAuth(header: string | undefined, expected: string): boolean {
83
+ if (!expected) return true; // auth disabled
84
+ return header === `Bearer ${expected}`;
85
+ }
86
+
87
+ /**
88
+ * Create the Hono app for the crypto key server.
89
+ * Mount this on the chain server at the root.
90
+ */
91
+ export function createKeyServerApp(deps: KeyServerDeps): Hono {
92
+ const app = new Hono();
93
+
94
+ // --- Auth middleware for product routes ---
95
+ app.use("/address", async (c, next) => {
96
+ if (deps.serviceKey && !requireAuth(c.req.header("Authorization"), deps.serviceKey)) {
97
+ return c.json({ error: "Unauthorized" }, 401);
98
+ }
99
+ await next();
100
+ });
101
+ app.use("/charges/*", async (c, next) => {
102
+ if (deps.serviceKey && !requireAuth(c.req.header("Authorization"), deps.serviceKey)) {
103
+ return c.json({ error: "Unauthorized" }, 401);
104
+ }
105
+ await next();
106
+ });
107
+ app.use("/charges", async (c, next) => {
108
+ if (deps.serviceKey && !requireAuth(c.req.header("Authorization"), deps.serviceKey)) {
109
+ return c.json({ error: "Unauthorized" }, 401);
110
+ }
111
+ await next();
112
+ });
113
+
114
+ // --- Auth middleware for admin routes ---
115
+ app.use("/admin/*", async (c, next) => {
116
+ if (!deps.adminToken) return c.json({ error: "Admin API disabled" }, 403);
117
+ if (!requireAuth(c.req.header("Authorization"), deps.adminToken)) {
118
+ return c.json({ error: "Unauthorized" }, 401);
119
+ }
120
+ await next();
121
+ });
122
+
123
+ // --- Product API ---
124
+
125
+ /** POST /address — derive next unused address */
126
+ app.post("/address", async (c) => {
127
+ const body = await c.req.json<{ chain: string }>();
128
+ if (!body.chain) return c.json({ error: "chain is required" }, 400);
129
+
130
+ const tenantId = c.req.header("X-Tenant-Id");
131
+ const result = await deriveNextAddress(deps.db, body.chain, tenantId ?? undefined);
132
+ return c.json(result, 201);
133
+ });
134
+
135
+ /** POST /charges — create charge + derive address + start watching */
136
+ app.post("/charges", async (c) => {
137
+ const body = await c.req.json<{
138
+ chain: string;
139
+ amountUsd: number;
140
+ callbackUrl?: string;
141
+ metadata?: Record<string, unknown>;
142
+ }>();
143
+
144
+ if (!body.chain || typeof body.amountUsd !== "number" || !Number.isFinite(body.amountUsd) || body.amountUsd <= 0) {
145
+ return c.json({ error: "chain is required and amountUsd must be a positive finite number" }, 400);
146
+ }
147
+
148
+ const tenantId = c.req.header("X-Tenant-Id") ?? "unknown";
149
+ const { address, index, chain, token } = await deriveNextAddress(deps.db, body.chain, tenantId);
150
+
151
+ // Look up payment method for decimals + oracle config
152
+ const method = await deps.methodStore.getById(body.chain);
153
+ if (!method) return c.json({ error: `Unknown chain: ${body.chain}` }, 400);
154
+
155
+ const amountUsdCents = Math.round(body.amountUsd * 100);
156
+
157
+ // Compute expected crypto amount in native base units.
158
+ // Price is locked NOW — this is what the user must send.
159
+ let expectedAmount: bigint;
160
+ if (method.oracleAddress) {
161
+ // Volatile asset (BTC, ETH, DOGE) — oracle-priced
162
+ const { priceCents } = await deps.oracle.getPrice(token);
163
+ expectedAmount = centsToNative(amountUsdCents, priceCents, method.decimals);
164
+ } else {
165
+ // Stablecoin (1:1 USD) — e.g. $50 USDC = 50_000_000 base units (6 decimals)
166
+ expectedAmount = (BigInt(amountUsdCents) * 10n ** BigInt(method.decimals)) / 100n;
167
+ }
168
+
169
+ const referenceId = `${token.toLowerCase()}:${address.toLowerCase()}`;
170
+
171
+ await deps.chargeStore.createStablecoinCharge({
172
+ referenceId,
173
+ tenantId,
174
+ amountUsdCents,
175
+ chain,
176
+ token,
177
+ depositAddress: address,
178
+ derivationIndex: index,
179
+ callbackUrl: body.callbackUrl,
180
+ expectedAmount: expectedAmount.toString(),
181
+ });
182
+
183
+ // Format display amount for the client
184
+ const divisor = 10 ** method.decimals;
185
+ const displayAmount = `${(Number(expectedAmount) / divisor).toFixed(Math.min(method.decimals, 8))} ${token}`;
186
+
187
+ return c.json(
188
+ {
189
+ chargeId: referenceId,
190
+ address,
191
+ chain,
192
+ token,
193
+ amountUsd: body.amountUsd,
194
+ expectedAmount: expectedAmount.toString(),
195
+ displayAmount,
196
+ derivationIndex: index,
197
+ expiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(), // 30 min
198
+ },
199
+ 201,
200
+ );
201
+ });
202
+
203
+ /** GET /charges/:id — check charge status */
204
+ app.get("/charges/:id", async (c) => {
205
+ const charge = await deps.chargeStore.getByReferenceId(c.req.param("id"));
206
+ if (!charge) return c.json({ error: "Charge not found" }, 404);
207
+
208
+ return c.json({
209
+ chargeId: charge.referenceId,
210
+ status: charge.status,
211
+ address: charge.depositAddress,
212
+ chain: charge.chain,
213
+ token: charge.token,
214
+ amountUsdCents: charge.amountUsdCents,
215
+ creditedAt: charge.creditedAt,
216
+ });
217
+ });
218
+
219
+ /** GET /chains — list enabled payment methods (for checkout UI) */
220
+ app.get("/chains", async (c) => {
221
+ const methods = await deps.methodStore.listEnabled();
222
+ return c.json(
223
+ methods.map((m) => ({
224
+ id: m.id,
225
+ token: m.token,
226
+ chain: m.chain,
227
+ decimals: m.decimals,
228
+ displayName: m.displayName,
229
+ contractAddress: m.contractAddress,
230
+ confirmations: m.confirmations,
231
+ })),
232
+ );
233
+ });
234
+
235
+ // --- Admin API ---
236
+
237
+ /** GET /admin/next-path — which derivation path to use for a coin type */
238
+ app.get("/admin/next-path", async (c) => {
239
+ const coinType = Number(c.req.query("coin_type"));
240
+ if (!Number.isInteger(coinType)) return c.json({ error: "coin_type must be an integer" }, 400);
241
+
242
+ // Find all allocations for this coin type
243
+ const existing = await deps.db.select().from(pathAllocations).where(eq(pathAllocations.coinType, coinType));
244
+
245
+ if (existing.length === 0) {
246
+ return c.json({
247
+ coin_type: coinType,
248
+ account_index: 0,
249
+ path: `m/44'/${coinType}'/0'`,
250
+ status: "available",
251
+ });
252
+ }
253
+
254
+ // If already allocated, return info about existing allocation
255
+ const latest = existing.sort(
256
+ (a: { accountIndex: number }, b: { accountIndex: number }) => b.accountIndex - a.accountIndex,
257
+ )[0];
258
+
259
+ // Find chains using this coin type's allocations
260
+ const chainIds = existing.map((a: { chainId: string | null }) => a.chainId).filter(Boolean);
261
+ return c.json({
262
+ coin_type: coinType,
263
+ account_index: latest.accountIndex,
264
+ path: `m/44'/${coinType}'/${latest.accountIndex}'`,
265
+ status: "allocated",
266
+ allocated_to: chainIds,
267
+ note: "xpub already registered — reuse for new chains with same key type",
268
+ next_available: {
269
+ account_index: latest.accountIndex + 1,
270
+ path: `m/44'/${coinType}'/${latest.accountIndex + 1}'`,
271
+ },
272
+ });
273
+ });
274
+
275
+ /** POST /admin/chains — register a new chain with its xpub */
276
+ app.post("/admin/chains", async (c) => {
277
+ const body = await c.req.json<{
278
+ id: string;
279
+ coin_type: number;
280
+ account_index: number;
281
+ network: string;
282
+ type: string;
283
+ token: string;
284
+ chain: string;
285
+ contract?: string;
286
+ decimals: number;
287
+ xpub: string;
288
+ rpc_url: string;
289
+ confirmations?: number;
290
+ display_name?: string;
291
+ oracle_address?: string;
292
+ }>();
293
+
294
+ if (!body.id || !body.xpub || !body.token) {
295
+ return c.json({ error: "id, xpub, and token are required" }, 400);
296
+ }
297
+
298
+ // Record the path allocation (idempotent — ignore if already exists)
299
+ const inserted = (await deps.db
300
+ .insert(pathAllocations)
301
+ .values({
302
+ coinType: body.coin_type,
303
+ accountIndex: body.account_index,
304
+ chainId: body.id,
305
+ xpub: body.xpub,
306
+ })
307
+ .onConflictDoNothing()) as { rowCount: number };
308
+
309
+ if (inserted.rowCount === 0) {
310
+ return c.json(
311
+ { error: "Path allocation already exists", path: `m/44'/${body.coin_type}'/${body.account_index}'` },
312
+ 409,
313
+ );
314
+ }
315
+
316
+ // Upsert the payment method
317
+ await deps.methodStore.upsert({
318
+ id: body.id,
319
+ type: body.type ?? "native",
320
+ token: body.token,
321
+ chain: body.chain ?? body.network,
322
+ contractAddress: body.contract ?? null,
323
+ decimals: body.decimals,
324
+ displayName: body.display_name ?? `${body.token} on ${body.network}`,
325
+ enabled: true,
326
+ displayOrder: 0,
327
+ rpcUrl: body.rpc_url,
328
+ oracleAddress: body.oracle_address ?? null,
329
+ xpub: body.xpub,
330
+ confirmations: body.confirmations ?? 6,
331
+ });
332
+
333
+ return c.json({ id: body.id, path: `m/44'/${body.coin_type}'/${body.account_index}'` }, 201);
334
+ });
335
+
336
+ /** DELETE /admin/chains/:id — soft disable */
337
+ app.delete("/admin/chains/:id", async (c) => {
338
+ await deps.methodStore.setEnabled(c.req.param("id"), false);
339
+ return c.body(null, 204);
340
+ });
341
+
342
+ return app;
343
+ }