tersign 0.5.0 → 0.6.1
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/LICENSE +202 -21
- package/NOTICE +4 -0
- package/README.md +22 -9
- package/dist/adapter/x402.d.ts +59 -3
- package/dist/adapter/x402.js +168 -34
- package/dist/assure.d.ts +69 -7
- package/dist/assure.js +74 -16
- package/dist/compliance/record.d.ts +11 -5
- package/dist/compliance/record.js +10 -4
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/ledgerClient.d.ts +3 -0
- package/dist/ledgerClient.js +2 -0
- package/dist/mcp/server.d.ts +1 -1
- package/dist/mcp/server.js +8 -8
- package/dist/mcp/tools.d.ts +3 -2
- package/dist/mcp/tools.js +2 -2
- package/dist/receipt/binding.d.ts +4 -1
- package/dist/receipt/binding.js +4 -1
- package/dist/receipt/network.d.ts +31 -0
- package/dist/receipt/network.js +71 -0
- package/dist/types.d.ts +25 -12
- package/dist/types.js +3 -3
- package/package.json +4 -3
package/LICENSE
CHANGED
|
@@ -1,21 +1,202 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
<p align="center">
|
|
6
6
|
<a href="https://www.npmjs.com/package/tersign"><img src="https://img.shields.io/npm/v/tersign?style=flat-square" alt="npm version"></a>
|
|
7
|
-
<a href="https://github.com/tersignhq/tersign-js/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/tersign?style=flat-square" alt="
|
|
7
|
+
<a href="https://github.com/tersignhq/tersign-js/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/tersign?style=flat-square" alt="Apache-2.0 license"></a>
|
|
8
8
|
<img src="https://img.shields.io/badge/npm-provenance%20attested-2ea44f?style=flat-square" alt="npm provenance attested">
|
|
9
9
|
<img src="https://img.shields.io/badge/MCP%20registry-io.github.tersignhq%2Fevidence-1c1c1c?style=flat-square" alt="MCP registry">
|
|
10
10
|
</p>
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
|
|
18
18
|
## Verify a Real Entry — Right Now
|
|
19
19
|
|
|
20
|
-
No account. No API key. This is the genesis receipt, `seq 1` on the production chain:
|
|
20
|
+
No account. No API key. This is the genesis receipt, `seq 1` on the production chain. It is a self-signed demo: Tersign signed it as seller and named its own key as payer, so its EIP-712 payload signature (domain `{name: "x402 receipt", version: "1", chainId: 1}`, per the x402 offer-and-receipt extension) recovers to the payload's own payer, `0x36f82906859E5B0bd076069f8cdfAea355358b14`. [`/v1/genesis`](https://tersign.ai/v1/genesis) serves the record with the recipe for each of its signatures.
|
|
21
21
|
|
|
22
22
|
```sh
|
|
23
23
|
npx tersign verify 0xe5874f1ffe87f0a6dd9eb157730f67b86ee4538b125fe30fcc4e165213dd3fc4
|
|
@@ -69,7 +69,7 @@ graph LR
|
|
|
69
69
|
|
|
70
70
|
<sub>Diagram renders on GitHub. On npm, the paragraph above IS the diagram.</sub>
|
|
71
71
|
|
|
72
|
-
|
|
72
|
+
A refund record references the record it corrects by digest (`refundOf`). Disputes attach to the digest with objective reason codes. Party statements are structurally segregated behind an `UNVERIFIED` marker — the evidence stays prompt-injection-hardened.
|
|
73
73
|
|
|
74
74
|
## Enter the Record
|
|
75
75
|
|
|
@@ -77,15 +77,28 @@ Refunds chain back to the original receipt via `refundOf`. Disputes attach to th
|
|
|
77
77
|
npm i tersign
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
-
`withAssure()` wraps your x402 fetch handler
|
|
80
|
+
`withAssure()` wraps your x402 fetch handler. On a settled call it signs a receipt and a compliance-fields record with your key and merges both into the `PAYMENT-RESPONSE` header, the base64 JSON settlement response x402 wallets already read; the response body is left alone. When it cannot issue them (a settlement network that is neither CAIP-2 nor a v1 name in its table, such as `"bsc"`, or a ledger error), the paid response goes out exactly as your handler returned it, with no receipt, and the error goes to `onError` (default: `console.error`); with idempotency on, a retry with the same payment id replays that response. On a 402 it adds `compliance-fields` to the `PAYMENT-REQUIRED` header. When the `Assure` is built with a ledger, the ledger counter-signs the receipt into your chain; the compliance-fields record is not counter-signed, and is bound to its receipt only by your own signature, which covers the receipt's digest. Without a ledger, both carry your signature alone.
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { privateKeyToAccount } from 'viem/accounts';
|
|
84
|
+
import { Assure, withAssure } from 'tersign';
|
|
85
|
+
|
|
86
|
+
const signer = privateKeyToAccount(process.env.TERSIGN_SELLER_KEY as `0x${string}`);
|
|
87
|
+
const assure = new Assure({ signer, issuer: { name: 'Example API Ltd', jurisdiction: 'HK' } });
|
|
88
|
+
export default { fetch: withAssure(app.fetch, { assure }) }; // app: your x402-protected Hono app
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
A wallet finds the receipt at `extensions["offer-receipt"].info.receipt` and the record at `extensions["compliance-fields"].info.record` of the decoded `PAYMENT-RESPONSE` (`X-PAYMENT-RESPONSE` on x402 v1). Sellers whose readers still parse the JSON body can pass `legacyBodyPlacement: true` for one more minor release.
|
|
92
|
+
|
|
93
|
+
The full register:
|
|
81
94
|
|
|
82
95
|
| Capability | In the record |
|
|
83
96
|
|---|---|
|
|
84
97
|
| Receipts | Seller-signed EIP-712 (x402 offer-receipt extension), keccak256 canonical digests |
|
|
85
|
-
| `withAssure()` | x402 fetch-handler adapter —
|
|
86
|
-
| Compliance
|
|
98
|
+
| `withAssure()` | x402 fetch-handler adapter — receipt + compliance-fields record in `PAYMENT-RESPONSE` on each paid call it can issue for, the paid response passed through unchanged when it cannot; `compliance-fields` advertised on 402 |
|
|
99
|
+
| Compliance-fields records | MINIMAL tier (Art 226b simplified-invoice content) via `buildMinimalRecord` · ledger exports `format=art226b` · `format=s51c` — mappings, not certifications |
|
|
87
100
|
| Action records | `ActionRecordV1` — GDPR-minimized; captures the content of an Art-50 disclosure so the disclosure itself is independently attested, not self-reported |
|
|
88
|
-
| Refunds |
|
|
101
|
+
| Refunds | A refund record carries `refundOf`, the digest of the record it corrects · `record_refund` logs a pending refund entry on the ledger (not counter-signed) |
|
|
89
102
|
| Disputes v0 | Objective reason codes, evidence submission, adjudication |
|
|
90
103
|
| Venue envelopes | Internet Court (5,000-char slot) · Kleros ERC-1497 · UMA · generic |
|
|
91
104
|
| Evidence packs | `format=art50` · `format=safr` (beta) |
|
|
@@ -168,7 +181,7 @@ Full URLs, readable without auth. If you are an agent, start here.
|
|
|
168
181
|
| Bundle verifier, out-of-band | https://tersign.ai/verify/v1/ — `verify_bundle.py` · `keccak.py` · `secp256k1.py` · `SHA256SUMS`. A bundle ships its own checker; for evidence from an interested party fetch this copy and diff the two. |
|
|
169
182
|
| llms.txt | https://raw.githubusercontent.com/tersignhq/tersign-js/main/llms.txt |
|
|
170
183
|
| Conformance vectors (RFC 8785 + keccak256, two-sided) | https://github.com/tersignhq/evidence-record-conformance |
|
|
171
|
-
| Sample
|
|
184
|
+
| Sample compliance-fields record + digests | https://github.com/tersignhq/tersign-js/blob/main/test/fixtures/compliance-record.json |
|
|
172
185
|
| Genesis verify | `npx tersign verify 0xe5874f1ffe87f0a6dd9eb157730f67b86ee4538b125fe30fcc4e165213dd3fc4` |
|
|
173
186
|
|
|
174
187
|
---
|
|
@@ -200,7 +213,7 @@ If a maintainer ever asks you to reopen work elsewhere because of this, that is
|
|
|
200
213
|
<img src="https://raw.githubusercontent.com/tersignhq/.github/main/assets/seal.svg" alt="Tersign seal" width="72">
|
|
201
214
|
</p>
|
|
202
215
|
|
|
203
|
-
<p align="center"><sub>MIT · built and published from <a href="https://github.com/tersignhq/tersign-js">tersignhq/tersign-js</a> via trusted-publishing CI, provenance attested · Python verifier: <code>pip install tersign</code></sub></p>
|
|
216
|
+
<p align="center"><sub>Apache-2.0 from 0.6.1; earlier releases were MIT · built and published from <a href="https://github.com/tersignhq/tersign-js">tersignhq/tersign-js</a> via trusted-publishing CI, provenance attested · Python verifier: <code>pip install tersign</code></sub></p>
|
|
204
217
|
|
|
205
218
|
<p align="center"><sub><b>Venues rotate. The transcript endures.</b></sub></p>
|
|
206
219
|
|
package/dist/adapter/x402.d.ts
CHANGED
|
@@ -6,8 +6,42 @@ export interface SettlementInfo {
|
|
|
6
6
|
network?: string | undefined;
|
|
7
7
|
payer?: string | undefined;
|
|
8
8
|
}
|
|
9
|
+
/** Encode a JSON value the way an x402 HTTP header carries it (base64 over UTF-8 JSON). */
|
|
10
|
+
export declare function encodeX402Header(value: unknown): string;
|
|
11
|
+
/** Decode an x402 HTTP header value; `undefined` when it is not base64 over UTF-8 JSON. */
|
|
12
|
+
export declare function decodeX402Header(value: string): unknown;
|
|
9
13
|
export declare function extractPaymentPayload(headers: Headers): unknown;
|
|
10
14
|
export declare function extractSettlement(headers: Headers): SettlementInfo | undefined;
|
|
15
|
+
/** What a 402 advertises under `extensions["compliance-fields"].info`. Each member is a claim
|
|
16
|
+
* about the records this server emits, so set one only when it is true of every record:
|
|
17
|
+
* `tiers: ['minimal']` needs every record to carry each MINIMAL member, including `tax.amount`
|
|
18
|
+
* whenever `tax.scheme` is not `none`. The default advertises the extension with no tier or
|
|
19
|
+
* jurisdiction claim. */
|
|
20
|
+
export interface ComplianceAdvertisement {
|
|
21
|
+
tiers?: ReadonlyArray<'minimal' | 'full'>;
|
|
22
|
+
jurisdictions?: ReadonlyArray<string>;
|
|
23
|
+
}
|
|
24
|
+
/** JSON Schema for the advertised `info` (the core v2 spec makes `schema` a required member of
|
|
25
|
+
* every PaymentRequired extension entry). */
|
|
26
|
+
export declare const COMPLIANCE_FIELDS_ADVERTISEMENT_SCHEMA: {
|
|
27
|
+
readonly $schema: "https://json-schema.org/draft/2020-12/schema";
|
|
28
|
+
readonly type: "object";
|
|
29
|
+
readonly properties: {
|
|
30
|
+
readonly tiers: {
|
|
31
|
+
readonly type: "array";
|
|
32
|
+
readonly items: {
|
|
33
|
+
readonly type: "string";
|
|
34
|
+
readonly enum: readonly ["minimal", "full"];
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
readonly jurisdictions: {
|
|
38
|
+
readonly type: "array";
|
|
39
|
+
readonly items: {
|
|
40
|
+
readonly type: "string";
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
};
|
|
11
45
|
export interface WithAssureConfig {
|
|
12
46
|
assure: Assure;
|
|
13
47
|
/** describe the supply for the receipt; defaults to the request path */
|
|
@@ -20,10 +54,32 @@ export interface WithAssureConfig {
|
|
|
20
54
|
required: boolean;
|
|
21
55
|
scope: string;
|
|
22
56
|
};
|
|
57
|
+
/** Advertise `compliance-fields` in a 402's `PAYMENT-REQUIRED` header (x402 v2). Default: on,
|
|
58
|
+
* with an empty claim set. `false` leaves 402 responses untouched. An entry the handler
|
|
59
|
+
* already put there is kept as it is. */
|
|
60
|
+
advertise?: false | ComplianceAdvertisement;
|
|
61
|
+
/** @deprecated Also decorate a JSON response BODY with the receipt and record (the ≤0.5
|
|
62
|
+
* placement). The `PAYMENT-RESPONSE` header carries them either way. Scheduled for removal in
|
|
63
|
+
* the next minor release after the one that introduced header placement. A body that does not
|
|
64
|
+
* parse as a JSON object is left as it is. */
|
|
65
|
+
legacyBodyPlacement?: boolean;
|
|
66
|
+
/** Called when a settled call's receipt cannot be issued: a settlement network that is neither
|
|
67
|
+
* CAIP-2 nor in the v1 table (`toCaip2Network`), a ledger error, a throwing `toSettlementContext`
|
|
68
|
+
* or `describeSupply`. The paid response then goes out exactly as the handler returned it, with
|
|
69
|
+
* no receipt or record in it. Default: one `console.error` line per failure. An error thrown by
|
|
70
|
+
* this callback, or a rejection of a promise it returns, is ignored. */
|
|
71
|
+
onError?: (err: unknown) => void;
|
|
23
72
|
}
|
|
24
73
|
type FetchHandler = (req: Request) => Response | Promise<Response>;
|
|
25
|
-
/** Wrap an x402-protected handler: enforce idempotency on the way in
|
|
26
|
-
*
|
|
27
|
-
*
|
|
74
|
+
/** Wrap an x402-protected handler: enforce idempotency on the way in; on the way out, advertise
|
|
75
|
+
* `compliance-fields` on a 402, and — when the settlement header reports success — issue the
|
|
76
|
+
* signed receipt + compliance-fields record and merge both into that same settlement header
|
|
77
|
+
* (`PAYMENT-RESPONSE`, or `X-PAYMENT-RESPONSE` for v1), where x402 wallets read them. The
|
|
78
|
+
* response body is left untouched unless `legacyBodyPlacement` is set.
|
|
79
|
+
*
|
|
80
|
+
* Once the settlement header reports success the buyer has paid, so a failure to issue does not
|
|
81
|
+
* throw: the response goes out exactly as the handler returned it, the error goes to `onError`,
|
|
82
|
+
* and with idempotency on the payment id is completed with that delivered response, so a retry
|
|
83
|
+
* replays it instead of finding the id stuck in flight. */
|
|
28
84
|
export declare function withAssure(handler: FetchHandler, cfg: WithAssureConfig): FetchHandler;
|
|
29
85
|
export {};
|
package/dist/adapter/x402.js
CHANGED
|
@@ -1,22 +1,57 @@
|
|
|
1
|
-
import { attachToExtensions } from '../assure.js';
|
|
1
|
+
import { attachToExtensions, attachToSettlementResponse } from '../assure.js';
|
|
2
2
|
import { checkIdempotency, extractPaymentId, fingerprint, REPLAY_HEADER, } from '../idempotency/middleware.js';
|
|
3
3
|
/** Adapter for x402-protected fetch-style handlers ((Request) => Response) — this is the
|
|
4
4
|
* shape of a Hono app (`app.fetch`), a Workers export, and Next.js route handlers, so one
|
|
5
5
|
* wrapper covers the common seller stacks. An adapter pinned to the official x402 SDK's
|
|
6
6
|
* middleware internals is deliberately deferred until we integrate against a pinned
|
|
7
7
|
* version (its surface is still churning); this wrapper only touches the WIRE contract:
|
|
8
|
-
* the payment payload request header and the settlement
|
|
9
|
-
|
|
8
|
+
* the payment payload request header, the payment-required header and the settlement
|
|
9
|
+
* response header. */
|
|
10
|
+
/** x402 HTTP transport headers, v2 names first with v1 fallbacks. Verified 2026-09-29 against
|
|
11
|
+
* x402-foundation/x402 specs/transports-v2/http.md (main 5eee1e3c35): `PAYMENT-REQUIRED`
|
|
12
|
+
* (server → client, PaymentRequired), `PAYMENT-SIGNATURE` (client → server, PaymentPayload),
|
|
13
|
+
* `PAYMENT-RESPONSE` (server → client, SettlementResponse), each base64 over UTF-8 JSON; "All
|
|
14
|
+
* x402 protocol information is communicated through headers". Re-verify at integration
|
|
15
|
+
* (CLAUDE.md rule 1). */
|
|
10
16
|
const PAYMENT_PAYLOAD_HEADERS = ['payment-signature', 'x-payment'];
|
|
11
17
|
const SETTLEMENT_HEADERS = ['payment-response', 'x-payment-response'];
|
|
18
|
+
const PAYMENT_REQUIRED_HEADER = 'payment-required';
|
|
19
|
+
/** base64 → UTF-8 text, as the upstream reference decodes (`safeBase64Decode`), so a record
|
|
20
|
+
* carrying a non-ASCII issuer name or supply description survives the header round trip. Unlike
|
|
21
|
+
* the reference, invalid UTF-8 is refused rather than replaced with U+FFFD: a header this
|
|
22
|
+
* wrapper rewrites must decode exactly, or it is left alone. */
|
|
23
|
+
function b64decodeUtf8(value) {
|
|
24
|
+
const binary = atob(value);
|
|
25
|
+
const bytes = new Uint8Array(binary.length);
|
|
26
|
+
for (let i = 0; i < binary.length; i++)
|
|
27
|
+
bytes[i] = binary.charCodeAt(i);
|
|
28
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
29
|
+
}
|
|
30
|
+
/** UTF-8 text → base64, as the upstream reference encodes (`safeBase64Encode`). Plain `btoa`
|
|
31
|
+
* throws on any character above U+00FF. */
|
|
32
|
+
function b64encodeUtf8(text) {
|
|
33
|
+
const bytes = new TextEncoder().encode(text);
|
|
34
|
+
let binary = '';
|
|
35
|
+
for (const b of bytes)
|
|
36
|
+
binary += String.fromCharCode(b);
|
|
37
|
+
return btoa(binary);
|
|
38
|
+
}
|
|
12
39
|
function b64json(value) {
|
|
13
40
|
try {
|
|
14
|
-
return JSON.parse(
|
|
41
|
+
return JSON.parse(b64decodeUtf8(value));
|
|
15
42
|
}
|
|
16
43
|
catch {
|
|
17
44
|
return undefined;
|
|
18
45
|
}
|
|
19
46
|
}
|
|
47
|
+
/** Encode a JSON value the way an x402 HTTP header carries it (base64 over UTF-8 JSON). */
|
|
48
|
+
export function encodeX402Header(value) {
|
|
49
|
+
return b64encodeUtf8(JSON.stringify(value));
|
|
50
|
+
}
|
|
51
|
+
/** Decode an x402 HTTP header value; `undefined` when it is not base64 over UTF-8 JSON. */
|
|
52
|
+
export function decodeX402Header(value) {
|
|
53
|
+
return b64json(value);
|
|
54
|
+
}
|
|
20
55
|
export function extractPaymentPayload(headers) {
|
|
21
56
|
for (const name of PAYMENT_PAYLOAD_HEADERS) {
|
|
22
57
|
const raw = headers.get(name);
|
|
@@ -25,29 +60,105 @@ export function extractPaymentPayload(headers) {
|
|
|
25
60
|
}
|
|
26
61
|
return undefined;
|
|
27
62
|
}
|
|
28
|
-
|
|
63
|
+
function findSettlement(headers) {
|
|
29
64
|
for (const name of SETTLEMENT_HEADERS) {
|
|
30
65
|
const raw = headers.get(name);
|
|
31
66
|
if (!raw)
|
|
32
67
|
continue;
|
|
33
68
|
const parsed = b64json(raw);
|
|
34
|
-
if (!parsed
|
|
69
|
+
if (!isPlainRecord(parsed))
|
|
35
70
|
continue;
|
|
36
|
-
return {
|
|
37
|
-
success: parsed.success === true,
|
|
38
|
-
transaction: str(parsed.transaction) ?? str(parsed.txHash),
|
|
39
|
-
network: str(parsed.network) ?? str(parsed.networkId),
|
|
40
|
-
payer: str(parsed.payer) ?? str(parsed.from),
|
|
41
|
-
};
|
|
71
|
+
return { name, response: parsed };
|
|
42
72
|
}
|
|
43
73
|
return undefined;
|
|
44
74
|
}
|
|
75
|
+
export function extractSettlement(headers) {
|
|
76
|
+
const found = findSettlement(headers);
|
|
77
|
+
return found ? settlementInfo(found.response) : undefined;
|
|
78
|
+
}
|
|
79
|
+
function settlementInfo(parsed) {
|
|
80
|
+
return {
|
|
81
|
+
success: parsed.success === true,
|
|
82
|
+
transaction: str(parsed.transaction) ?? str(parsed.txHash),
|
|
83
|
+
network: str(parsed.network) ?? str(parsed.networkId),
|
|
84
|
+
payer: str(parsed.payer) ?? str(parsed.from),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
45
87
|
function str(v) {
|
|
46
88
|
return typeof v === 'string' && v.length > 0 ? v : undefined;
|
|
47
89
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
90
|
+
function isPlainRecord(v) {
|
|
91
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
92
|
+
}
|
|
93
|
+
/** JSON Schema for the advertised `info` (the core v2 spec makes `schema` a required member of
|
|
94
|
+
* every PaymentRequired extension entry). */
|
|
95
|
+
export const COMPLIANCE_FIELDS_ADVERTISEMENT_SCHEMA = {
|
|
96
|
+
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
|
97
|
+
type: 'object',
|
|
98
|
+
properties: {
|
|
99
|
+
tiers: { type: 'array', items: { type: 'string', enum: ['minimal', 'full'] } },
|
|
100
|
+
jurisdictions: { type: 'array', items: { type: 'string' } },
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
function reportIssueError(err) {
|
|
104
|
+
let message;
|
|
105
|
+
try {
|
|
106
|
+
message = String(err instanceof Error ? err.message : err);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
message = 'unprintable error';
|
|
110
|
+
}
|
|
111
|
+
console.error(`tersign withAssure: receipt not issued, response delivered unchanged: ${message.replace(/\s+/g, ' ')}`);
|
|
112
|
+
}
|
|
113
|
+
/** The legacy body placement reads a clone, so a body that is not a JSON object stays readable
|
|
114
|
+
* and goes out as it came. */
|
|
115
|
+
async function jsonObjectBody(res) {
|
|
116
|
+
try {
|
|
117
|
+
const parsed = await res.clone().json();
|
|
118
|
+
return isPlainRecord(parsed) ? parsed : undefined;
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function withHeaders(res, headers, body = res.body) {
|
|
125
|
+
return new Response(body, { status: res.status, statusText: res.statusText, headers });
|
|
126
|
+
}
|
|
127
|
+
function advertiseCompliance(res, adv) {
|
|
128
|
+
if (res.status !== 402)
|
|
129
|
+
return res;
|
|
130
|
+
const raw = res.headers.get(PAYMENT_REQUIRED_HEADER);
|
|
131
|
+
if (!raw)
|
|
132
|
+
return res;
|
|
133
|
+
const required = b64json(raw);
|
|
134
|
+
if (!isPlainRecord(required))
|
|
135
|
+
return res;
|
|
136
|
+
const prior = isPlainRecord(required.extensions) ? required.extensions : {};
|
|
137
|
+
if (prior['compliance-fields'] !== undefined)
|
|
138
|
+
return res;
|
|
139
|
+
const info = {};
|
|
140
|
+
if (adv.tiers !== undefined)
|
|
141
|
+
info.tiers = [...adv.tiers];
|
|
142
|
+
if (adv.jurisdictions !== undefined)
|
|
143
|
+
info.jurisdictions = [...adv.jurisdictions];
|
|
144
|
+
const decorated = {
|
|
145
|
+
...required,
|
|
146
|
+
extensions: { ...prior, 'compliance-fields': { info, schema: COMPLIANCE_FIELDS_ADVERTISEMENT_SCHEMA } },
|
|
147
|
+
};
|
|
148
|
+
const headers = new Headers(res.headers);
|
|
149
|
+
headers.set(PAYMENT_REQUIRED_HEADER, encodeX402Header(decorated));
|
|
150
|
+
return withHeaders(res, headers);
|
|
151
|
+
}
|
|
152
|
+
/** Wrap an x402-protected handler: enforce idempotency on the way in; on the way out, advertise
|
|
153
|
+
* `compliance-fields` on a 402, and — when the settlement header reports success — issue the
|
|
154
|
+
* signed receipt + compliance-fields record and merge both into that same settlement header
|
|
155
|
+
* (`PAYMENT-RESPONSE`, or `X-PAYMENT-RESPONSE` for v1), where x402 wallets read them. The
|
|
156
|
+
* response body is left untouched unless `legacyBodyPlacement` is set.
|
|
157
|
+
*
|
|
158
|
+
* Once the settlement header reports success the buyer has paid, so a failure to issue does not
|
|
159
|
+
* throw: the response goes out exactly as the handler returned it, the error goes to `onError`,
|
|
160
|
+
* and with idempotency on the payment id is completed with that delivered response, so a retry
|
|
161
|
+
* replays it instead of finding the id stuck in flight. */
|
|
51
162
|
export function withAssure(handler, cfg) {
|
|
52
163
|
const now = cfg.clock ?? (() => Math.floor(Date.now() / 1000));
|
|
53
164
|
return async (req) => {
|
|
@@ -74,25 +185,48 @@ export function withAssure(handler, cfg) {
|
|
|
74
185
|
}
|
|
75
186
|
}
|
|
76
187
|
let res = await handler(req);
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
188
|
+
if (cfg.advertise !== false)
|
|
189
|
+
res = advertiseCompliance(res, cfg.advertise ?? {});
|
|
190
|
+
const found = findSettlement(res.headers);
|
|
191
|
+
const settlement = found ? settlementInfo(found.response) : undefined;
|
|
192
|
+
if (found && settlement?.success) {
|
|
193
|
+
// Paid: nothing from here may cost the buyer the response. On any failure `res` stays the
|
|
194
|
+
// handler's own, and the idempotency entry below is completed with it.
|
|
195
|
+
try {
|
|
196
|
+
const url = new URL(req.url);
|
|
197
|
+
const overrides = cfg.toSettlementContext?.(req, settlement) ?? {};
|
|
198
|
+
const ctx = {
|
|
199
|
+
network: settlement.network ?? 'eip155:8453',
|
|
200
|
+
resourceUrl: url.origin + url.pathname,
|
|
201
|
+
payer: settlement.payer ?? 'unknown',
|
|
202
|
+
settledAt: now(),
|
|
203
|
+
supplyDescription: cfg.describeSupply?.(req) ?? url.pathname,
|
|
204
|
+
...(settlement.transaction !== undefined ? { txHash: settlement.transaction } : {}),
|
|
205
|
+
...overrides,
|
|
206
|
+
};
|
|
207
|
+
const issued = await cfg.assure.issueFor(ctx);
|
|
208
|
+
const headers = new Headers(res.headers);
|
|
209
|
+
headers.set(found.name, encodeX402Header(attachToSettlementResponse(found.response, issued)));
|
|
210
|
+
const body = cfg.legacyBodyPlacement && (res.headers.get('content-type') ?? '').includes('application/json')
|
|
211
|
+
? await jsonObjectBody(res)
|
|
212
|
+
: undefined;
|
|
213
|
+
if (body) {
|
|
214
|
+
headers.delete('content-length');
|
|
215
|
+
res = withHeaders(res, headers, JSON.stringify(attachToExtensions(body, issued)));
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
res = withHeaders(res, headers);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
catch (err) {
|
|
222
|
+
try {
|
|
223
|
+
// An async reporter's rejection is caught too: left unhandled it would end the process.
|
|
224
|
+
void Promise.resolve((cfg.onError ?? reportIssueError)(err)).catch(() => { });
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
// a throwing reporter must not cost the paid response either
|
|
228
|
+
}
|
|
229
|
+
}
|
|
96
230
|
}
|
|
97
231
|
if (onComplete) {
|
|
98
232
|
const body = await res.clone().text();
|