@provethebuy/verify 0.0.0-stage → 0.1.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 (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +43 -2
  3. package/dist/bodyObjects.d.ts +28 -0
  4. package/dist/bodyObjects.js +47 -0
  5. package/dist/bodyObjects.js.map +1 -0
  6. package/dist/cloud.d.ts +42 -0
  7. package/dist/cloud.js +102 -0
  8. package/dist/cloud.js.map +1 -0
  9. package/dist/confirmation.d.ts +17 -0
  10. package/dist/confirmation.js +31 -0
  11. package/dist/confirmation.js.map +1 -0
  12. package/dist/evidence.d.ts +39 -0
  13. package/dist/evidence.js +96 -0
  14. package/dist/evidence.js.map +1 -0
  15. package/dist/express.d.ts +43 -0
  16. package/dist/express.js +72 -0
  17. package/dist/express.js.map +1 -0
  18. package/dist/httpsig.d.ts +58 -0
  19. package/dist/httpsig.js +203 -0
  20. package/dist/httpsig.js.map +1 -0
  21. package/dist/index.d.ts +29 -0
  22. package/dist/index.js +16 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/jws.d.ts +28 -0
  25. package/dist/jws.js +93 -0
  26. package/dist/jws.js.map +1 -0
  27. package/dist/keys.d.ts +61 -0
  28. package/dist/keys.js +76 -0
  29. package/dist/keys.js.map +1 -0
  30. package/dist/ledger.d.ts +102 -0
  31. package/dist/ledger.js +131 -0
  32. package/dist/ledger.js.map +1 -0
  33. package/dist/mandates/ap2.d.ts +31 -0
  34. package/dist/mandates/ap2.js +91 -0
  35. package/dist/mandates/ap2.js.map +1 -0
  36. package/dist/mandates/index.d.ts +25 -0
  37. package/dist/mandates/index.js +26 -0
  38. package/dist/mandates/index.js.map +1 -0
  39. package/dist/mandates/verifiableIntent.d.ts +20 -0
  40. package/dist/mandates/verifiableIntent.js +128 -0
  41. package/dist/mandates/verifiableIntent.js.map +1 -0
  42. package/dist/order.d.ts +9 -0
  43. package/dist/order.js +32 -0
  44. package/dist/order.js.map +1 -0
  45. package/dist/payment.d.ts +22 -0
  46. package/dist/payment.js +19 -0
  47. package/dist/payment.js.map +1 -0
  48. package/dist/policy.d.ts +39 -0
  49. package/dist/policy.js +29 -0
  50. package/dist/policy.js.map +1 -0
  51. package/dist/replay.d.ts +46 -0
  52. package/dist/replay.js +61 -0
  53. package/dist/replay.js.map +1 -0
  54. package/dist/reputation.d.ts +16 -0
  55. package/dist/reputation.js +46 -0
  56. package/dist/reputation.js.map +1 -0
  57. package/dist/testing.d.ts +53 -0
  58. package/dist/testing.js +100 -0
  59. package/dist/testing.js.map +1 -0
  60. package/dist/types.d.ts +72 -0
  61. package/dist/types.js +2 -0
  62. package/dist/types.js.map +1 -0
  63. package/dist/util.d.ts +15 -0
  64. package/dist/util.js +59 -0
  65. package/dist/util.js.map +1 -0
  66. package/dist/verify.d.ts +50 -0
  67. package/dist/verify.js +309 -0
  68. package/dist/verify.js.map +1 -0
  69. package/package.json +63 -4
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @provethebuy/verify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Verify AI-agent orders at your checkout: the agent's signature, the shopper's mandate, and the order's limits. Keeps tamper-evident evidence for disputes.
4
+
5
+ ```bash
6
+ npm install @provethebuy/verify
7
+ ```
8
+
9
+ ```js
10
+ import { ProveTheBuy, KeyDirectory, KNOWN_DIRECTORIES } from "@provethebuy/verify";
11
+
12
+ const ptb = new ProveTheBuy({
13
+ merchantId: "acct_your_shop",
14
+ keys: new KeyDirectory({ sources: [{ name: "visa", url: KNOWN_DIRECTORIES.visa }] }),
15
+ });
16
+
17
+ const result = await ptb.verify({ method: "POST", url, headers, body });
18
+ // result.decision: "allow" | "step_up" | "block" | "not_agent"
19
+ ```
20
+
21
+ With Express:
22
+
23
+ ```js
24
+ import { createMiddleware } from "@provethebuy/verify/express";
25
+ const agents = createMiddleware(ptb, ledger);
26
+ app.post("/checkout", agents.capture(), agents.verify(), handler);
27
+ ```
28
+
29
+ Send records to ProveTheBuy Cloud (optional, fails open):
30
+
31
+ ```js
32
+ import { connectCloud, UpstashReplayStore } from "@provethebuy/verify";
33
+ const cloud = connectCloud(ledger, { apiKey: process.env.PROVETHEBUY_API_KEY });
34
+ // serverless: await cloud.flush() before the response ends
35
+
36
+ // shared replay protection without a Redis connection
37
+ const replay = new UpstashReplayStore({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN });
38
+ ```
39
+
40
+ Supports RFC 9421 / Web Bot Auth, Visa Trusted Agent Protocol, Mastercard Verifiable Intent (preview), AP2 (preview) and Stripe shared payment token limits. No runtime dependencies; Node 18.17+.
41
+
42
+ Docs: [provethebuy.com/docs](https://provethebuy.com/docs/quickstart). Try it in the browser: [provethebuy.com/playground](https://provethebuy.com/playground). Source and examples: [GitHub](https://github.com/noelps-git/provethebuy).
43
+
44
+ Apache-2.0
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Visa TAP body objects: the Agentic Consumer Recognition Object and the Agentic Payment Container.
3
+ * Each carries `nonce`, `kid`, `alg` and `signature`, signed with the same key as the HTTP signature,
4
+ * and repeats the header nonce so it is bound to that request.
5
+ *
6
+ * ASSUMPTION: Visa's specification does not yet define the exact signature base for these objects
7
+ * (github.com/visa/trusted-agent-protocol/issues/23). Until it does, we sign and verify the RFC 8785
8
+ * canonical JSON of the object without its `signature` member. This is isolated here so it can change
9
+ * in one place when Visa publishes a worked example.
10
+ */
11
+ import { type KeyObject } from "node:crypto";
12
+ import { type SigAlg } from "./httpsig.js";
13
+ import type { Jwk } from "./keys.js";
14
+ import type { Check } from "./types.js";
15
+ export interface SignedBodyObject {
16
+ nonce: string;
17
+ kid: string;
18
+ alg: string;
19
+ signature: string;
20
+ [k: string]: unknown;
21
+ }
22
+ export declare function signBodyObject(obj: Omit<SignedBodyObject, "signature">, privateJwk: Jwk, alg?: SigAlg): SignedBodyObject;
23
+ export declare function verifyBodyObject(name: string, obj: SignedBodyObject | undefined, expect: {
24
+ nonce: string;
25
+ keyid: string;
26
+ alg: SigAlg;
27
+ key: KeyObject;
28
+ }): Check | null;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Visa TAP body objects: the Agentic Consumer Recognition Object and the Agentic Payment Container.
3
+ * Each carries `nonce`, `kid`, `alg` and `signature`, signed with the same key as the HTTP signature,
4
+ * and repeats the header nonce so it is bound to that request.
5
+ *
6
+ * ASSUMPTION: Visa's specification does not yet define the exact signature base for these objects
7
+ * (github.com/visa/trusted-agent-protocol/issues/23). Until it does, we sign and verify the RFC 8785
8
+ * canonical JSON of the object without its `signature` member. This is isolated here so it can change
9
+ * in one place when Visa publishes a worked example.
10
+ */
11
+ import { createPrivateKey } from "node:crypto";
12
+ import { canonicalize } from "./util.js";
13
+ import { signBytes, verifyBytes } from "./httpsig.js";
14
+ function signingInput(obj) {
15
+ const { signature: _omit, ...rest } = obj;
16
+ return Buffer.from(canonicalize(rest), "utf8");
17
+ }
18
+ export function signBodyObject(obj, privateJwk, alg = "ed25519") {
19
+ const pk = createPrivateKey({ key: privateJwk, format: "jwk" });
20
+ const sig = signBytes(alg, pk, signingInput(obj));
21
+ return { ...obj, signature: sig.toString("base64") };
22
+ }
23
+ export function verifyBodyObject(name, obj, expect) {
24
+ if (!obj)
25
+ return null;
26
+ const problems = [];
27
+ if (obj.nonce !== expect.nonce)
28
+ problems.push("its nonce does not match the signature nonce");
29
+ if (obj.kid !== expect.keyid)
30
+ problems.push("its kid does not match the signature keyid");
31
+ let ok = false;
32
+ try {
33
+ ok = verifyBytes(expect.alg, expect.key, signingInput(obj), Buffer.from(obj.signature, "base64"));
34
+ }
35
+ catch {
36
+ ok = false;
37
+ }
38
+ if (!ok)
39
+ problems.push("its signature does not verify");
40
+ return problems.length
41
+ ? { name: `body_${name}`, status: "fail", detail: `The ${label(name)} is not bound to this request: ${problems.join("; ")}.` }
42
+ : { name: `body_${name}`, status: "pass", detail: `The ${label(name)} is signed by the same agent key and bound to this request's nonce.` };
43
+ }
44
+ function label(name) {
45
+ return name === "consumer_recognition" ? "consumer recognition object" : name === "payment_container" ? "payment container" : name;
46
+ }
47
+ //# sourceMappingURL=bodyObjects.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bodyObjects.js","sourceRoot":"","sources":["../src/bodyObjects.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,gBAAgB,EAAkB,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAe,MAAM,cAAc,CAAC;AAYnE,SAAS,YAAY,CAAC,GAA4B;IAChD,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,GAAG,CAAC;IAC1C,OAAO,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC;AACjD,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAwC,EAAE,UAAe,EAAE,MAAc,SAAS;IAC/G,MAAM,EAAE,GAAG,gBAAgB,CAAC,EAAE,GAAG,EAAE,UAAmB,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IACzE,MAAM,GAAG,GAAG,SAAS,CAAC,GAAG,EAAE,EAAE,EAAE,YAAY,CAAC,GAA8B,CAAC,CAAC,CAAC;IAC7E,OAAO,EAAE,GAAG,GAAG,EAAE,SAAS,EAAE,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAsB,CAAC;AAC3E,CAAC;AAED,MAAM,UAAU,gBAAgB,CAC9B,IAAY,EACZ,GAAiC,EACjC,MAAqE;IAErE,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IACtB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+ * Send evidence records to ProveTheBuy Cloud in the background.
3
+ *
4
+ * const cloud = connectCloud(ledger, { apiKey: process.env.PROVETHEBUY_API_KEY });
5
+ *
6
+ * Fails open by design: a slow or unreachable cloud never delays or breaks checkout. Records wait in a
7
+ * bounded in-memory queue and are retried; if the queue fills, the oldest are dropped and counted.
8
+ * On serverless platforms, call `await cloud.flush()` before the response ends.
9
+ */
10
+ import type { EvidenceLedger } from "./ledger.js";
11
+ export interface CloudOptions {
12
+ apiKey: string;
13
+ /** Default https://app.provethebuy.com */
14
+ endpoint?: string;
15
+ /** Records per request. Default 50. */
16
+ batchSize?: number;
17
+ /** How often queued records are sent, in ms. Default 2000. */
18
+ flushIntervalMs?: number;
19
+ /** Per-request timeout in ms. Default 3000. */
20
+ timeoutMs?: number;
21
+ /** Most records held while the cloud is unreachable. Default 5000. */
22
+ maxQueue?: number;
23
+ /** Send the raw request and key snapshot so the cloud can re-verify for disputes. Default true. */
24
+ includeArtifacts?: boolean;
25
+ fetch?: typeof fetch;
26
+ onError?: (err: Error) => void;
27
+ }
28
+ export interface CloudStats {
29
+ queued: number;
30
+ sent: number;
31
+ dropped: number;
32
+ failures: number;
33
+ lastError?: string;
34
+ }
35
+ export interface CloudConnection {
36
+ /** Send everything queued now. Never throws. */
37
+ flush(): Promise<void>;
38
+ /** Stop the timer and send what is left. */
39
+ close(): Promise<void>;
40
+ readonly stats: CloudStats;
41
+ }
42
+ export declare function connectCloud(ledger: EvidenceLedger, opts: CloudOptions): CloudConnection;
package/dist/cloud.js ADDED
@@ -0,0 +1,102 @@
1
+ export function connectCloud(ledger, opts) {
2
+ if (!opts?.apiKey)
3
+ throw new Error("connectCloud needs an apiKey (PROVETHEBUY_API_KEY).");
4
+ const endpoint = (opts.endpoint ?? "https://app.provethebuy.com").replace(/\/$/, "");
5
+ const batchSize = opts.batchSize ?? 50;
6
+ const maxQueue = opts.maxQueue ?? 5000;
7
+ const timeoutMs = opts.timeoutMs ?? 3000;
8
+ const doFetch = opts.fetch ?? fetch;
9
+ const queue = [];
10
+ const stats = { queued: 0, sent: 0, dropped: 0, failures: 0 };
11
+ let inFlight = null;
12
+ let backoffUntil = 0;
13
+ const unsubscribe = ledger.onRecord((rec) => {
14
+ const r = opts.includeArtifacts === false && rec.type === "verification" ? { ...rec, artifacts: undefined } : rec;
15
+ queue.push(r);
16
+ while (queue.length > maxQueue) {
17
+ queue.shift();
18
+ stats.dropped++;
19
+ }
20
+ stats.queued = queue.length;
21
+ if (queue.length >= batchSize)
22
+ void flush();
23
+ });
24
+ async function sendBatch(batch) {
25
+ const ctrl = new AbortController();
26
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
27
+ try {
28
+ const res = await doFetch(`${endpoint}/v1/records`, {
29
+ method: "POST",
30
+ headers: { authorization: `Bearer ${opts.apiKey}`, "content-type": "application/json" },
31
+ body: JSON.stringify({ records: batch }),
32
+ signal: ctrl.signal,
33
+ });
34
+ if (res.status === 401 || res.status === 403)
35
+ throw new Error(`ProveTheBuy Cloud rejected the API key (HTTP ${res.status}).`);
36
+ if (res.status === 400) {
37
+ // A malformed batch will never succeed: drop it rather than retry forever.
38
+ stats.dropped += batch.length;
39
+ throw new Error(`ProveTheBuy Cloud refused a batch (HTTP 400): ${(await res.text()).slice(0, 200)}`);
40
+ }
41
+ if (!res.ok)
42
+ throw Object.assign(new Error(`ProveTheBuy Cloud returned HTTP ${res.status}.`), { retry: true });
43
+ stats.sent += batch.length;
44
+ return true;
45
+ }
46
+ catch (e) {
47
+ const err = e instanceof Error ? e : new Error(String(e));
48
+ stats.failures++;
49
+ stats.lastError = err.message;
50
+ try {
51
+ opts.onError?.(err);
52
+ }
53
+ catch {
54
+ /* ignore */
55
+ }
56
+ const retry = err.retry || err.name === "AbortError" || err.name === "TypeError";
57
+ return !retry; // true = do not requeue
58
+ }
59
+ finally {
60
+ clearTimeout(t);
61
+ }
62
+ }
63
+ async function drain() {
64
+ while (queue.length && Date.now() >= backoffUntil) {
65
+ const batch = queue.splice(0, batchSize);
66
+ const done = await sendBatch(batch);
67
+ if (!done) {
68
+ queue.unshift(...batch);
69
+ while (queue.length > maxQueue) {
70
+ queue.pop();
71
+ stats.dropped++;
72
+ }
73
+ backoffUntil = Date.now() + Math.min(60_000, 1000 * 2 ** Math.min(stats.failures, 6));
74
+ break;
75
+ }
76
+ }
77
+ stats.queued = queue.length;
78
+ }
79
+ function flush() {
80
+ if (!inFlight)
81
+ inFlight = drain().finally(() => (inFlight = null));
82
+ return inFlight;
83
+ }
84
+ const timer = setInterval(() => void flush(), opts.flushIntervalMs ?? 2000);
85
+ timer.unref?.();
86
+ return {
87
+ flush: async () => {
88
+ backoffUntil = 0;
89
+ await flush();
90
+ },
91
+ close: async () => {
92
+ clearInterval(timer);
93
+ unsubscribe();
94
+ backoffUntil = 0;
95
+ await flush();
96
+ },
97
+ get stats() {
98
+ return { ...stats, queued: queue.length };
99
+ },
100
+ };
101
+ }
102
+ //# sourceMappingURL=cloud.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud.js","sourceRoot":"","sources":["../src/cloud.ts"],"names":[],"mappings":"AA6CA,MAAM,UAAU,YAAY,CAAC,MAAsB,EAAE,IAAkB;IACrE,IAAI,CAAC,IAAI,EAAE,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IAC1F,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,QAAQ,IAAI,6BAA6B,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACrF,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,EAAE,CAAC;IACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC;IACvC,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC;IACzC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC;IACpC,MAAM,KAAK,GAAmB,EAAE,CAAC;IACjC,MAAM,KA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AE,IAAI,CAAC,eAAe,IAAI,IAAI,CAAC,CAAC;IAC3E,KAAgC,CAAC,KAAK,EAAE,EAAE,CAAC;IAE5C,OAAO;QACL,KAAK,EAAE,KAAK,IAAI,EAAE;YAChB,YAAY,GAAG,CAAC,CAAC;YACjB,MAAM,KAAK,EAAE,CAAC;QAChB,CAAC;QACD,KAAK,EAAE,KAAK,IAAI,EAAE;YAChB,aAAa,CAAC,KAAK,CAAC,CAAC;YACrB,WAAW,EAAE,CAAC;YACd,YAAY,GAAG,CAAC,CAAC;YACjB,MAAM,KAAK,EAAE,CAAC;QAChB,CAAC;QACD,IAAI,KAAK;YACP,OAAO,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC;QAC5C,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,17 @@
1
+ import type { Jwks } from "./keys.js";
2
+ export interface ConfirmationClaims {
3
+ sub: string;
4
+ status: "approved" | "declined";
5
+ order_hash: string;
6
+ store: string;
7
+ decided_at: string;
8
+ iat: number;
9
+ iss: string;
10
+ }
11
+ export declare function verifyConfirmation(token: string, opts: {
12
+ jwks?: Jwks;
13
+ jwksUrl?: string;
14
+ orderHash?: string;
15
+ maxAgeSeconds?: number;
16
+ fetch?: typeof fetch;
17
+ }): Promise<ConfirmationClaims>;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Verify a shopper confirmation issued by ProveTheBuy Cloud's hosted confirmation page.
3
+ *
4
+ * const c = await verifyConfirmation(token, { jwksUrl: "https://app.provethebuy.com/.well-known/jwks.json", orderHash });
5
+ * if (c.status === "approved") { ...charge... }
6
+ */
7
+ import { createPublicKey, verify } from "node:crypto";
8
+ export async function verifyConfirmation(token, opts) {
9
+ const [h, p, s] = token.split(".");
10
+ if (!h || !p || !s)
11
+ throw new Error("Not a confirmation token.");
12
+ const header = JSON.parse(Buffer.from(h, "base64url").toString("utf8"));
13
+ if (header.alg !== "EdDSA")
14
+ throw new Error("Unexpected token algorithm.");
15
+ const jwks = opts.jwks ?? (await (await (opts.fetch ?? fetch)(opts.jwksUrl)).json());
16
+ const jwk = jwks.keys.find((k) => k.kid === header.kid);
17
+ if (!jwk)
18
+ throw new Error(`Signing key ${header.kid} is not in the JWKS.`);
19
+ const ok = verify(null, Buffer.from(`${h}.${p}`), createPublicKey({ key: jwk, format: "jwk" }), Buffer.from(s, "base64url"));
20
+ if (!ok)
21
+ throw new Error("Confirmation signature does not verify.");
22
+ const claims = JSON.parse(Buffer.from(p, "base64url").toString("utf8"));
23
+ if (claims.typ !== "provethebuy-confirmation")
24
+ throw new Error("Token is not a ProveTheBuy confirmation.");
25
+ if (opts.orderHash && claims.order_hash !== opts.orderHash)
26
+ throw new Error("Confirmation is for a different order.");
27
+ if (opts.maxAgeSeconds && Date.now() / 1000 - claims.iat > opts.maxAgeSeconds)
28
+ throw new Error("Confirmation is too old.");
29
+ return claims;
30
+ }
31
+ //# sourceMappingURL=confirmation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"confirmation.js","sourceRoot":"","sources":["../src/confirmation.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAatD,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,KAAa,EACb,IAAyG;IAEzG,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IACjE,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IACxE,IAAI,MAAM,CAAC,GAAG,KAAK,OAAO;QAAE,MAAM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GAAG,MAAM,CAAC,GAAG,GAAG,IAAI,CAAC,aAAa;QAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAC3H,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,39 @@
1
+ import { type ProveTheBuyOptions } from "./verify.js";
2
+ import type { EvidenceLedger, VerificationRecord } from "./ledger.js";
3
+ export interface DisputeInput {
4
+ dispute_id: string;
5
+ reason_code: string;
6
+ network?: "visa" | "mastercard" | "amex" | "other";
7
+ amount: number;
8
+ currency: string;
9
+ opened_at?: string;
10
+ }
11
+ export interface ReverifyResult {
12
+ ok: boolean;
13
+ detail: string;
14
+ checks: {
15
+ name: string;
16
+ status: string;
17
+ detail: string;
18
+ }[];
19
+ }
20
+ /**
21
+ * Re-run the signature and mandate checks with the stored raw request and the key snapshot taken at
22
+ * the time, as of the original signing time. Works after the agent's key has rotated.
23
+ */
24
+ export declare function reverifyRecord(rec: VerificationRecord, opts: Pick<ProveTheBuyOptions, "merchantId" | "issuers" | "merchantJwk" | "policy">): Promise<ReverifyResult>;
25
+ export interface EvidencePack {
26
+ dispute_id: string;
27
+ reason: string;
28
+ record_id: string;
29
+ record_hash: string;
30
+ reverification: ReverifyResult;
31
+ submittable: boolean;
32
+ sections: {
33
+ title: string;
34
+ body: string;
35
+ }[];
36
+ /** Plain text suitable for Stripe's uncategorized_text evidence field. */
37
+ text: string;
38
+ }
39
+ export declare function buildEvidencePack(rec: VerificationRecord, dispute: DisputeInput, ledger: EvidenceLedger, opts: Pick<ProveTheBuyOptions, "merchantId" | "issuers" | "merchantJwk" | "policy">): Promise<EvidencePack>;