@integraledger/terms 0.2.0 → 0.3.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 (41) hide show
  1. package/README.md +85 -51
  2. package/dist/agreement.d.ts +14 -4
  3. package/dist/agreement.js +139 -49
  4. package/dist/channels.d.ts +35 -13
  5. package/dist/channels.js +119 -66
  6. package/dist/gate.d.ts +31 -15
  7. package/dist/gate.js +56 -29
  8. package/dist/pairings/batch.d.ts +2 -5
  9. package/dist/pairings/batch.js +1 -11
  10. package/dist/pairings/card.js +0 -2
  11. package/dist/pairings/common.d.ts +4 -3
  12. package/dist/pairings/common.js +4 -3
  13. package/dist/pairings/lnbtc-request.d.ts +1 -1
  14. package/dist/pairings/lnbtc-request.js +1 -1
  15. package/dist/pairings/mpp-charge-hedera.d.ts +7 -7
  16. package/dist/pairings/mpp-charge-hedera.js +1 -1
  17. package/dist/pairings/mpp-charge-tempo-memo.d.ts +1 -9
  18. package/dist/pairings/mpp-charge-tempo-memo.js +3 -7
  19. package/dist/pairings/mpp-charge-tempo-push.d.ts +0 -1
  20. package/dist/pairings/mpp-charge-tempo-push.js +2 -10
  21. package/dist/pairings/mpp-charge-xrpl.js +3 -3
  22. package/dist/pairings/mpp-rails.d.ts +1 -1
  23. package/dist/pairings/mpp-session-xrpl.js +3 -4
  24. package/dist/pairings/mpp.d.ts +12 -16
  25. package/dist/pairings/mpp.js +31 -108
  26. package/dist/pairings/protocol-groups.d.ts +1 -1
  27. package/dist/pairings/x402-account-rails.d.ts +1 -1
  28. package/dist/pairings/x402-batch-settlement-solana.d.ts +2 -0
  29. package/dist/pairings/x402-batch-settlement-solana.js +2 -1
  30. package/dist/pairings/x402-exact-hedera.d.ts +4 -1
  31. package/dist/pairings/x402-exact-hedera.js +5 -2
  32. package/dist/pairings/x402-exact-solana.d.ts +4 -4
  33. package/dist/pairings/x402-exact-solana.js +3 -2
  34. package/dist/pairings/x402-exact-sui.js +3 -1
  35. package/dist/pairings/x402-exact-tvm.js +10 -2
  36. package/dist/pairings/x402-exact-xrpl.js +2 -4
  37. package/dist/pairings/x402-rail.d.ts +1 -1
  38. package/dist/transact.d.ts +3 -2
  39. package/dist/transact.js +9 -6
  40. package/dist/types.d.ts +6 -16
  41. package/package.json +11 -12
package/dist/channels.js CHANGED
@@ -1,21 +1,31 @@
1
1
  /**
2
2
  * The buyer's channel steps. One ATR covers a whole channel: the gate compares it once, at the opening, and the caller
3
3
  * keeps the result as a `ChannelHold`, the ATR's bytes together with the signed opening and the channel it names.
4
- * `within` signs a later voucher only for a channel held this way, re-deriving everything from the hold and never from
5
- * the new challenge, and only when that challenge advertises the held ATR's hash. It serves x402's batch channels and
6
- * MPP's sessions through the binding's `buildWithin`. `recordCharge` records the server's cumulative charge, bounded by
7
- * what was signed.
4
+ * `within` signs a later voucher only for a channel held this way: the ATR's bytes, its hash and the channel come from
5
+ * the hold, and the amount from the new challenge. On x402's batch channels that challenge must advertise the held
6
+ * ATR's hash. On MPP's sessions a challenge that names another channel or another hash is declined, and one with no
7
+ * legal context is signed under the held hash. Both are served through the binding's `buildWithin`. `recordCharge`
8
+ * records the server's cumulative charge, bounded by what was signed.
8
9
  */
9
- import { fromLcpString, hash, hashEquals, parseJson } from "@integraledger/lcp";
10
+ import { fromBase64, fromLcpString, hash, hashEquals, parseJson, toBase64, toBase64Url, } from "@integraledger/lcp/core";
10
11
  import { network as mppNetwork, sessionResume } from "@integraledger/lcp/mpp";
11
- import { offers, requestOf } from "./pairings/mpp.js";
12
+ import { decodeObject, offers, requestOf } from "./pairings/mpp.js";
12
13
  import { isRefusal, refuse, withPaymentIdentifier } from "./pairings/common.js";
14
+ import { KEY } from "./pairings/x402-batch-settlement-solana.js";
13
15
  import { MAX_ATR_BYTES, } from "./types.js";
14
16
  const DECIMAL = /^[0-9]{1,78}$/;
17
+ const U32_MAX = 0xffff_ffff;
18
+ const U64_LIMIT = 1n << 64n;
19
+ /** The pairing whose refunds carry a payer-signed `request_close` when taken again. */
20
+ const SOLANA_BATCH = "x402/batch-settlement/solana";
21
+ /**
22
+ * The code a seller answers a Solana refund with when the receiver's binding is unavailable, as a settle failure's
23
+ * `PAYMENT-RESPONSE` `errorReason` or a payment request's `error`: x402 then takes the refund again, carrying the
24
+ * payer-signed `request_close`.
25
+ */
26
+ const BINDING_UNAVAILABLE = "invalid_batch_settlement_svm_receiver_binding_unavailable";
15
27
  /** At most this many challenges of a within document are looked at, as the MPP entry point reads a document. */
