@dakota-xyz/ts-sdk 1.0.15

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.
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Webhook event types and parsing.
3
+ */
4
+ /**
5
+ * Known webhook event types.
6
+ *
7
+ * These match the canonical EventType enum from the Dakota Platform API.
8
+ * Use wildcards with the handler for flexible matching (e.g., 'customer.*').
9
+ */
10
+ declare enum WebhookEventType {
11
+ UserCreated = "user.created",
12
+ UserUpdated = "user.updated",
13
+ UserDeleted = "user.deleted",
14
+ ApiKeyCreated = "api_key.created",
15
+ ApiKeyDeleted = "api_key.deleted",
16
+ CustomerCreated = "customer.created",
17
+ CustomerUpdated = "customer.updated",
18
+ CustomerKybLinkCreated = "customer.kyb_link.created",
19
+ CustomerKybLinkUpdated = "customer.kyb_link.updated",
20
+ CustomerKybStatusCreated = "customer.kyb_status.created",
21
+ CustomerKybStatusUpdated = "customer.kyb_status.updated",
22
+ CustomerKybApplicationSubmitted = "customer.kyb_application.submitted",
23
+ AutoAccountCreated = "auto_account.created",
24
+ AutoAccountUpdated = "auto_account.updated",
25
+ AutoAccountDeleted = "auto_account.deleted",
26
+ /** Auto transaction created (from off-ramp/on-ramp accounts) */
27
+ TransactionAutoCreated = "transaction.auto.created",
28
+ /** Auto transaction updated */
29
+ TransactionAutoUpdated = "transaction.auto.updated",
30
+ /** One-off transaction created */
31
+ TransactionOneOffCreated = "transaction.one_off.created",
32
+ /** One-off transaction updated */
33
+ TransactionOneOffUpdated = "transaction.one_off.updated",
34
+ RecipientCreated = "recipient.created",
35
+ RecipientUpdated = "recipient.updated",
36
+ RecipientDeleted = "recipient.deleted",
37
+ DestinationCreated = "destination.created",
38
+ DestinationDeleted = "destination.deleted",
39
+ TargetCreated = "target.created",
40
+ TargetUpdated = "target.updated",
41
+ TargetDeleted = "target.deleted",
42
+ ExceptionCreated = "exception.created",
43
+ ExceptionCleared = "exception.cleared",
44
+ BvnkOnboardingCreated = "bvnk.onboarding.created",
45
+ BvnkOnboardingUpdated = "bvnk.onboarding.updated",
46
+ WalletCreated = "wallet.created",
47
+ WalletUpdated = "wallet.updated",
48
+ WalletSignerGroupCreated = "wallet.signer_group.created",
49
+ WalletSignerGroupUpdated = "wallet.signer_group.updated",
50
+ WalletPolicyCreated = "wallet.policy.created",
51
+ WalletPolicyUpdated = "wallet.policy.updated",
52
+ WalletTransactionCreated = "wallet.transaction.created",
53
+ WalletTransactionUpdated = "wallet.transaction.updated",
54
+ WalletDeposit = "wallet.deposit",
55
+ /** @deprecated Use TransactionAutoCreated or TransactionOneOffCreated */
56
+ TransactionCreated = "transaction.created",
57
+ /** @deprecated Use TransactionAutoUpdated or TransactionOneOffUpdated */
58
+ TransactionUpdated = "transaction.updated",
59
+ /** @deprecated Check transaction status in the updated event */
60
+ TransactionCompleted = "transaction.completed",
61
+ /** @deprecated Check transaction status in the updated event */
62
+ TransactionFailed = "transaction.failed",
63
+ /** @deprecated Check transaction status in the updated event */
64
+ TransactionCancelled = "transaction.cancelled",
65
+ /** @deprecated Use AutoAccountCreated */
66
+ AccountCreated = "account.created",
67
+ /** @deprecated Use AutoAccountUpdated */
68
+ AccountUpdated = "account.updated"
69
+ }
70
+ /**
71
+ * Webhook event structure.
72
+ */
73
+ interface WebhookEvent<T = unknown> {
74
+ /** Unique event ID */
75
+ id: string;
76
+ /** Event type */
77
+ type: string;
78
+ /** Event data payload */
79
+ data: T;
80
+ /** Unix timestamp when the event was created */
81
+ created_at: number;
82
+ /** API version */
83
+ api_version?: string;
84
+ }
85
+ /**
86
+ * Parse a webhook event from a JSON payload.
87
+ *
88
+ * @param payload - Raw JSON payload (string or Buffer)
89
+ * @returns Parsed webhook event
90
+ * @throws Error if parsing fails
91
+ */
92
+ declare function parseEvent<T = unknown>(payload: string | Uint8Array): WebhookEvent<T>;
93
+ /**
94
+ * Check if an event type matches a pattern.
95
+ *
96
+ * Supports wildcards: 'customer.*' matches 'customer.created', 'customer.updated', etc.
97
+ */
98
+ declare function matchesEventType(eventType: string, pattern: string): boolean;
99
+
100
+ /**
101
+ * Idempotency store for webhook event deduplication.
102
+ */
103
+ /**
104
+ * Interface for idempotency stores.
105
+ */
106
+ interface IdempotencyStore {
107
+ /**
108
+ * Check if an event has been seen before.
109
+ *
110
+ * @param eventId - Event ID to check
111
+ * @returns true if event was already processed
112
+ */
113
+ has(eventId: string): Promise<boolean> | boolean;
114
+ /**
115
+ * Mark an event as seen.
116
+ *
117
+ * @param eventId - Event ID to mark
118
+ */
119
+ add(eventId: string): Promise<void> | void;
120
+ }
121
+ /**
122
+ * In-memory idempotency store.
123
+ *
124
+ * Suitable for single-process applications. For distributed systems,
125
+ * use a Redis-based or database-backed implementation.
126
+ */
127
+ declare class MemoryIdempotencyStore implements IdempotencyStore {
128
+ private readonly seen;
129
+ private readonly maxSize;
130
+ private readonly ttlMs;
131
+ private readonly timestamps;
132
+ /**
133
+ * Create a new in-memory idempotency store.
134
+ *
135
+ * @param options - Store options
136
+ * @param options.maxSize - Maximum number of event IDs to store (default: 10000)
137
+ * @param options.ttlMs - Time-to-live in milliseconds (default: 24 hours)
138
+ */
139
+ constructor(options?: {
140
+ maxSize?: number;
141
+ ttlMs?: number;
142
+ });
143
+ /**
144
+ * Check if an event has been seen.
145
+ */
146
+ has(eventId: string): boolean;
147
+ /**
148
+ * Mark an event as seen.
149
+ */
150
+ add(eventId: string): void;
151
+ /**
152
+ * Get the number of stored event IDs.
153
+ */
154
+ get size(): number;
155
+ /**
156
+ * Clear all stored event IDs.
157
+ */
158
+ clear(): void;
159
+ /**
160
+ * Remove expired entries.
161
+ */
162
+ private cleanup;
163
+ /**
164
+ * Find the oldest entry.
165
+ */
166
+ private findOldest;
167
+ }
168
+
169
+ /**
170
+ * Webhook handler for processing incoming webhooks.
171
+ */
172
+
173
+ /**
174
+ * Webhook event handler function.
175
+ */
176
+ type WebhookEventHandler<T = unknown> = (event: WebhookEvent<T>) => Promise<void> | void;
177
+ /**
178
+ * Webhook handler configuration.
179
+ */
180
+ interface WebhookHandlerConfig {
181
+ /** Hex-encoded Ed25519 public key for signature verification */
182
+ publicKey: string;
183
+ /** Timestamp tolerance in seconds (default: 300) */
184
+ timestampTolerance?: number;
185
+ /** Maximum payload size in bytes (default: 65536) */
186
+ maxPayloadSize?: number;
187
+ /** Idempotency store for deduplication (default: in-memory) */
188
+ idempotencyStore?: IdempotencyStore | false;
189
+ }
190
+ /**
191
+ * Headers object type (works with various HTTP frameworks).
192
+ */
193
+ interface WebhookHeaders {
194
+ [key: string]: string | string[] | undefined;
195
+ }
196
+ /**
197
+ * Webhook handler for verifying and processing incoming webhooks.
198
+ *
199
+ * @example
200
+ * ```typescript
201
+ * import { WebhookHandler, WebhookEventType } from 'dakota-ts-sdk/webhook';
202
+ *
203
+ * const handler = new WebhookHandler({
204
+ * publicKey: process.env.WEBHOOK_PUBLIC_KEY!,
205
+ * });
206
+ *
207
+ * // Register event handlers
208
+ * handler.on(WebhookEventType.CustomerCreated, async (event) => {
209
+ * console.log('Customer created:', event.data);
210
+ * });
211
+ *
212
+ * handler.on('transaction.*', async (event) => {
213
+ * console.log('Transaction event:', event.type, event.data);
214
+ * });
215
+ *
216
+ * handler.onDefault(async (event) => {
217
+ * console.log('Unhandled event:', event.type);
218
+ * });
219
+ *
220
+ * // In your HTTP handler
221
+ * app.post('/webhooks/dakota', async (req, res) => {
222
+ * try {
223
+ * await handler.handleRequest(req.body, req.headers);
224
+ * res.status(200).send('OK');
225
+ * } catch (error) {
226
+ * console.error('Webhook error:', error);
227
+ * res.status(400).send(error.message);
228
+ * }
229
+ * });
230
+ * ```
231
+ */
232
+ declare class WebhookHandler {
233
+ private readonly publicKey;
234
+ private readonly timestampTolerance;
235
+ private readonly maxPayloadSize;
236
+ private readonly idempotencyStore;
237
+ private readonly handlers;
238
+ private defaultHandler;
239
+ /**
240
+ * Create a new webhook handler.
241
+ *
242
+ * @param config - Handler configuration
243
+ */
244
+ constructor(config: WebhookHandlerConfig);
245
+ /**
246
+ * Register a handler for specific event types.
247
+ *
248
+ * Supports wildcards: 'customer.*' matches all customer events.
249
+ *
250
+ * @param eventType - Event type or pattern to handle
251
+ * @param handler - Handler function
252
+ * @returns this for chaining
253
+ *
254
+ * @example
255
+ * ```typescript
256
+ * handler
257
+ * .on('customer.created', handleCustomerCreated)
258
+ * .on('transaction.*', handleTransactionEvents)
259
+ * .on('*', logAllEvents);
260
+ * ```
261
+ */
262
+ on<T = unknown>(eventType: string, handler: WebhookEventHandler<T>): this;
263
+ /**
264
+ * Register a default handler for unmatched events.
265
+ *
266
+ * @param handler - Handler function
267
+ * @returns this for chaining
268
+ */
269
+ onDefault<T = unknown>(handler: WebhookEventHandler<T>): this;
270
+ /**
271
+ * Handle an incoming webhook request.
272
+ *
273
+ * @param body - Raw request body (string or Buffer)
274
+ * @param headers - Request headers
275
+ * @throws SignatureVerificationError if signature is invalid
276
+ * @throws Error if payload is invalid or too large
277
+ *
278
+ * @example
279
+ * ```typescript
280
+ * // Express with raw body parser
281
+ * app.post('/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
282
+ * try {
283
+ * await handler.handleRequest(req.body, req.headers);
284
+ * res.sendStatus(200);
285
+ * } catch (error) {
286
+ * res.status(400).send(error.message);
287
+ * }
288
+ * });
289
+ * ```
290
+ */
291
+ handleRequest(body: string | Uint8Array | Buffer, headers: WebhookHeaders): Promise<WebhookEvent>;
292
+ /**
293
+ * Construct a webhook event from payload and verify signature.
294
+ *
295
+ * Use this when you need to verify and parse without dispatching.
296
+ *
297
+ * @param payload - Raw request body
298
+ * @param signature - X-Webhook-Signature header value
299
+ * @param timestamp - X-Webhook-Timestamp header value
300
+ * @returns Parsed and verified event
301
+ */
302
+ constructEvent<T = unknown>(payload: string | Uint8Array, signature: string, timestamp: string): Promise<WebhookEvent<T>>;
303
+ /**
304
+ * Create Express-compatible middleware.
305
+ *
306
+ * @returns Express middleware function
307
+ *
308
+ * @example
309
+ * ```typescript
310
+ * import express from 'express';
311
+ *
312
+ * const app = express();
313
+ *
314
+ * app.post(
315
+ * '/webhooks/dakota',
316
+ * express.raw({ type: 'application/json' }),
317
+ * handler.expressMiddleware()
318
+ * );
319
+ * ```
320
+ */
321
+ expressMiddleware(): (req: {
322
+ body: Buffer | string;
323
+ headers: WebhookHeaders;
324
+ }, res: {
325
+ status: (code: number) => {
326
+ send: (body: string) => void;
327
+ };
328
+ sendStatus: (code: number) => void;
329
+ }, next: (error?: Error) => void) => Promise<void>;
330
+ /**
331
+ * Dispatch an event to registered handlers.
332
+ */
333
+ private dispatch;
334
+ /**
335
+ * Get a header value (case-insensitive).
336
+ */
337
+ private getHeader;
338
+ }
339
+
340
+ /**
341
+ * Webhook signature verification using Ed25519.
342
+ */
343
+ /** Default timestamp tolerance in seconds (5 minutes) */
344
+ declare const DEFAULT_TIMESTAMP_TOLERANCE = 300;
345
+ /** Webhook signature header name */
346
+ declare const SIGNATURE_HEADER = "x-webhook-signature";
347
+ /** Webhook timestamp header name */
348
+ declare const TIMESTAMP_HEADER = "x-webhook-timestamp";
349
+ /**
350
+ * Error thrown when signature verification fails.
351
+ */
352
+ declare class SignatureVerificationError extends Error {
353
+ constructor(message: string);
354
+ }
355
+ /**
356
+ * Parse a hex-encoded Ed25519 public key.
357
+ *
358
+ * @param hexKey - Hex-encoded public key (64 characters)
359
+ * @returns Parsed public key as Uint8Array
360
+ * @throws SignatureVerificationError if the key is invalid
361
+ */
362
+ declare function parsePublicKey(hexKey: string): Uint8Array;
363
+ /**
364
+ * Parse a base64-encoded Ed25519 signature.
365
+ *
366
+ * @param signatureB64 - Base64-encoded signature
367
+ * @returns Parsed signature as Uint8Array
368
+ * @throws SignatureVerificationError if the signature is invalid
369
+ */
370
+ declare function parseSignature(signatureB64: string): Uint8Array;
371
+ /**
372
+ * Validate the timestamp is within tolerance.
373
+ *
374
+ * @param timestampStr - Unix timestamp as string
375
+ * @param toleranceSeconds - Maximum age in seconds
376
+ * @throws SignatureVerificationError if timestamp is invalid or expired
377
+ */
378
+ declare function validateTimestamp(timestampStr: string, toleranceSeconds: number): void;
379
+ /**
380
+ * Verify a webhook signature.
381
+ *
382
+ * @param payload - The raw request body
383
+ * @param signatureB64 - The X-Webhook-Signature header value (base64)
384
+ * @param timestampStr - The X-Webhook-Timestamp header value
385
+ * @param publicKeyHex - Your webhook public key (hex-encoded)
386
+ * @param toleranceSeconds - Maximum timestamp age (default: 300 seconds)
387
+ * @returns Promise that resolves if verification succeeds
388
+ * @throws SignatureVerificationError if verification fails
389
+ *
390
+ * @example
391
+ * ```typescript
392
+ * await verifySignature(
393
+ * requestBody,
394
+ * request.headers['x-webhook-signature'],
395
+ * request.headers['x-webhook-timestamp'],
396
+ * process.env.WEBHOOK_PUBLIC_KEY
397
+ * );
398
+ * ```
399
+ */
400
+ declare function verifySignature(payload: Uint8Array | string, signatureB64: string, timestampStr: string, publicKeyHex: string, toleranceSeconds?: number): Promise<void>;
401
+ /**
402
+ * Synchronous signature verification (if available).
403
+ *
404
+ * Note: This may not work in all environments. Use verifySignature for
405
+ * guaranteed compatibility.
406
+ */
407
+ declare function verifySignatureSync(payload: Uint8Array | string, signatureB64: string, timestampStr: string, publicKeyHex: string, toleranceSeconds?: number): void;
408
+
409
+ export { DEFAULT_TIMESTAMP_TOLERANCE, type IdempotencyStore, MemoryIdempotencyStore, SIGNATURE_HEADER, SignatureVerificationError, TIMESTAMP_HEADER, type WebhookEvent, type WebhookEventHandler, WebhookEventType, WebhookHandler, type WebhookHandlerConfig, type WebhookHeaders, matchesEventType, parseEvent, parsePublicKey, parseSignature, validateTimestamp, verifySignature, verifySignatureSync };