@bosonprotocol/x402-server 0.1.0-alpha-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 (53) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +65 -0
  3. package/dist/cjs/challenge/index.d.ts +64 -0
  4. package/dist/cjs/challenge/index.js +96 -0
  5. package/dist/cjs/challenge/index.js.map +1 -0
  6. package/dist/cjs/client-tnrpqVMW.d.ts +36 -0
  7. package/dist/cjs/config-CBr9qMps.d.ts +419 -0
  8. package/dist/cjs/facilitator/index.d.ts +26 -0
  9. package/dist/cjs/facilitator/index.js +136 -0
  10. package/dist/cjs/facilitator/index.js.map +1 -0
  11. package/dist/cjs/handlers/index.d.ts +267 -0
  12. package/dist/cjs/handlers/index.js +1182 -0
  13. package/dist/cjs/handlers/index.js.map +1 -0
  14. package/dist/cjs/index.d.ts +72 -0
  15. package/dist/cjs/index.js +1643 -0
  16. package/dist/cjs/index.js.map +1 -0
  17. package/dist/cjs/onchain/index.d.ts +73 -0
  18. package/dist/cjs/onchain/index.js +87 -0
  19. package/dist/cjs/onchain/index.js.map +1 -0
  20. package/dist/cjs/package.json +3 -0
  21. package/dist/cjs/validate/index.d.ts +67 -0
  22. package/dist/cjs/validate/index.js +429 -0
  23. package/dist/cjs/validate/index.js.map +1 -0
  24. package/dist/esm/challenge/index.js +3 -0
  25. package/dist/esm/challenge/index.js.map +1 -0
  26. package/dist/esm/chunk-4NQ3VKC3.js +84 -0
  27. package/dist/esm/chunk-4NQ3VKC3.js.map +1 -0
  28. package/dist/esm/chunk-CGVXQX5V.js +426 -0
  29. package/dist/esm/chunk-CGVXQX5V.js.map +1 -0
  30. package/dist/esm/chunk-DJMCSCBE.js +3 -0
  31. package/dist/esm/chunk-DJMCSCBE.js.map +1 -0
  32. package/dist/esm/chunk-EAKQ4EFZ.js +124 -0
  33. package/dist/esm/chunk-EAKQ4EFZ.js.map +1 -0
  34. package/dist/esm/chunk-GBPU373M.js +93 -0
  35. package/dist/esm/chunk-GBPU373M.js.map +1 -0
  36. package/dist/esm/chunk-PU5Y7FZG.js +14 -0
  37. package/dist/esm/chunk-PU5Y7FZG.js.map +1 -0
  38. package/dist/esm/chunk-WU7QJ7YP.js +3 -0
  39. package/dist/esm/chunk-WU7QJ7YP.js.map +1 -0
  40. package/dist/esm/chunk-Y5HFLCAT.js +657 -0
  41. package/dist/esm/chunk-Y5HFLCAT.js.map +1 -0
  42. package/dist/esm/facilitator/index.js +4 -0
  43. package/dist/esm/facilitator/index.js.map +1 -0
  44. package/dist/esm/handlers/index.js +6 -0
  45. package/dist/esm/handlers/index.js.map +1 -0
  46. package/dist/esm/index.js +261 -0
  47. package/dist/esm/index.js.map +1 -0
  48. package/dist/esm/onchain/index.js +4 -0
  49. package/dist/esm/onchain/index.js.map +1 -0
  50. package/dist/esm/package.json +3 -0
  51. package/dist/esm/validate/index.js +4 -0
  52. package/dist/esm/validate/index.js.map +1 -0
  53. package/package.json +88 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Boson Protocol
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # @bosonprotocol/x402-server
2
+
3
+ Framework-agnostic resource-server SDK for the Boson Protocol
4
+ [`escrow`](https://github.com/bosonprotocol/x402-escrow-schema) scheme — the
5
+ server side of [x402B](https://github.com/bosonprotocol/x402B).
6
+
7
+ See [`docs/boson-impl-05-server-sdk.md`](../../../docs/boson-impl-05-server-sdk.md)
8
+ for the spec and [`docs/boson-impl-01-escrow-scheme.md`](../../../docs/boson-impl-01-escrow-scheme.md)
9
+ for the wire format.
10
+
11
+ ## Status
12
+
13
+ **Pre-release.** v0.1 ships only the request-side primitives — the 402
14
+ challenge builder, the seller FullOffer signer hook, and the
15
+ `createX402bServer` factory that binds them together. Follow-up PRs add:
16
+
17
+ - the `X-PAYMENT` 13-rule validator,
18
+ - the facilitator HTTP client (talks to `@bosonprotocol/x402-facilitator`),
19
+ - the convenience handlers (`commit-and-redeem`, `complete`, `dispute/*`),
20
+ - a framework adapter (`@bosonprotocol/x402-server-express`).
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ pnpm add @bosonprotocol/x402-server @bosonprotocol/x402-core @bosonprotocol/x402-actions
26
+ ```
27
+
28
+ ## Quick start
29
+
30
+ ```ts
31
+ import { createX402bServer } from "@bosonprotocol/x402-server";
32
+ import { buildChannelRegistry } from "@bosonprotocol/x402-actions";
33
+ import { privateKeyToAccount } from "viem/accounts";
34
+
35
+ const sellerAssistant = privateKeyToAccount(process.env.SELLER_PK as `0x${string}`);
36
+
37
+ const server = createX402bServer({
38
+ network: "eip155:8453",
39
+ chainId: 8453,
40
+ escrow: "0xDIAMOND...",
41
+ signer: sellerAssistant,
42
+ facilitator: { url: "https://facilitator.example" },
43
+ channelRegistry: buildChannelRegistry({
44
+ channels: ["server", "facilitator", "onchain", "mcp"],
45
+ escrow: "0xDIAMOND...",
46
+ mcp: "boson://seller/12345",
47
+ }),
48
+ });
49
+
50
+ const requirements = await server.buildPaymentRequirements({
51
+ offer: { unsigned: { /* UnsignedFullOffer — see `@bosonprotocol/x402-core/eip712` */ } },
52
+ asset: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", // USDC on Base
53
+ amount: "1000000", // 1 USDC (6 decimals)
54
+ tokenAuthStrategies: ["erc3009"],
55
+ recipientId: "did:boson:seller:12345",
56
+ maxTimeoutSeconds: 300,
57
+ });
58
+ ```
59
+
60
+ `requirements` is an `EscrowPaymentRequirements` ready to embed in a
61
+ 402 response's `accepts[]` array.
62
+
63
+ ## License
64
+
65
+ [Apache-2.0](./LICENSE)
@@ -0,0 +1,64 @@
1
+ import { UnsignedFullOffer } from '@bosonprotocol/x402-core/eip712';
2
+ import { Address, BosonOfferRef, TokenAuthStrategy, FulfillmentRequirements, EvmNetwork, EscrowPaymentRequirements } from '@bosonprotocol/x402-core/schemes/escrow';
3
+ import { S as SellerSigner } from '../config-CBr9qMps.js';
4
+ import { ChannelRegistry } from '@bosonprotocol/x402-actions';
5
+ import '@bosonprotocol/x402-facilitator';
6
+ import 'viem';
7
+ import 'zod';
8
+ import '@bosonprotocol/core-sdk';
9
+ import '../onchain/index.js';
10
+
11
+ interface SignFullOfferArgs {
12
+ fullOffer: UnsignedFullOffer;
13
+ signer: SellerSigner;
14
+ /** Boson Diamond address — the EIP-712 `verifyingContract`. */
15
+ escrow: Address;
16
+ chainId: number;
17
+ }
18
+ /**
19
+ * Sign a FullOffer via `@bosonprotocol/core-sdk`'s `signFullOffer`
20
+ * and return a `BosonOfferRef` ready to embed in
21
+ * `EscrowPaymentRequirements.offer`. The seller signer is plugged
22
+ * into core-sdk via a forwarding `Web3LibAdapter` so any viem
23
+ * `LocalAccount` / HSM / KMS signer drops in without exposing
24
+ * core-sdk's adapter shape in this package's public API.
25
+ *
26
+ * ERC-1271 contract-wallet sellers: pass the wallet's address as
27
+ * `signer.address` and route `signer.signTypedData` to whatever
28
+ * surface the wallet exposes — the protocol's on-chain `verifyOffer`
29
+ * runs via `EIP712Lib.verify` which already handles both ECDSA and
30
+ * ERC-1271 recovery.
31
+ */
32
+ declare function signFullOffer({ fullOffer, signer, escrow, chainId, }: SignFullOfferArgs): Promise<BosonOfferRef>;
33
+
34
+ interface BuildPaymentRequirementsArgs {
35
+ /** Signed offer reference — usually from `signFullOffer`. */
36
+ offer: BosonOfferRef;
37
+ /** ERC-20 token address the buyer pays in. */
38
+ asset: Address;
39
+ /** Atomic amount as a decimal string (e.g. wei). */
40
+ amount: string;
41
+ /** Token-auth strategies the server is willing to accept. */
42
+ tokenAuthStrategies: readonly TokenAuthStrategy[];
43
+ /** Routing-only seller identifier — numeric sellerId, `did:boson:seller:N`, or wallet address. */
44
+ recipientId: string;
45
+ /** Upper bound for `validBefore` / `deadline` in token-auth payloads. */
46
+ maxTimeoutSeconds: number;
47
+ /** Optional fulfillment channel options. Absent or `{required: false}` means the server treats payment as fully atomic. */
48
+ fulfillment?: FulfillmentRequirements;
49
+ /** CAIP-2 network identifier (e.g. `eip155:8453`). */
50
+ network: EvmNetwork;
51
+ /** Boson Diamond address — same as `config.escrow`. */
52
+ escrow: Address;
53
+ /** Per-seller channel registry consumed by `deriveInitialNextActions`. */
54
+ channelRegistry: ChannelRegistry;
55
+ }
56
+ /**
57
+ * Build an `EscrowPaymentRequirements` body (the entry that lives
58
+ * inside the 402 response's `accepts[]` array). The result is
59
+ * round-tripped through `escrowPaymentRequirementsSchema` to fail
60
+ * loudly if any caller-provided field violates the wire format.
61
+ */
62
+ declare function buildPaymentRequirements(args: BuildPaymentRequirementsArgs): EscrowPaymentRequirements;
63
+
64
+ export { type BuildPaymentRequirementsArgs, type SignFullOfferArgs, buildPaymentRequirements, signFullOffer };
@@ -0,0 +1,96 @@
1
+ 'use strict';
2
+
3
+ var coreSdk = require('@bosonprotocol/core-sdk');
4
+ var x402Actions = require('@bosonprotocol/x402-actions');
5
+ var escrow = require('@bosonprotocol/x402-core/schemes/escrow');
6
+
7
+ // src/challenge/sign-full-offer.ts
8
+ var STUB_CALLER_TAG = "@bosonprotocol/x402-server:sign-full-offer";
9
+ async function signFullOffer({
10
+ fullOffer,
11
+ signer,
12
+ escrow,
13
+ chainId
14
+ }) {
15
+ const web3Lib = buildForwardingAdapter(signer, chainId);
16
+ const result = await coreSdk.exchanges.handler.signFullOffer({
17
+ fullOfferArgsUnsigned: fullOffer,
18
+ contractAddress: escrow,
19
+ chainId,
20
+ web3Lib
21
+ });
22
+ return {
23
+ fullOffer,
24
+ sellerSig: result.signature,
25
+ creator: signer.address
26
+ };
27
+ }
28
+ function buildForwardingAdapter(signer, chainId) {
29
+ const unreachable = (method) => Promise.reject(
30
+ new Error(
31
+ `${STUB_CALLER_TAG}: Web3LibAdapter.${method}() called unexpectedly \u2014 sign-full-offer is a signing-only path.`
32
+ )
33
+ );
34
+ return {
35
+ uuid: `${STUB_CALLER_TAG}:forward`,
36
+ getSignerAddress: () => Promise.resolve(signer.address),
37
+ isSignerContract: () => Promise.resolve(false),
38
+ getChainId: () => Promise.resolve(chainId),
39
+ send: async (method, params) => {
40
+ if (method !== "eth_signTypedData_v4") {
41
+ throw new Error(`${STUB_CALLER_TAG}: unexpected RPC method: ${method}`);
42
+ }
43
+ const [, json] = params;
44
+ if (typeof json !== "string") {
45
+ throw new Error(`${STUB_CALLER_TAG}: eth_signTypedData_v4 payload is not a JSON string`);
46
+ }
47
+ const td = JSON.parse(json);
48
+ return signer.signTypedData({
49
+ domain: td.domain,
50
+ types: td.types,
51
+ primaryType: td.primaryType,
52
+ message: td.message
53
+ });
54
+ },
55
+ getBalance: () => unreachable("getBalance"),
56
+ estimateGas: () => unreachable("estimateGas"),
57
+ sendTransaction: () => unreachable("sendTransaction"),
58
+ call: () => unreachable("call"),
59
+ getTransactionReceipt: () => unreachable("getTransactionReceipt"),
60
+ getCurrentTimeMs: () => unreachable("getCurrentTimeMs")
61
+ };
62
+ }
63
+ function buildPaymentRequirements(args) {
64
+ const {
65
+ offer,
66
+ asset,
67
+ amount,
68
+ tokenAuthStrategies,
69
+ recipientId,
70
+ maxTimeoutSeconds,
71
+ fulfillment,
72
+ network,
73
+ escrow: escrow$1,
74
+ channelRegistry
75
+ } = args;
76
+ const actions = x402Actions.deriveInitialNextActions(channelRegistry);
77
+ const requirements = {
78
+ scheme: "escrow",
79
+ network,
80
+ asset,
81
+ amount,
82
+ escrowAddress: escrow$1,
83
+ recipientId,
84
+ maxTimeoutSeconds,
85
+ offer,
86
+ tokenAuthStrategies: [...tokenAuthStrategies],
87
+ ...fulfillment !== void 0 ? { fulfillment } : {},
88
+ actions
89
+ };
90
+ return escrow.escrowPaymentRequirementsSchema.parse(requirements);
91
+ }
92
+
93
+ exports.buildPaymentRequirements = buildPaymentRequirements;
94
+ exports.signFullOffer = signFullOffer;
95
+ //# sourceMappingURL=index.js.map
96
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/challenge/sign-full-offer.ts","../../../src/challenge/build-requirements.ts"],"names":["exchanges","escrow","deriveInitialNextActions","escrowPaymentRequirementsSchema"],"mappings":"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","file":"index.js","sourcesContent":["// FullOffer signer hook — produces the seller's `BosonOfferRef` from\n// an unsigned FullOffer. Delegates directly to\n// `@bosonprotocol/core-sdk`'s `exchanges.handler.signFullOffer`,\n// supplying a forwarding `Web3LibAdapter` that routes the inner\n// `eth_signTypedData_v4` RPC call to the configured `SellerSigner`.\n//\n// Routing through core-sdk keeps the typed-data shape, EIP-712 domain\n// (salt-based `Boson Protocol` / `V2`), and offer-struct\n// canonicalisation in lock-step with the deployed protocol — we don't\n// re-derive the FullOffer EIP-712 type-list on our side.\n\nimport { exchanges } from \"@bosonprotocol/core-sdk\";\nimport type { Web3LibAdapter } from \"@bosonprotocol/common\";\nimport type { UnsignedFullOffer } from \"@bosonprotocol/x402-core/eip712\";\nimport type {\n Address,\n BosonOfferRef,\n FullOffer,\n Hex,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\n\nimport type { SellerSigner } from \"../config.js\";\n\nconst STUB_CALLER_TAG = \"@bosonprotocol/x402-server:sign-full-offer\";\n\nexport interface SignFullOfferArgs {\n fullOffer: UnsignedFullOffer;\n signer: SellerSigner;\n /** Boson Diamond address — the EIP-712 `verifyingContract`. */\n escrow: Address;\n chainId: number;\n}\n\n/**\n * Sign a FullOffer via `@bosonprotocol/core-sdk`'s `signFullOffer`\n * and return a `BosonOfferRef` ready to embed in\n * `EscrowPaymentRequirements.offer`. The seller signer is plugged\n * into core-sdk via a forwarding `Web3LibAdapter` so any viem\n * `LocalAccount` / HSM / KMS signer drops in without exposing\n * core-sdk's adapter shape in this package's public API.\n *\n * ERC-1271 contract-wallet sellers: pass the wallet's address as\n * `signer.address` and route `signer.signTypedData` to whatever\n * surface the wallet exposes — the protocol's on-chain `verifyOffer`\n * runs via `EIP712Lib.verify` which already handles both ECDSA and\n * ERC-1271 recovery.\n */\nexport async function signFullOffer({\n fullOffer,\n signer,\n escrow,\n chainId,\n}: SignFullOfferArgs): Promise<BosonOfferRef> {\n const web3Lib = buildForwardingAdapter(signer, chainId);\n const result = await exchanges.handler.signFullOffer({\n fullOfferArgsUnsigned: fullOffer as unknown as Parameters<\n typeof exchanges.handler.signFullOffer\n >[0][\"fullOfferArgsUnsigned\"],\n contractAddress: escrow,\n chainId,\n web3Lib,\n });\n return {\n fullOffer: fullOffer as unknown as FullOffer,\n sellerSig: result.signature as Hex,\n creator: signer.address,\n };\n}\n\n/**\n * Build a `Web3LibAdapter` whose `send(\"eth_signTypedData_v4\", [from, json])`\n * routes to `signer.signTypedData(...)`. core-sdk's `signFullOffer`\n * path only touches `getSignerAddress`, `getChainId`, and that one\n * `send` invocation — every other adapter method rejects so a future\n * leak into a non-signing-only path is loud rather than silent.\n */\nfunction buildForwardingAdapter(signer: SellerSigner, chainId: number): Web3LibAdapter {\n const unreachable = (method: string): Promise<never> =>\n Promise.reject(\n new Error(\n `${STUB_CALLER_TAG}: Web3LibAdapter.${method}() called unexpectedly — sign-full-offer is a signing-only path.`,\n ),\n );\n\n return {\n uuid: `${STUB_CALLER_TAG}:forward`,\n getSignerAddress: () => Promise.resolve(signer.address),\n isSignerContract: () => Promise.resolve(false),\n getChainId: () => Promise.resolve(chainId),\n send: async (method, params) => {\n if (method !== \"eth_signTypedData_v4\") {\n throw new Error(`${STUB_CALLER_TAG}: unexpected RPC method: ${method}`);\n }\n const [, json] = params as [unknown, string];\n if (typeof json !== \"string\") {\n throw new Error(`${STUB_CALLER_TAG}: eth_signTypedData_v4 payload is not a JSON string`);\n }\n const td = JSON.parse(json) as {\n domain: Record<string, unknown>;\n types: Record<string, readonly { name: string; type: string }[]>;\n primaryType: string;\n message: Record<string, unknown>;\n };\n return signer.signTypedData({\n domain: td.domain,\n types: td.types,\n primaryType: td.primaryType,\n message: td.message,\n });\n },\n getBalance: () => unreachable(\"getBalance\"),\n estimateGas: () => unreachable(\"estimateGas\"),\n sendTransaction: () => unreachable(\"sendTransaction\"),\n call: () => unreachable(\"call\"),\n getTransactionReceipt: () => unreachable(\"getTransactionReceipt\"),\n getCurrentTimeMs: () => unreachable(\"getCurrentTimeMs\"),\n };\n}\n","// 402 challenge builder — assembles an `EscrowPaymentRequirements`\n// from per-offer inputs (asset, amount, fulfillment, etc.) plus the\n// signed `BosonOfferRef` and the server's channel registry. The\n// initial `nextActions` envelope is filled via\n// `deriveInitialNextActions(registry)` so the legal transitions out\n// of `PRE_COMMIT` are always populated consistently.\n//\n// Source of truth: docs/boson-impl-01-escrow-scheme.md §2.\n\nimport { deriveInitialNextActions, type ChannelRegistry } from \"@bosonprotocol/x402-actions\";\nimport {\n escrowPaymentRequirementsSchema,\n type Address,\n type BosonOfferRef,\n type EscrowPaymentRequirements,\n type EvmNetwork,\n type FulfillmentRequirements,\n type TokenAuthStrategy,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\n\nexport interface BuildPaymentRequirementsArgs {\n /** Signed offer reference — usually from `signFullOffer`. */\n offer: BosonOfferRef;\n /** ERC-20 token address the buyer pays in. */\n asset: Address;\n /** Atomic amount as a decimal string (e.g. wei). */\n amount: string;\n /** Token-auth strategies the server is willing to accept. */\n tokenAuthStrategies: readonly TokenAuthStrategy[];\n /** Routing-only seller identifier — numeric sellerId, `did:boson:seller:N`, or wallet address. */\n recipientId: string;\n /** Upper bound for `validBefore` / `deadline` in token-auth payloads. */\n maxTimeoutSeconds: number;\n /** Optional fulfillment channel options. Absent or `{required: false}` means the server treats payment as fully atomic. */\n fulfillment?: FulfillmentRequirements;\n /** CAIP-2 network identifier (e.g. `eip155:8453`). */\n network: EvmNetwork;\n /** Boson Diamond address — same as `config.escrow`. */\n escrow: Address;\n /** Per-seller channel registry consumed by `deriveInitialNextActions`. */\n channelRegistry: ChannelRegistry;\n}\n\n/**\n * Build an `EscrowPaymentRequirements` body (the entry that lives\n * inside the 402 response's `accepts[]` array). The result is\n * round-tripped through `escrowPaymentRequirementsSchema` to fail\n * loudly if any caller-provided field violates the wire format.\n */\nexport function buildPaymentRequirements(\n args: BuildPaymentRequirementsArgs,\n): EscrowPaymentRequirements {\n const {\n offer,\n asset,\n amount,\n tokenAuthStrategies,\n recipientId,\n maxTimeoutSeconds,\n fulfillment,\n network,\n escrow,\n channelRegistry,\n } = args;\n\n const actions = deriveInitialNextActions(channelRegistry);\n\n const requirements: EscrowPaymentRequirements = {\n scheme: \"escrow\",\n network,\n asset,\n amount,\n escrowAddress: escrow,\n recipientId,\n maxTimeoutSeconds,\n offer,\n tokenAuthStrategies: [...tokenAuthStrategies],\n ...(fulfillment !== undefined ? { fulfillment } : {}),\n actions,\n };\n\n return escrowPaymentRequirementsSchema.parse(requirements) as EscrowPaymentRequirements;\n}\n"]}
@@ -0,0 +1,36 @@
1
+ import { FacilitatorVerifyInput, FacilitatorVerifyResult, FacilitatorSettleInput, FacilitatorSettleResult, FacilitatorPerformActionInput, FacilitatorPerformActionResult } from '@bosonprotocol/x402-facilitator';
2
+
3
+ type FetchLike = (input: string, init?: {
4
+ method?: string;
5
+ headers?: Record<string, string>;
6
+ body?: string;
7
+ }) => Promise<{
8
+ ok: boolean;
9
+ status: number;
10
+ text: () => Promise<string>;
11
+ json?: () => Promise<unknown>;
12
+ }>;
13
+ interface CreateFacilitatorClientOptions {
14
+ /** Base URL of the facilitator service (no trailing slash needed). */
15
+ url: string;
16
+ /** Optional `fetch` override — defaults to the global `fetch`. Useful for tests + non-`fetch` runtimes. */
17
+ fetch?: FetchLike;
18
+ /** Optional headers attached to every request — e.g. an `Authorization` for hosted facilitators. */
19
+ headers?: Record<string, string>;
20
+ }
21
+ interface FacilitatorClient {
22
+ verify(input: FacilitatorVerifyInput): Promise<FacilitatorVerifyResult>;
23
+ settle(input: FacilitatorSettleInput): Promise<FacilitatorSettleResult>;
24
+ performAction(input: FacilitatorPerformActionInput): Promise<FacilitatorPerformActionResult>;
25
+ }
26
+ /**
27
+ * Construct a typed HTTP client for the facilitator. The returned
28
+ * methods stringify the input as JSON and POST to the matching path
29
+ * on the configured URL. Bodies matching the well-formed result shape
30
+ * (whether HTTP 2xx success or HTTP 400 domain rejection) are returned
31
+ * verbatim; transport failures (network, non-JSON body,
32
+ * schema-mismatched body) raise `FacilitatorHttpError`.
33
+ */
34
+ declare function createFacilitatorClient(opts: CreateFacilitatorClientOptions): FacilitatorClient;
35
+
36
+ export { type CreateFacilitatorClientOptions as C, type FacilitatorClient as F, type FetchLike as a, createFacilitatorClient as c };