16
28
  const MAX_CHALLENGES = 32;
17
- /** An `opaque` of at most this many base64url characters, 8 KiB decoded, is read. */
18
- const MAX_OPAQUE = 10_924;
19
29
  const NOT_BOUND_WITHIN = /\/not-bound-within$/;
20
30
  const REF_BYTES = 24;
21
31
  const HOLD_KEYS = ["pairing", "network", "channel", "h", "atr", "charged", "signedMax"];
@@ -45,26 +55,20 @@ async function guarded(run) {
45
55
  return refuse("member-failed");
46
56
  }
47
57
  }
48
- function toBase64(bytes) {
49
- let s = "";
50
- for (let i = 0; i < bytes.length; i += 0x8000)
51
- s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
52
- return btoa(s);
53
- }
54
- function fromBase64(s) {
55
- try {
56
- const binary = atob(s);
57
- return Uint8Array.from(binary, (c) => c.charCodeAt(0));
58
- }
59
- catch {
60
- return undefined;
61
- }
62
- }
63
- /** A value as plain JSON, or undefined when it holds anything JSON does not carry. */
58
+ /**
59
+ * A value as the plain JSON `JSON.stringify` writes for it, without the members it leaves out (undefined, a function or
60
+ * a symbol), read back as the protocol package reads JSON, so its arrays and objects nest at most 64 levels; undefined
61
+ * when it holds a number that is not finite, nests deeper, or `JSON.stringify` writes nothing for it or throws.
62
+ */
64
63
  function asJson(v) {
65
64
  try {
66
- const text = JSON.stringify(v);
67
- return text === undefined ? undefined : JSON.parse(text);
65
+ const text = JSON.stringify(v, (_k, x) => {
66
+ const n = x instanceof Number ? x.valueOf() : x;
67
+ if (typeof n === "number" && !Number.isFinite(n))
68
+ throw new RangeError("A number that is not finite.");
69
+ return x;
70
+ });
71
+ return text === undefined ? undefined : parseJson(text);
68
72
  }
69
73
  catch {
70
74
  return undefined;
@@ -93,23 +97,53 @@ async function wouldBeChannel(batch, channel) {
93
97
  return isRefusal(ref) ? declined("offer-unreadable", ref.code) : ref;
94
98
  }
95
99
  /**
96
- * The buyer's own chain values a refund's build takes: a Solana `request_close` needs a recent blockhash when the option
97
- * names none, and may take the Compute Budget values.
100
+ * The buyer's own chain values a Solana refund's `request_close` takes, each optional: `recentBlockhash`, a base58
101
+ * blockhash; `computeUnitLimit`, a u32; and `computeUnitPrice`, a u64 as a decimal string. Undefined when one is given
102
+ * in another form. Only the refund taken again after the seller answers `BINDING_UNAVAILABLE` carries a
103
+ * `request_close`, and it needs the blockhash; the refund before it is the voucher alone, and takes none of these.
98
104
  */
99
105
  function refundInputs(inputs) {
100
106
  const out = {};
101
107
  const { recentBlockhash, computeUnitLimit, computeUnitPrice } = inputs;
102
- if (typeof recentBlockhash === "string")
108
+ if (recentBlockhash !== undefined) {
109
+ if (typeof recentBlockhash !== "string" || !KEY.test(recentBlockhash))
110
+ return undefined;
103
111
  out.recentBlockhash = recentBlockhash;
104
- if (typeof computeUnitLimit === "number" && Number.isSafeInteger(computeUnitLimit))
112
+ }
113
+ if (computeUnitLimit !== undefined) {
114
+ if (typeof computeUnitLimit !== "number" || !Number.isInteger(computeUnitLimit))
115
+ return undefined;
116
+ if (computeUnitLimit < 0 || computeUnitLimit > U32_MAX)
117
+ return undefined;
105
118
  out.computeUnitLimit = computeUnitLimit;
106
- if (typeof computeUnitPrice === "string" && DECIMAL.test(computeUnitPrice))
119
+ }
120
+ if (computeUnitPrice !== undefined) {
121
+ if (typeof computeUnitPrice !== "string" || !DECIMAL.test(computeUnitPrice))
122
+ return undefined;
123
+ if (BigInt(computeUnitPrice) >= U64_LIMIT)
124
+ return undefined;
107
125
  out.computeUnitPrice = BigInt(computeUnitPrice);
126
+ }
108
127
  return out;
109
128
  }
129
+ /**
130
+ * Whether a Solana refund is taken again after the receiver's binding is unavailable, as x402's reference client
131
+ * decides it: the `errorReason` of `refund.paymentResponse`, the settle failure's decoded `PAYMENT-RESPONSE`, read
132
+ * first, or else the payment request's `error`, is `BINDING_UNAVAILABLE`. Undefined when `paymentResponse` is given
133
+ * and is not an object, or its `errorReason` is given and is not a string.
134
+ */
135
+ function takenAgain(refund, required) {
136
+ const response = refund.paymentResponse;
137
+ if (response !== undefined && !isObject(response))
138
+ return undefined;
139
+ const settled = isObject(response) ? response["errorReason"] : undefined;
140
+ if (settled !== undefined && settled !== null && typeof settled !== "string")
141
+ return undefined;
142
+ return (settled ?? (isObject(required) ? required["error"] : undefined)) === BINDING_UNAVAILABLE;
143
+ }
110
144
  /** 24 random bytes as unpadded base64url: 32 characters from `[A-Za-z0-9_-]`. */
111
145
  function newRef() {
112
- return toBase64(crypto.getRandomValues(new Uint8Array(REF_BYTES))).replace(/\+/g, "-").replace(/\//g, "_");
146
+ return toBase64Url(crypto.getRandomValues(new Uint8Array(REF_BYTES)));
113
147
  }
114
148
  /** The opening voucher's `maxClaimableAmount`, where the payment carries one, else "0". */
115
149
  function openingMax(signed) {
@@ -121,7 +155,8 @@ function openingMax(signed) {
121
155
  /**
122
156
  * Takes a channel pairing's signed opening and the ATR bytes the gate compared for it, with the landed receipt
123
157
  * `transact` returned beside the opening, where it returned one. The opening, with that receipt, must be of kind `open`,
124
- * carry the hash of these bytes, and name its channel; the hold keeps all three together.
158
+ * the pairing must read the hash of these bytes from it, and it must name its channel; the hold keeps all three
159
+ * together.
125
160
  */
126
161
  export async function openChannel(bytes, opened, binding, landed) {
127
162
  const b = stepsOf(binding);
@@ -143,7 +178,7 @@ export async function openChannel(bytes, opened, binding, landed) {
143
178
  const h = await hash(bytes);
144
179
  const inside = await guarded(() => b.bound(signed));
145
180
  if (isRefusal(inside) || !hashEquals(inside, h)) {
146
- return declined("signed-not-bound", "The opening does not carry the hash of these bytes.");
181
+ return declined("signed-not-bound", "The pairing does not read the hash of the compared bytes from the opening.");
147
182
  }
148
183
  const ref = await guarded(() => channel.ref(signed));
149
184
  if (isRefusal(ref))
@@ -164,11 +199,25 @@ export async function openChannel(bytes, opened, binding, landed) {
164
199
  }
165
200
  /**
166
201
  * Signs one later voucher, or a refund, in a held channel. The ATR bytes, the opening's hash and the opening's
167
- * channel are re-derived from the hold, and the challenge must advertise the held hash. A voucher's
168
- * `maxClaimableAmount` is the recorded charge plus the option's amount; a refund's is the recorded charge. `inputs`
169
- * are the buyer's own chain values a refund's build takes. Before the signer is called, the channel the built payment
170
- * would name must be the held one. What was signed must be of the expected kind and belong to the held channel, or it
171
- * is dropped.
202
+ * channel are re-derived from the hold. An x402 challenge must advertise the held hash. An MPP session's challenge
203
+ * that names another channel or another hash is declined, and one with no legal context is signed under the held
204
+ * hash. A voucher's `maxClaimableAmount` is the recorded charge plus the option's amount; a refund's is the recorded
205
+ * charge. `inputs` are the buyer's own chain values a refund's build takes; `inputs` that is not an object is declined
206
+ * `no-payable-option` with `<namespace>/input-malformed`.
207
+ *
208
+ * A Solana refund is the voucher alone. Taken again after the receiver's binding is unavailable, it also carries the
209
+ * payer-signed `request_close`, built with the `recentBlockhash`, `computeUnitLimit` and `computeUnitPrice` of
210
+ * `inputs`: when the `errorReason` of `refund.paymentResponse`, the settle failure's decoded `PAYMENT-RESPONSE`, read
211
+ * first, or else the challenge's `error`, is `invalid_batch_settlement_svm_receiver_binding_unavailable`. A Solana
212
+ * refund value given in another form, or a `paymentResponse` that is not an object or whose `errorReason` is not a
213
+ * string, is declined `no-payable-option` with `x402/input-malformed`, and the refund taken again without a
214
+ * `recentBlockhash` with `x402/input-missing`. No other pairing's refund reads these values or this code.
215
+ *
216
+ * On x402's batch channels, the channel the built payment would name must be the held one before the signer is called.
217
+ * On MPP's sessions, a channel the challenge names must be the held one and a legal context, where present, must name
218
+ * the held hash, before the signer is called, and the voucher is built from the held opening. In both, the signed
219
+ * payment must then be of the expected kind, commit to the held hash where the pairing's voucher carries one, and
220
+ * name the held channel, or it is dropped.
172
221
  */
173
222
  export async function within(doc, hold, binding, signer, refund, inputs = {}) {
174
223
  const b = stepsOf(binding);
@@ -190,16 +239,18 @@ export async function within(doc, hold, binding, signer, refund, inputs = {}) {
190
239
  }
191
240
  refundAmount = refund.amount === undefined ? undefined : BigInt(refund.amount);
192
241
  }
242
+ if (!isObject(inputs))
243
+ return declined("no-payable-option", `${ns}/input-malformed`);
193
244
  const channel = b.channel;
194
245
  const bytes = fromBase64(hold.atr);
195
- if (bytes === undefined || bytes.length > MAX_ATR_BYTES)
246
+ if (bytes === null || bytes.length > MAX_ATR_BYTES)
196
247
  return declined("signed-not-bound", "The held ATR is unreadable.");
197
248
  const h = await hash(bytes);
198
249
  if (!hashEquals(hold.h, h))
199
250
  return declined("hash-mismatch", "The held ATR does not hash to the held hash.");
200
251
  const opened = await guarded(() => b.bound(hold.opening));
201
252
  if (isRefusal(opened) || !hashEquals(opened, h)) {
202
- return declined("signed-not-bound", "The held opening does not carry the held ATR's hash.");
253
+ return declined("signed-not-bound", "The pairing does not read the held ATR's hash from the held opening.");
203
254
  }
204
255
  const openedRef = await guarded(() => channel.ref(hold.opening));
205
256
  if (isRefusal(openedRef) || openedRef.network !== hold.network || openedRef.channel !== hold.channel) {
@@ -225,13 +276,20 @@ export async function within(doc, hold, binding, signer, refund, inputs = {}) {
225
276
  const payload = hold.opening["payload"];
226
277
  const channelConfig = isObject(payload) ? payload["channelConfig"] : undefined;
227
278
  const required = isObject(offer) ? offer["required"] : undefined;
279
+ const solanaRefund = refund !== undefined && b.id === SOLANA_BATCH;
280
+ const values = solanaRefund ? refundInputs(inputs) : {};
281
+ const retry = solanaRefund ? takenAgain(refund, required) : false;
282
+ if (values === undefined || retry === undefined)
283
+ return declined("no-payable-option", `${ns}/input-malformed`);
284
+ if (retry && values.recentBlockhash === undefined)
285
+ return declined("no-payable-option", `${ns}/input-missing`);
228
286
  const unsigned = await guarded(() => b.buildWithin({
229
287
  required,
230
288
  accepted,
231
289
  channelConfig,
232
290
  maxClaimableAmount,
233
291
  ...(refund !== undefined ? { refund: refundAmount === undefined ? {} : { amount: refundAmount } } : {}),
234
- ...(refund !== undefined ? refundInputs(isObject(inputs) ? inputs : {}) : {}),
292
+ ...(retry ? values : {}),
235
293
  }, h));
236
294
  if (isRefusal(unsigned))
237
295
  return declined("offer-unreadable", unsigned.code);
@@ -280,10 +338,10 @@ export async function within(doc, hold, binding, signer, refund, inputs = {}) {
280
338
  /**
281
339
  * One voucher, or the close, in a held MPP session. The within challenge is the first of the document that either
282
340
  * offers the pairing on the held network, or names a channel of the pairing on the held network, as `sessionResume`
283
- * reads it for the pairing's method. A named channel must be the held one, and a legal context in
284
- * the challenge's `opaque` must name the held hash; either is checked before the signer is called. The voucher's
285
- * cumulative amount is the recorded charge plus the challenge's amount, and the close's is the recorded charge. Every
286
- * channel value comes from the held opening, through the binding's `buildWithin`.
341
+ * reads it for the pairing's method. A named channel must be the held one, the challenge's `opaque`, where present,
342
+ * must be MPP's flat string-to-string map, and a legal context in it must name the held hash; each is checked before
343
+ * the signer is called. The voucher's cumulative amount is the recorded charge plus the challenge's amount, and the
344
+ * close's is the recorded charge. Every channel value comes from the held opening, through the binding's `buildWithin`.
287
345
  */
288
346
  async function sessionWithin(b, doc, hold, h, signer, refund) {
289
347
  if (refund !== undefined && refund.amount !== undefined) {
@@ -317,8 +375,8 @@ async function sessionWithin(b, doc, hold, h, signer, refund) {
317
375
  if (challenge === undefined)
318
376
  return declined("no-payable-option", "mpp/no-payable-option");
319
377
  const named = legalContextOf(challenge);
320
- if (named === "malformed")
321
- return declined("offer-unreadable", "mpp/legal-context-malformed");
378
+ if (isRefusal(named))
379
+ return declined("offer-unreadable", named.code);
322
380
  if (named !== undefined && !hashEquals(named, h)) {
323
381
  return declined("hash-mismatch", "The challenge names another ATR's hash than the one this channel opened for.");
324
382
  }
@@ -376,32 +434,27 @@ function namedChannel(c, pairing) {
376
434
  }
377
435
  /**
378
436
  * The hash a challenge's `opaque` names as its legal context: undefined when there is no `opaque` or it has no
379
- * `legalContext` member, "malformed" when either cannot be read.
437
+ * `legalContext` member; `mpp/opaque-malformed` when the `opaque` is not a flat string-to-string map (`opaqueMap`);
438
+ * `mpp/legal-context-malformed` when its `legalContext` is not an LCP string.
380
439
  */
381
440
  function legalContextOf(c) {
382
441
  if (c.opaque === undefined)
383
442
  return undefined;
384
- const map = typeof c.opaque === "string" ? base64UrlJson(c.opaque) : undefined;
385
- if (!isObject(map))
386
- return "malformed";
443
+ const map = opaqueMap(c.opaque);
444
+ if (map === undefined)
445
+ return refuse("mpp/opaque-malformed");
387
446
  const lc = map["legalContext"];
388
447
  if (lc === undefined)
389
448
  return undefined;
390
- const named = typeof lc === "string" ? fromLcpString(lc) : null;
391
- return named ?? "malformed";
449
+ return fromLcpString(lc) ?? refuse("mpp/legal-context-malformed");
392
450
  }
393
- /** A base64url string's bytes read as one JSON value, or undefined. */
394
- function base64UrlJson(s) {
395
- if (s.length > MAX_OPAQUE || !/^[A-Za-z0-9_-]*$/.test(s))
396
- return undefined;
397
- try {
398
- const b64 = s.replace(/-/g, "+").replace(/_/g, "/");
399
- const binary = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
400
- return parseJson(new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (ch) => ch.charCodeAt(0))));
401
- }
402
- catch {
403
- return undefined;
404
- }
451
+ /**
452
+ * An `opaque` read as MPP's flat string-to-string map: an object `decodeObject` reads, whose members are all strings.
453
+ * Undefined for anything else.
454
+ */
455
+ function opaqueMap(s) {
456
+ const v = decodeObject(s);
457
+ return v !== undefined && Object.values(v).every((m) => typeof m === "string") ? v : undefined;
405
458
  }
406
459
  /**
407
460
  * Records the server's cumulative charge for the channel. It must be a decimal no lower than the charge last recorded
package/dist/gate.d.ts CHANGED
@@ -1,14 +1,16 @@
1
1
  /**
2
2
  * The buyer gate. `confirm` reads the offer, fetches the ATR from the seller's link, compares its SHA-256 with the
3
3
  * advertised hash, and only on a match builds the signing request with the hash it computed. `finish` completes the
4
- * payment with the signature and returns it only when what was signed carries the hash of these bytes, or, for a pairing
5
- * whose proof is the agreement payment, completes it without that reading. `check` confirms a payment held later against
6
- * kept bytes.
4
+ * payment with the signature and returns it only when the pairing's `bound` reads the hash of these bytes from the
5
+ * completed payment, or, for a pairing whose proof is the agreement payment, completes it without that reading. `check`
6
+ * confirms a payment held later against kept bytes.
7
7
  */
8
- import { type AtrHash } from "@integraledger/lcp";
8
+ import { type AtrHash } from "@integraledger/lcp/core";
9
9
  import { type Binding, type BuyerPiece, type Chosen, type DeclineCode, type Declined, type Fetch, type Inputs, type Presented, type Signature, type Signer, type SigningRequest } from "./types.js";
10
10
  export declare function declined(code: DeclineCode, detail: string): Declined;
11
11
  export declare function isObject(v: unknown): v is Record<string, unknown>;
12
+ /** Whether a signer's `account` is a string, the form every pairing reads its payer from. */
13
+ export declare function hasAccount(signer: unknown): boolean;
12
14
  /** The pairing's namespace: its id up to the first `/`. */
13
15
  export declare function namespaceOf(binding: Binding): string;
14
16
  export declare function pieceOf(binding: Binding): BuyerPiece | undefined;
@@ -21,13 +23,23 @@ export declare function redirected(response: Response): boolean;
21
23
  export declare const IDENTITY: {
22
24
  readonly "Accept-Encoding": "identity";
23
25
  };
24
- /** Whether a `Content-Encoding` value names no coding: absent, empty, or `identity`. */
26
+ /**
27
+ * A header value without its leading and trailing HTTP whitespace, as Fetch normalizes one. Any other character stays,
28
+ * so a value it surrounds is read as written.
29
+ */
30
+ export declare function trimHttpWhitespace(value: string): string;
31
+ /**
32
+ * Whether a `Content-Encoding` value names no coding: absent, empty, or `identity`, surrounding spaces, tabs, CRs and
33
+ * LFs aside.
34
+ */
25
35
  export declare function isIdentity(contentEncoding: string | null): boolean;
26
36
  /**
27
37
  * Reads the offer, chooses the option, fetches the ATR and compares its SHA-256 with the advertised hash. Only on a
28
- * match does it build, with the hash it computed. A pairing whose build has nothing for the buyer to sign returns
29
- * `request: null`: the comparison is the whole of the buyer's step. For a pairing whose payment is not itself a public
30
- * proof, `chosen.agreement` is the agreement URL the offer names.
38
+ * match does it build, with the hash it computed. `request` is what the signer is handed, or `null` when nothing is
39
+ * handed to the signer: the pairing has nothing for the buyer to sign, or the build is itself the payment, which
40
+ * `finish` completes with no signature. For a pairing whose payment is not itself a public proof, `chosen.agreement` is
41
+ * the agreement URL the offer names. `inputs` that is not an object is declined `no-payable-option` with
42
+ * `<namespace>/input-malformed` before the offer is read.
31
43
  */
32
44
  export declare function confirm(doc: unknown, binding: Binding, account: string, fetch: Fetch, inputs?: Inputs): Promise<{
33
45
  chosen: Chosen;
@@ -36,12 +48,13 @@ export declare function confirm(doc: unknown, binding: Binding, account: string,
36
48
  h: AtrHash;
37
49
  } | Declined>;
38
50
  /**
39
- * Rebuilds the payment from `chosen` and the bytes, joins the signer's answer, and returns the payment only when what
40
- * was signed carries the hash of these bytes. For a pairing whose payment is not a public proof and whose `bound` finds
41
- * no signed place for the hash, the proof is the agreement payment, and the completed payment is returned as it is.
42
- * Where the signer moved the payment itself, a decline keeps it as `moved`. Where the completion carried the landed
43
- * receipt `bound` reads and the payment sent leaves it out, `landed` is returned beside the payment as JSON, each integer
44
- * a decimal string, so `check` and `openChannel` can later read the payment with it.
51
+ * Rebuilds the payment from `chosen` and the bytes, joins the signer's answer, and returns the payment only when the
52
+ * pairing's `bound` reads the hash of these bytes from the completed payment. For a pairing whose payment is not a
53
+ * public proof and whose `bound` finds no signed place for the hash, the proof is the agreement payment, and the
54
+ * completed payment is returned as it is. Where the signer moved the payment itself, a decline keeps it as `moved`.
55
+ * Where the completion carried the landed receipt `bound` reads and the payment sent leaves it out, `landed` is
56
+ * returned beside the payment as JSON, each integer a decimal string, so `check` and `openChannel` can later read the
57
+ * payment with it.
45
58
  */
46
59
  export declare function finish(bytes: Uint8Array, chosen: Chosen, signature: Signature, binding: Binding): Promise<{
47
60
  signed: Presented;
@@ -51,7 +64,10 @@ export declare function finish(bytes: Uint8Array, chosen: Chosen, signature: Sig
51
64
  next: SigningRequest;
52
65
  h: AtrHash;
53
66
  } | Declined>;
54
- /** Confirms that a payment held later carries, inside what was signed, the hash of the kept bytes. */
67
+ /**
68
+ * Confirms that the ATR hash the pairing reads from a payment held later is the SHA-256 of the kept bytes. A payment
69
+ * from which the pairing reads no ATR hash is declined `signed-not-bound`.
70
+ */
55
71
  export declare function check(bytes: Uint8Array, presented: unknown, binding: Binding): Promise<{
56
72
  h: AtrHash;
57
73
  } | Declined>;
package/dist/gate.js CHANGED
@@ -1,22 +1,24 @@
1
1
  /**
2
2
  * The buyer gate. `confirm` reads the offer, fetches the ATR from the seller's link, compares its SHA-256 with the
3
3
  * advertised hash, and only on a match builds the signing request with the hash it computed. `finish` completes the
4
- * payment with the signature and returns it only when what was signed carries the hash of these bytes, or, for a pairing
5
- * whose proof is the agreement payment, completes it without that reading. `check` confirms a payment held later against
6
- * kept bytes.
4
+ * payment with the signature and returns it only when the pairing's `bound` reads the hash of these bytes from the
5
+ * completed payment, or, for a pairing whose proof is the agreement payment, completes it without that reading. `check`
6
+ * confirms a payment held later against kept bytes.
7
7
  */
8
- import { hash, hashEquals, isHttpsLink, isOtherSchemeLink } from "@integraledger/lcp";
8
+ import { hash, hashEquals, isHttpsLink, isOtherSchemeLink, toBase64Url, } from "@integraledger/lcp/core";
9
9
  import { isRefusal, refuse } from "./pairings/common.js";
10
10
  import { PIECES } from "./pairings/index.js";
11
11
  import { MAX_ATR_BYTES, } from "./types.js";
12
- const steps = (binding) => binding;
12
+ /** The binding's members, as the gate calls them. */
13
+ function steps(binding) {
14
+ return binding;
15
+ }
13
16
  /** A build refusal that means the pairing has nothing for the buyer to sign: the gate confirms only. */
14
17
  const NOTHING_TO_SIGN = /\/(no-signed-place|nothing-to-sign)$/;
15
18
  /** The most signer calls one payment takes: a funding and then a voucher. */
16
19
  const MAX_STEPS = 2;
17
20
  const FETCH_DEADLINE_MS = 10_000;
18
21
  const REF_BYTES = 24;
19
- const BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
20
22
  const DECIMAL = /^[0-9]+$/;
21
23
  export function declined(code, detail) {
22
24
  return { decline: { code, detail } };
@@ -24,6 +26,10 @@ export function declined(code, detail) {
24
26
  export function isObject(v) {
25
27
  return typeof v === "object" && v !== null && !Array.isArray(v);
26
28
  }
29
+ /** Whether a signer's `account` is a string, the form every pairing reads its payer from. */
30
+ export function hasAccount(signer) {
31
+ return typeof signer?.account === "string";
32
+ }
27
33
  /** The pairing's namespace: its id up to the first `/`. */
28
34
  export function namespaceOf(binding) {
29
35
  return String(binding.id).split("/")[0];
@@ -48,13 +54,7 @@ export function unsupported(binding) {
48
54
  const tooLarge = () => declined("atr-too-large", `The ATR is larger than ${MAX_ATR_BYTES} bytes.`);
49
55
  /** 24 random bytes as unpadded base64url: 32 characters from `[A-Za-z0-9_-]`. */
50
56
  export function newRef() {
51
- const b = crypto.getRandomValues(new Uint8Array(REF_BYTES));
52
- let s = "";
53
- for (let i = 0; i < b.length; i += 3) {
54
- const n = (b[i] << 16) | (b[i + 1] << 8) | b[i + 2];
55
- s += BASE64URL[(n >> 18) & 63] + BASE64URL[(n >> 12) & 63] + BASE64URL[(n >> 6) & 63] + BASE64URL[n & 63];
56
- }
57
- return s;
57
+ return toBase64Url(crypto.getRandomValues(new Uint8Array(REF_BYTES)));
58
58
  }
59
59
  /** Whether an answer to a `redirect: "manual"` request is a redirect: a 3xx status, or the opaque form a browser gives. */
60
60
  export function redirected(response) {
@@ -62,9 +62,27 @@ export function redirected(response) {
62
62
  }
63
63
  /** The request header that asks for the body with no content coding, so the bytes hashed are the bytes sent. */
64
64
  export const IDENTITY = { "Accept-Encoding": "identity" };
65
- /** Whether a `Content-Encoding` value names no coding: absent, empty, or `identity`. */
65
+ /** HTTP whitespace, as the Fetch standard names it: tab, LF, CR and space. */
66
+ const HTTP_WHITESPACE = "\t\n\r ";
67
+ /**
68
+ * A header value without its leading and trailing HTTP whitespace, as Fetch normalizes one. Any other character stays,
69
+ * so a value it surrounds is read as written.
70
+ */
71
+ export function trimHttpWhitespace(value) {
72
+ let start = 0;
73
+ let end = value.length;
74
+ while (start < end && HTTP_WHITESPACE.includes(value[start]))
75
+ start++;
76
+ while (end > start && HTTP_WHITESPACE.includes(value[end - 1]))
77
+ end--;
78
+ return value.slice(start, end);
79
+ }
80
+ /**
81
+ * Whether a `Content-Encoding` value names no coding: absent, empty, or `identity`, surrounding spaces, tabs, CRs and
82
+ * LFs aside.
83
+ */
66
84
  export function isIdentity(contentEncoding) {
67
- const v = (contentEncoding ?? "").trim().toLowerCase();
85
+ const v = trimHttpWhitespace(contentEncoding ?? "").toLowerCase();
68
86
  return v === "" || v === "identity";
69
87
  }
70
88
  /**
@@ -96,7 +114,8 @@ async function fetchAtr(fetch, link) {
96
114
  if (!isIdentity(response.headers.get("content-encoding"))) {
97
115
  return declined("atr-unfetchable", "The link served a content coding other than identity.");
98
116
  }
99
- const declared = response.headers.get("content-length")?.trim();
117
+ const length = response.headers.get("content-length");
118
+ const declared = length === null ? undefined : trimHttpWhitespace(length);
100
119
  if (declared !== undefined && DECIMAL.test(declared) && Number(declared) > MAX_ATR_BYTES)
101
120
  return tooLarge();
102
121
  if (body === null) {
@@ -150,14 +169,18 @@ function cancel(s) {
150
169
  }
151
170
  /**
152
171
  * Reads the offer, chooses the option, fetches the ATR and compares its SHA-256 with the advertised hash. Only on a
153
- * match does it build, with the hash it computed. A pairing whose build has nothing for the buyer to sign returns
154
- * `request: null`: the comparison is the whole of the buyer's step. For a pairing whose payment is not itself a public
155
- * proof, `chosen.agreement` is the agreement URL the offer names.
172
+ * match does it build, with the hash it computed. `request` is what the signer is handed, or `null` when nothing is
173
+ * handed to the signer: the pairing has nothing for the buyer to sign, or the build is itself the payment, which
174
+ * `finish` completes with no signature. For a pairing whose payment is not itself a public proof, `chosen.agreement` is
175
+ * the agreement URL the offer names. `inputs` that is not an object is declined `no-payable-option` with
176
+ * `<namespace>/input-malformed` before the offer is read.
156
177
  */
157
178
  export async function confirm(doc, binding, account, fetch, inputs = {}) {
158
179
  const piece = pieceOf(binding);
159
180
  if (piece === undefined)
160
181
  return unsupported(binding);
182
+ if (!isObject(inputs))
183
+ return declined("no-payable-option", `${namespaceOf(binding)}/input-malformed`);
161
184
  const b = steps(binding);
162
185
  const read = b.read(doc);
163
186
  if (isRefusal(read))
@@ -166,7 +189,7 @@ export async function confirm(doc, binding, account, fetch, inputs = {}) {
166
189
  if (agreement !== undefined && typeof agreement !== "string") {
167
190
  return declined("offer-unreadable", "The offer names an agreement URL that is not a string.");
168
191
  }
169
- const choice = await piece.choose(read, account, isObject(inputs) ? inputs : {}, Math.floor(Date.now() / 1000), newRef(), doc);
192
+ const choice = await piece.choose(read, account, inputs, Math.floor(Date.now() / 1000), newRef(), doc);
170
193
  if (isRefusal(choice))
171
194
  return declined("no-payable-option", choice.code);
172
195
  const chosen = agreement === undefined ? choice : { ...choice, agreement };
@@ -206,12 +229,13 @@ async function buildWith(piece, b, chosen, h, bytes) {
206
229
  }
207
230
  }
208
231
  /**
209
- * Rebuilds the payment from `chosen` and the bytes, joins the signer's answer, and returns the payment only when what
210
- * was signed carries the hash of these bytes. For a pairing whose payment is not a public proof and whose `bound` finds
211
- * no signed place for the hash, the proof is the agreement payment, and the completed payment is returned as it is.
212
- * Where the signer moved the payment itself, a decline keeps it as `moved`. Where the completion carried the landed
213
- * receipt `bound` reads and the payment sent leaves it out, `landed` is returned beside the payment as JSON, each integer
214
- * a decimal string, so `check` and `openChannel` can later read the payment with it.
232
+ * Rebuilds the payment from `chosen` and the bytes, joins the signer's answer, and returns the payment only when the
233
+ * pairing's `bound` reads the hash of these bytes from the completed payment. For a pairing whose payment is not a
234
+ * public proof and whose `bound` finds no signed place for the hash, the proof is the agreement payment, and the
235
+ * completed payment is returned as it is. Where the signer moved the payment itself, a decline keeps it as `moved`.
236
+ * Where the completion carried the landed receipt `bound` reads and the payment sent leaves it out, `landed` is
237
+ * returned beside the payment as JSON, each integer a decimal string, so `check` and `openChannel` can later read the
238
+ * payment with it.
215
239
  */
216
240
  export async function finish(bytes, chosen, signature, binding) {
217
241
  const piece = pieceOf(binding);
@@ -247,7 +271,7 @@ export async function finish(bytes, chosen, signature, binding) {
247
271
  const inside = await boundOf(b, signed);
248
272
  const onAgreement = !isPublicProof(binding) && isRefusal(inside) && NOTHING_TO_SIGN.test(inside.code);
249
273
  if (!onAgreement && (isRefusal(inside) || !hashEquals(inside, h))) {
250
- return keep(declined("signed-not-bound", "What was signed does not carry the hash of these bytes."), sent);
274
+ return keep(declined("signed-not-bound", "The pairing does not read the hash of the compared bytes from the payment."), sent);
251
275
  }
252
276
  const landed = sent !== signed && isObject(signed) ? jsonSafe(signed.landed) : undefined;
253
277
  return landed === undefined ? { signed: sent, h } : { signed: sent, landed, h };
@@ -280,14 +304,17 @@ async function boundOf(b, presented) {
280
304
  return refuse("bound-failed");
281
305
  }
282
306
  }
283
- /** Confirms that a payment held later carries, inside what was signed, the hash of the kept bytes. */
307
+ /**
308
+ * Confirms that the ATR hash the pairing reads from a payment held later is the SHA-256 of the kept bytes. A payment
309
+ * from which the pairing reads no ATR hash is declined `signed-not-bound`.
310
+ */
284
311
  export async function check(bytes, presented, binding) {
285
312
  if (bytes.length > MAX_ATR_BYTES)
286
313
  return tooLarge();
287
314
  const h = await hash(bytes);
288
315
  const b = await boundOf(steps(binding), presented);
289
316
  if (isRefusal(b) || !hashEquals(b, h)) {
290
- return declined("signed-not-bound", "The payment does not carry the hash of these bytes.");
317
+ return declined("signed-not-bound", "The pairing does not read the hash of the compared bytes from the payment.");
291
318
  }
292
319
  return { h };
293
320
  }
@@ -3,13 +3,10 @@
3
3
  * built, and the payment the list of answers completes, with the payment
4
4
  * identifier appended where the challenge advertises it.
5
5
  */
6
- import type { Json, Refusal } from "@integraledger/lcp";
6
+ import type { Json, Refusal } from "@integraledger/lcp/core";
7
7
  import type { PaymentRequirements } from "@integraledger/lcp/x402";
8
8
  import type { Chosen, Inputs, Presented, Signature, SigningRequest } from "../types.js";
9
- /**
10
- * The deposit: `extra.minDeposit` when the option carries one, else the buyer's `deposit` input. A deposit above the
11
- * buyer's `maxDeposit` input, when given, is refused.
12
- */
9
+ /** The deposit: `extra.minDeposit` when the option carries one, else the buyer's `deposit` input. */
13
10
  export declare function depositOf(accepted: PaymentRequirements, inputs: Inputs): string | Refusal;
14
11
  /** `n` bytes from the platform's CSPRNG. */
15
12
  export declare function randomBytes(n: number): Uint8Array;
@@ -1,20 +1,10 @@
1
1
  import { bigintOf, choiceOf, hexOf, isObject, isRefusal, refuse, withPaymentIdentifier } from "./common.js";
2
- /**
3
- * The deposit: `extra.minDeposit` when the option carries one, else the buyer's `deposit` input. A deposit above the
4
- * buyer's `maxDeposit` input, when given, is refused.
5
- */
2
+ /** The deposit: `extra.minDeposit` when the option carries one, else the buyer's `deposit` input. */
6
3
  export function depositOf(accepted, inputs) {
7
4
  const min = isObject(accepted.extra) ? accepted.extra["minDeposit"] : undefined;
8
5
  const deposit = min !== undefined ? bigintOf(min) : bigintOf(inputs["deposit"]);
9
6
  if (deposit === undefined)
10
7
  return refuse(min !== undefined ? "x402/option-malformed" : "x402/input-missing");
11
- if (inputs["maxDeposit"] !== undefined) {
12
- const max = bigintOf(inputs["maxDeposit"]);
13
- if (max === undefined)
14
- return refuse("x402/input-missing");
15
- if (deposit > max)
16
- return refuse("x402/deposit-above-maximum");
17
- }
18
8
  return deposit.toString();
19
9
  }
20
10
  /** `n` bytes from the platform's CSPRNG. */
@@ -6,8 +6,6 @@ function chooseDoc(_read, account, _inputs, _now, _ref, doc) {
6
6
  const unnamed = unnamedBuyer(account, NS);
7
7
  if (unnamed !== undefined)
8
8
  return unnamed;
9
- if (doc === undefined)
10
- return refuse("card/document-missing");
11
9
  return { doc: doc };
12
10
  }
13
11
  function docOf(chosen) {
@@ -2,14 +2,15 @@
2
2
  * What the buyer pieces share: the CAIP-10 account, the first x402 option on the account's network, the payment
3
3
  * identifier the x402 client writes, and the JSON forms of byte strings and integers.
4
4
  */
5
- import { type Json, type Refusal } from "@integraledger/lcp";
5
+ import { type Json, type Refusal } from "@integraledger/lcp/core";
6
6
  import type { PaymentRequired, PaymentRequirements, X402Offer } from "@integraledger/lcp/x402";
7
7
  import type { Chosen, Inputs, Read } from "../types.js";
8
8
  /** A refusal with `code`, made by the gate. */
9
9
  export declare function refuse(code: string): Refusal;
10
10
  /**
11
- * True for a refusal the protocol package made (its `isRefusal`) or the gate made (`refuse`). A value from a seller,
12
- * a signer or a caller that is shaped `{ refused: true, … }` is neither, so it is never passed on as a refusal.
11
+ * True for a refusal any installed copy of the protocol package made (its `isRefusal`, which reads the package's mark)
12
+ * or the gate made (`refuse`). The mark and membership, not shape, make a value one of them: a value from a seller, a
13
+ * signer or a caller that is shaped `{ refused: true, … }` is never passed on as a refusal.
13
14
  */
14
15
  export declare function isRefusal(v: unknown): v is Refusal;
15
16
  export declare function isObject(v: unknown): v is Record<string, unknown>;