@openfacilitator/sdk 0.2.0 → 0.5.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/dist/index.js CHANGED
@@ -28,14 +28,24 @@ __export(index_exports, {
28
28
  SettlementError: () => SettlementError,
29
29
  VerificationError: () => VerificationError,
30
30
  createDefaultFacilitator: () => createDefaultFacilitator,
31
+ createPaymentContext: () => createPaymentContext,
32
+ createPaymentMiddleware: () => createPaymentMiddleware,
33
+ createRefundMiddleware: () => createRefundMiddleware,
34
+ executeClaim: () => executeClaim,
35
+ getClaimHistory: () => getClaimHistory,
36
+ getClaimable: () => getClaimable,
31
37
  getMainnets: () => getMainnets,
32
38
  getNetwork: () => getNetwork,
33
39
  getNetworkType: () => getNetworkType,
34
40
  getTestnets: () => getTestnets,
41
+ honoPaymentMiddleware: () => honoPaymentMiddleware,
42
+ honoRefundMiddleware: () => honoRefundMiddleware,
35
43
  isPaymentPayload: () => isPaymentPayload,
36
44
  isValidNetwork: () => isValidNetwork,
45
+ reportFailure: () => reportFailure,
37
46
  toV1NetworkId: () => toV1NetworkId,
38
- toV2NetworkId: () => toV2NetworkId
47
+ toV2NetworkId: () => toV2NetworkId,
48
+ withRefundProtection: () => withRefundProtection
39
49
  });
40
50
  module.exports = __toCommonJS(index_exports);
41
51
 
@@ -334,6 +344,422 @@ function getMainnets() {
334
344
  function getTestnets() {
335
345
  return NETWORKS.filter((n) => n.testnet);
336
346
  }
347
+
348
+ // src/claims.ts
349
+ async function reportFailure(params) {
350
+ const {
351
+ facilitatorUrl,
352
+ apiKey,
353
+ originalTxHash,
354
+ userWallet,
355
+ amount,
356
+ asset,
357
+ network,
358
+ reason
359
+ } = params;
360
+ const baseUrl = facilitatorUrl.replace(/\/$/, "");
361
+ try {
362
+ const response = await fetch(`${baseUrl}/claims/report-failure`, {
363
+ method: "POST",
364
+ headers: {
365
+ "Content-Type": "application/json",
366
+ "X-Server-Api-Key": apiKey
367
+ },
368
+ body: JSON.stringify({
369
+ originalTxHash,
370
+ userWallet,
371
+ amount,
372
+ asset,
373
+ network,
374
+ reason
375
+ })
376
+ });
377
+ const data = await response.json();
378
+ if (!response.ok) {
379
+ return {
380
+ success: false,
381
+ error: data.error || `HTTP ${response.status}`
382
+ };
383
+ }
384
+ return data;
385
+ } catch (error) {
386
+ return {
387
+ success: false,
388
+ error: error instanceof Error ? error.message : "Unknown error"
389
+ };
390
+ }
391
+ }
392
+ async function getClaimable(params) {
393
+ const { facilitatorUrl, wallet, facilitator } = params;
394
+ const baseUrl = facilitatorUrl.replace(/\/$/, "");
395
+ const queryParams = new URLSearchParams({ wallet });
396
+ if (facilitator) {
397
+ queryParams.set("facilitator", facilitator);
398
+ }
399
+ const response = await fetch(`${baseUrl}/api/claims?${queryParams.toString()}`);
400
+ const data = await response.json();
401
+ if (!response.ok) {
402
+ throw new Error(data.error || `HTTP ${response.status}`);
403
+ }
404
+ return data;
405
+ }
406
+ async function getClaimHistory(params) {
407
+ const { facilitatorUrl, wallet, facilitator } = params;
408
+ const baseUrl = facilitatorUrl.replace(/\/$/, "");
409
+ const queryParams = new URLSearchParams({ wallet });
410
+ if (facilitator) {
411
+ queryParams.set("facilitator", facilitator);
412
+ }
413
+ const response = await fetch(`${baseUrl}/api/claims/history?${queryParams.toString()}`);
414
+ const data = await response.json();
415
+ if (!response.ok) {
416
+ throw new Error(data.error || `HTTP ${response.status}`);
417
+ }
418
+ return data;
419
+ }
420
+ async function executeClaim(params) {
421
+ const { facilitatorUrl, claimId, signature } = params;
422
+ const baseUrl = facilitatorUrl.replace(/\/$/, "");
423
+ try {
424
+ const response = await fetch(`${baseUrl}/api/claims/${claimId}/execute`, {
425
+ method: "POST",
426
+ headers: {
427
+ "Content-Type": "application/json"
428
+ },
429
+ body: JSON.stringify({ signature })
430
+ });
431
+ const data = await response.json();
432
+ if (!response.ok) {
433
+ return {
434
+ success: false,
435
+ error: data.error || `HTTP ${response.status}`
436
+ };
437
+ }
438
+ return data;
439
+ } catch (error) {
440
+ return {
441
+ success: false,
442
+ error: error instanceof Error ? error.message : "Unknown error"
443
+ };
444
+ }
445
+ }
446
+
447
+ // src/middleware.ts
448
+ function withRefundProtection(config, handler) {
449
+ return async (context) => {
450
+ try {
451
+ return await handler(context);
452
+ } catch (error) {
453
+ const err = error instanceof Error ? error : new Error(String(error));
454
+ if (config.shouldReport && !config.shouldReport(err)) {
455
+ throw error;
456
+ }
457
+ try {
458
+ const result = await reportFailure({
459
+ facilitatorUrl: config.facilitatorUrl,
460
+ apiKey: config.apiKey,
461
+ originalTxHash: context.transactionHash,
462
+ userWallet: context.userWallet,
463
+ amount: context.amount,
464
+ asset: context.asset,
465
+ network: context.network,
466
+ reason: err.message
467
+ });
468
+ if (config.onReport) {
469
+ config.onReport(result.claimId, err);
470
+ }
471
+ } catch (reportError) {
472
+ if (config.onReportError) {
473
+ config.onReportError(
474
+ reportError instanceof Error ? reportError : new Error(String(reportError)),
475
+ err
476
+ );
477
+ }
478
+ }
479
+ throw error;
480
+ }
481
+ };
482
+ }
483
+ function createRefundMiddleware(config) {
484
+ return async (req, res, next) => {
485
+ const originalNext = next;
486
+ const paymentContext = res.locals?.paymentContext || req.paymentContext;
487
+ if (!paymentContext) {
488
+ return originalNext();
489
+ }
490
+ const wrappedNext = async (error) => {
491
+ if (error) {
492
+ const err = error instanceof Error ? error : new Error(String(error));
493
+ if (!config.shouldReport || config.shouldReport(err)) {
494
+ try {
495
+ const result = await reportFailure({
496
+ facilitatorUrl: config.facilitatorUrl,
497
+ apiKey: config.apiKey,
498
+ originalTxHash: paymentContext.transactionHash,
499
+ userWallet: paymentContext.userWallet,
500
+ amount: paymentContext.amount,
501
+ asset: paymentContext.asset,
502
+ network: paymentContext.network,
503
+ reason: err.message
504
+ });
505
+ if (config.onReport) {
506
+ config.onReport(result.claimId, err);
507
+ }
508
+ } catch (reportError) {
509
+ if (config.onReportError) {
510
+ config.onReportError(
511
+ reportError instanceof Error ? reportError : new Error(String(reportError)),
512
+ err
513
+ );
514
+ }
515
+ }
516
+ }
517
+ }
518
+ originalNext(error);
519
+ };
520
+ next = wrappedNext;
521
+ originalNext();
522
+ };
523
+ }
524
+ function honoRefundMiddleware(config) {
525
+ return async (c, next) => {
526
+ const paymentContext = config.getPaymentContext(c);
527
+ if (!paymentContext) {
528
+ return next();
529
+ }
530
+ try {
531
+ await next();
532
+ } catch (error) {
533
+ const err = error instanceof Error ? error : new Error(String(error));
534
+ if (!config.shouldReport || config.shouldReport(err)) {
535
+ try {
536
+ const result = await reportFailure({
537
+ facilitatorUrl: config.facilitatorUrl,
538
+ apiKey: config.apiKey,
539
+ originalTxHash: paymentContext.transactionHash,
540
+ userWallet: paymentContext.userWallet,
541
+ amount: paymentContext.amount,
542
+ asset: paymentContext.asset,
543
+ network: paymentContext.network,
544
+ reason: err.message
545
+ });
546
+ if (config.onReport) {
547
+ config.onReport(result.claimId, err);
548
+ }
549
+ } catch (reportError) {
550
+ if (config.onReportError) {
551
+ config.onReportError(
552
+ reportError instanceof Error ? reportError : new Error(String(reportError)),
553
+ err
554
+ );
555
+ }
556
+ }
557
+ }
558
+ throw error;
559
+ }
560
+ };
561
+ }
562
+ function createPaymentContext(settleResponse, paymentPayload) {
563
+ return {
564
+ transactionHash: settleResponse.transaction,
565
+ userWallet: settleResponse.payer,
566
+ amount: paymentPayload.payload.authorization.amount,
567
+ asset: paymentPayload.payload.authorization.asset,
568
+ network: settleResponse.network
569
+ };
570
+ }
571
+ function createPaymentMiddleware(config) {
572
+ const facilitator = typeof config.facilitator === "string" ? new OpenFacilitator({ url: config.facilitator }) : config.facilitator;
573
+ return async (req, res, next) => {
574
+ try {
575
+ const requirements = await config.getRequirements(req);
576
+ const paymentHeader = req.headers["x-payment"];
577
+ const paymentString = Array.isArray(paymentHeader) ? paymentHeader[0] : paymentHeader;
578
+ if (!paymentString) {
579
+ if (config.on402) {
580
+ await config.on402(req, res, requirements);
581
+ } else {
582
+ const extra = {
583
+ ...requirements.extra
584
+ };
585
+ if (config.refundProtection) {
586
+ extra.supportsRefunds = true;
587
+ }
588
+ res.status(402).json({
589
+ error: "Payment Required",
590
+ accepts: [{
591
+ scheme: requirements.scheme,
592
+ network: requirements.network,
593
+ maxAmountRequired: requirements.maxAmountRequired,
594
+ asset: requirements.asset,
595
+ payTo: requirements.payTo,
596
+ resource: requirements.resource || req.url,
597
+ description: requirements.description,
598
+ ...Object.keys(extra).length > 0 ? { extra } : {}
599
+ }]
600
+ });
601
+ }
602
+ return;
603
+ }
604
+ let paymentPayload;
605
+ try {
606
+ paymentPayload = JSON.parse(paymentString);
607
+ if (!isPaymentPayload(paymentPayload)) {
608
+ throw new Error("Invalid payment payload structure");
609
+ }
610
+ } catch {
611
+ res.status(400).json({ error: "Invalid X-PAYMENT header" });
612
+ return;
613
+ }
614
+ const verifyResult = await facilitator.verify(paymentPayload, requirements);
615
+ if (!verifyResult.isValid) {
616
+ res.status(402).json({
617
+ error: "Payment verification failed",
618
+ reason: verifyResult.invalidReason
619
+ });
620
+ return;
621
+ }
622
+ const settleResult = await facilitator.settle(paymentPayload, requirements);
623
+ if (!settleResult.success) {
624
+ res.status(402).json({
625
+ error: "Payment settlement failed",
626
+ reason: settleResult.errorReason
627
+ });
628
+ return;
629
+ }
630
+ const paymentContext = createPaymentContext(settleResult, paymentPayload);
631
+ req.paymentContext = paymentContext;
632
+ if (res.locals) {
633
+ res.locals.paymentContext = paymentContext;
634
+ }
635
+ if (config.refundProtection) {
636
+ const originalNext = next;
637
+ const refundConfig = config.refundProtection;
638
+ next = async (error) => {
639
+ if (error) {
640
+ const err = error instanceof Error ? error : new Error(String(error));
641
+ if (!refundConfig.shouldReport || refundConfig.shouldReport(err)) {
642
+ try {
643
+ const result = await reportFailure({
644
+ facilitatorUrl: refundConfig.facilitatorUrl,
645
+ apiKey: refundConfig.apiKey,
646
+ originalTxHash: paymentContext.transactionHash,
647
+ userWallet: paymentContext.userWallet,
648
+ amount: paymentContext.amount,
649
+ asset: paymentContext.asset,
650
+ network: paymentContext.network,
651
+ reason: err.message
652
+ });
653
+ if (refundConfig.onReport) {
654
+ refundConfig.onReport(result.claimId, err);
655
+ }
656
+ } catch (reportError) {
657
+ if (refundConfig.onReportError) {
658
+ refundConfig.onReportError(
659
+ reportError instanceof Error ? reportError : new Error(String(reportError)),
660
+ err
661
+ );
662
+ }
663
+ }
664
+ }
665
+ }
666
+ originalNext(error);
667
+ };
668
+ }
669
+ next();
670
+ } catch (error) {
671
+ next(error);
672
+ }
673
+ };
674
+ }
675
+ function honoPaymentMiddleware(config) {
676
+ const facilitator = typeof config.facilitator === "string" ? new OpenFacilitator({ url: config.facilitator }) : config.facilitator;
677
+ return async (c, next) => {
678
+ const requirements = await config.getRequirements(c);
679
+ const paymentString = c.req.header("x-payment");
680
+ if (!paymentString) {
681
+ const extra = {
682
+ ...requirements.extra
683
+ };
684
+ if (config.refundProtection) {
685
+ extra.supportsRefunds = true;
686
+ }
687
+ return c.json({
688
+ error: "Payment Required",
689
+ accepts: [{
690
+ scheme: requirements.scheme,
691
+ network: requirements.network,
692
+ maxAmountRequired: requirements.maxAmountRequired,
693
+ asset: requirements.asset,
694
+ payTo: requirements.payTo,
695
+ resource: requirements.resource || c.req.url,
696
+ description: requirements.description,
697
+ ...Object.keys(extra).length > 0 ? { extra } : {}
698
+ }]
699
+ }, 402);
700
+ }
701
+ let paymentPayload;
702
+ try {
703
+ paymentPayload = JSON.parse(paymentString);
704
+ if (!isPaymentPayload(paymentPayload)) {
705
+ throw new Error("Invalid payment payload structure");
706
+ }
707
+ } catch {
708
+ return c.json({ error: "Invalid X-PAYMENT header" }, 400);
709
+ }
710
+ const verifyResult = await facilitator.verify(paymentPayload, requirements);
711
+ if (!verifyResult.isValid) {
712
+ return c.json({
713
+ error: "Payment verification failed",
714
+ reason: verifyResult.invalidReason
715
+ }, 402);
716
+ }
717
+ const settleResult = await facilitator.settle(paymentPayload, requirements);
718
+ if (!settleResult.success) {
719
+ return c.json({
720
+ error: "Payment settlement failed",
721
+ reason: settleResult.errorReason
722
+ }, 402);
723
+ }
724
+ const paymentContext = createPaymentContext(settleResult, paymentPayload);
725
+ c.set("paymentContext", paymentContext);
726
+ if (config.refundProtection) {
727
+ const refundConfig = config.refundProtection;
728
+ try {
729
+ await next();
730
+ } catch (error) {
731
+ const err = error instanceof Error ? error : new Error(String(error));
732
+ if (!refundConfig.shouldReport || refundConfig.shouldReport(err)) {
733
+ try {
734
+ const result = await reportFailure({
735
+ facilitatorUrl: refundConfig.facilitatorUrl,
736
+ apiKey: refundConfig.apiKey,
737
+ originalTxHash: paymentContext.transactionHash,
738
+ userWallet: paymentContext.userWallet,
739
+ amount: paymentContext.amount,
740
+ asset: paymentContext.asset,
741
+ network: paymentContext.network,
742
+ reason: err.message
743
+ });
744
+ if (refundConfig.onReport) {
745
+ refundConfig.onReport(result.claimId, err);
746
+ }
747
+ } catch (reportError) {
748
+ if (refundConfig.onReportError) {
749
+ refundConfig.onReportError(
750
+ reportError instanceof Error ? reportError : new Error(String(reportError)),
751
+ err
752
+ );
753
+ }
754
+ }
755
+ }
756
+ throw error;
757
+ }
758
+ } else {
759
+ await next();
760
+ }
761
+ };
762
+ }
337
763
  // Annotate the CommonJS export names for ESM import in node:
338
764
  0 && (module.exports = {
339
765
  ConfigurationError,
@@ -344,12 +770,22 @@ function getTestnets() {
344
770
  SettlementError,
345
771
  VerificationError,
346
772
  createDefaultFacilitator,
773
+ createPaymentContext,
774
+ createPaymentMiddleware,
775
+ createRefundMiddleware,
776
+ executeClaim,
777
+ getClaimHistory,
778
+ getClaimable,
347
779
  getMainnets,
348
780
  getNetwork,
349
781
  getNetworkType,
350
782
  getTestnets,
783
+ honoPaymentMiddleware,
784
+ honoRefundMiddleware,
351
785
  isPaymentPayload,
352
786
  isValidNetwork,
787
+ reportFailure,
353
788
  toV1NetworkId,
354
- toV2NetworkId
789
+ toV2NetworkId,
790
+ withRefundProtection
355
791
  });