uvd-x402-sdk 2.75.0 → 2.77.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/dx402.ts CHANGED
@@ -856,6 +856,41 @@ export interface AnchorOptions {
856
856
  * anchor for the same payment supersedes it.
857
857
  */
858
858
  sign?: (digest: Uint8Array) => string | Promise<string>;
859
+ /**
860
+ * `(sealedBytes) => pointer`. Bring your own storage.
861
+ *
862
+ * Without this the sealed envelope travels **inside** the anchor request and
863
+ * the facilitator hosts it, which is the easy path and stays the default. With
864
+ * it, the SDK still seals exactly as before -- the buyer has to be able to
865
+ * decrypt, so the sealing is not optional -- then hands you the ciphertext,
866
+ * you write it wherever you keep durable bytes, and you return the pointer
867
+ * that addresses it. The request then carries only that pointer, so the
868
+ * ciphertext never travels through the anchor call and
869
+ * {@link ANCHOR_MAX_REQUEST_BYTES} does not apply to your body.
870
+ *
871
+ * A callable rather than a precomputed pointer, for the same reason
872
+ * {@link AnchorOptions.sign} is one: the SDK must seal first, and only then
873
+ * can anything be uploaded. Handing in a pointer computed in advance would
874
+ * mean addressing bytes that do not exist yet.
875
+ *
876
+ * The returned pointer is what the buyer will dereference, so it must be
877
+ * readable by them -- see {@link dereferencePointer} for the schemes the SDK
878
+ * resolves out of the box. It is also bound into the seller signature.
879
+ *
880
+ * **It is never allowed to break the sale.** If it throws or returns
881
+ * something unusable, the anchor degrades to a skip and the payment is
882
+ * untouched.
883
+ */
884
+ upload?: (sealed: Uint8Array) => string | Promise<string>;
885
+ /**
886
+ * Which storage family the pointer belongs to: `s3`, `ipfs` or `arweave`.
887
+ *
888
+ * Defaults to `s3`, and in {@link AnchorOptions.upload} mode it is inferred
889
+ * from the pointer's scheme when you do not say. Distinct from `storage`,
890
+ * which names one of the FACILITATOR's own offers and is meaningless when you
891
+ * supply the bytes yourself.
892
+ */
893
+ backend?: 's3' | 'ipfs' | 'arweave';
859
894
  retention?: string;
860
895
  facilitator?: string;
861
896
  fetch?: typeof fetch;
@@ -867,6 +902,34 @@ export interface AnchorOptions {
867
902
  * **It never throws.** Every failure resolves to a skip notice, because evidence
868
903
  * is an addition to the payment path and must never be a gate in front of it —
869
904
  * an unreachable facilitator has to cost the receipt, never the sale.
905
+ *
906
+ * # Two ways to store the ciphertext
907
+ *
908
+ * **Hosted (default).** The sealed envelope travels inside the anchor request
909
+ * and the facilitator stores it and issues the pointer. Nothing to set up. The
910
+ * request carries the ciphertext, so it is bounded by
911
+ * {@link ANCHOR_MAX_REQUEST_BYTES}.
912
+ *
913
+ * **Your own storage.** Pass {@link AnchorOptions.upload}. The SDK seals
914
+ * identically, hands you the ciphertext, and sends the pointer you return in
915
+ * place of the blob — so the ciphertext never travels through the anchor call
916
+ * and that request bound does not apply to your body. The facilitator has
917
+ * accepted a caller-supplied pointer since v0.1; this is the SDK catching up.
918
+ *
919
+ * ```ts
920
+ * await anchorEvidence(body, {
921
+ * ...common,
922
+ * // called with the SEALED bytes, never the plaintext
923
+ * upload: async (sealed) => {
924
+ * await myBucket.put(key, sealed);
925
+ * return `s3+https://cdn.example.com/${key}`;
926
+ * },
927
+ * });
928
+ * ```
929
+ *
930
+ * Either way the seller keeps custody of nothing it did not already have: the
931
+ * facilitator cannot read a `direct`-mode envelope in the hosted case either.
932
+ * What changes is durability and cost, which become yours.
870
933
  */
871
934
 
872
935
  /** `0x` + 40 hex. An ed25519 payee (Solana, Stellar) never matches. */
@@ -905,14 +968,20 @@ function chainIdFor(network: string): number | undefined {
905
968
  * identical, the ed25519 form was refused (`409 dx402_already_anchored`) and the
906
969
  * EVM form superseded the provisional.
907
970
  *
908
- * `pointer` stays empty on both branches: this call sends `sealed`, so the
909
- * facilitator issues the pointer and you cannot sign what you have not seen.
971
+ * `pointer` defaults to the empty string, which is right when you send `sealed`:
972
+ * the facilitator issues the pointer and you cannot sign what you have not seen.
973
+ * When you supply your OWN pointer it must be passed here **verbatim** -- the
974
+ * facilitator verifies against `req.pointer` when one is present and against
975
+ * `""` when it is absent (x402-rs `dx402/service.rs`, `signed_pointer`), so
976
+ * signing the empty string alongside a pointer produces a signature that never
977
+ * verifies and an anchor that silently stays provisional.
910
978
  */
911
979
  export function sellerDigestFor(
912
980
  paymentId: string,
913
981
  contentHash: string,
914
982
  payee: string,
915
983
  network: string,
984
+ pointer = '',
916
985
  ): Uint8Array | undefined {
917
986
  if (isEvmAddress(payee)) {
918
987
  const chainId = chainIdFor(network);
@@ -922,20 +991,19 @@ export function sellerDigestFor(
922
991
  // with no error anywhere. Refuse instead -- unsigned is honest and
923
992
  // recoverable, signed-but-worthless only looks done.
924
993
  if (!chainId) return undefined;
925
- return anchorDigest(paymentId, contentHash, '', payee, chainId);
994
+ return anchorDigest(paymentId, contentHash, pointer, payee, chainId);
926
995
  }
927
- return anchorDigest(paymentId, contentHash, '', ZERO_ADDRESS, 0);
996
+ return anchorDigest(paymentId, contentHash, pointer, ZERO_ADDRESS, 0);
928
997
  }
929
998
 
930
999
 
931
1000
  /**
932
1001
  * Largest `POST /dx402/anchor` request the facilitator accepts, mirroring its
933
1002
  * `MAX_REQUEST_BODY_BYTES` (default 64 KiB, an anti-OOM bound on every route).
934
- * After base64 inflation and ~600 bytes of metadata this leaves ~47 KB of
935
- * plaintext.
936
1003
  */
937
1004
  export const ANCHOR_MAX_REQUEST_BYTES = 64 * 1024;
938
1005
 
1006
+
939
1007
  /** base64 without spreading the array into arguments -- a large blob would
940
1008
  * otherwise overflow the call stack and surface as a generic failure. */
941
1009
  function toBase64(bytes: Uint8Array): string {
@@ -947,6 +1015,19 @@ function toBase64(bytes: Uint8Array): string {
947
1015
  return btoa(out);
948
1016
  }
949
1017
 
1018
+ /**
1019
+ * Which storage family a pointer names, for the anchor's `backend` field.
1020
+ *
1021
+ * The facilitator records this; it does not fetch through it. `s3` is the
1022
+ * fallback because `s3+https://` is the SDK's own scheme for "an ordinary HTTPS
1023
+ * URL", which is what most sellers' own sinks are.
1024
+ */
1025
+ function backendForPointer(pointer: string): 's3' | 'ipfs' | 'arweave' {
1026
+ if (pointer.startsWith('ipfs://')) return 'ipfs';
1027
+ if (pointer.startsWith('ar://')) return 'arweave';
1028
+ return 's3';
1029
+ }
1030
+
950
1031
  export async function anchorEvidence(
951
1032
  body: Uint8Array,
952
1033
  opts: AnchorOptions,
@@ -961,14 +1042,45 @@ export async function anchorEvidence(
961
1042
  const blob = sealEvidenceTo(body, recipients, opts.paymentId);
962
1043
  const hash = contentHash(body);
963
1044
 
1045
+ // Bring-your-own-storage. The sealing above is identical either way -- the
1046
+ // buyer must be able to decrypt -- so all that changes is who holds the
1047
+ // ciphertext and, therefore, whether it has to travel in this request.
1048
+ //
1049
+ // The upload is fenced off completely: a seller's bucket going down is not
1050
+ // a reason for a paid response to fail, so anything thrown here becomes a
1051
+ // skip, exactly like an unreachable facilitator.
1052
+ let pointer: string | undefined;
1053
+ if (opts.upload) {
1054
+ try {
1055
+ pointer = await opts.upload(blob);
1056
+ } catch {
1057
+ return { v: 1, skipped: 'anchor_failed', stage: 'upload' };
1058
+ }
1059
+ if (typeof pointer !== 'string' || pointer.trim() === '') {
1060
+ // An empty pointer addresses nothing, and the facilitator would record
1061
+ // an anchor that dereferences to a 404 forever. Worse than no anchor.
1062
+ return { v: 1, skipped: 'anchor_failed', stage: 'upload' };
1063
+ }
1064
+ pointer = pointer.trim();
1065
+ }
1066
+
964
1067
  const payload: Record<string, unknown> = {
965
1068
  paymentId: opts.paymentId,
966
1069
  network: opts.network,
967
1070
  txHash: opts.txHash,
968
1071
  payer: opts.payer,
969
1072
  payee: opts.payee,
970
- sealed: toBase64(blob),
971
- backend: 's3',
1073
+ // Exactly one of these. The facilitator dispatches on their presence:
1074
+ // `sealed` -> it hosts and derives the pointer; `pointer` alone -> it uses
1075
+ // yours; neither -> error (x402-rs `dx402/service.rs`).
1076
+ ...(pointer !== undefined ? { pointer } : { sealed: toBase64(blob) }),
1077
+ // Declared, not measured. Since x402-rs 2.3.0 the facilitator records
1078
+ // the store that ACTUALLY took the bytes and returns that, so a response
1079
+ // may name a different backend than the request did -- `ipfs` where you
1080
+ // said `s3`, because a deployment whose primary is Pinata wrote there.
1081
+ // That is the facilitator correcting the record, not a mismatch to
1082
+ // assert on.
1083
+ backend: opts.backend ?? (pointer !== undefined ? backendForPointer(pointer) : 's3'),
972
1084
  contentHash: hash,
973
1085
  keyAlg: opts.payerKey.length === 32 ? 'ECIES-X25519' : 'ECIES-secp256k1',
974
1086
  mode: 'direct',
@@ -985,7 +1097,11 @@ export async function anchorEvidence(
985
1097
  }
986
1098
 
987
1099
  if (opts.sign) {
988
- const digest = sellerDigestFor(opts.paymentId, hash, opts.payee, opts.network);
1100
+ // The signature covers the pointer the facilitator will verify against:
1101
+ // ours when we supply one, the empty string when the facilitator issues
1102
+ // it. Signing the wrong one throws nothing and leaves the anchor
1103
+ // provisional -- which is the state anyone can supersede.
1104
+ const digest = sellerDigestFor(opts.paymentId, hash, opts.payee, opts.network, pointer ?? '');
989
1105
  if (digest === undefined) {
990
1106
  unsigned = 'unknown_chain_id';
991
1107
  } else {
@@ -999,8 +1115,12 @@ export async function anchorEvidence(
999
1115
  // facilitator then rejects, arriving as a generic failure long after the
1000
1116
  // sealing work was done. Measured by KarmaKadabra, 2026-08-19: 47 KB of
1001
1117
  // plaintext fits, 48 KB does not.
1118
+ //
1119
+ // In `upload` mode the ciphertext is not in the request at all, so this
1120
+ // bound says nothing about the body and is not applied. The request is a
1121
+ // pointer and some metadata; only a pathological pointer could approach it.
1002
1122
  const wire = JSON.stringify(payload);
1003
- if (new TextEncoder().encode(wire).length > ANCHOR_MAX_REQUEST_BYTES) {
1123
+ if (pointer === undefined && new TextEncoder().encode(wire).length > ANCHOR_MAX_REQUEST_BYTES) {
1004
1124
  return { v: 1, skipped: 'too_large' };
1005
1125
  }
1006
1126
 
package/src/index.ts CHANGED
@@ -379,6 +379,19 @@ export {
379
379
  getCorsHeaders,
380
380
  X402_CORS_HEADERS,
381
381
  X402_HEADER_NAMES,
382
+ // Reading a facilitator refusal as data. A 503 is "no verdict", not a
383
+ // rejected payment: re-signing on one charges the buyer twice.
384
+ MAX_RETRY_AFTER_SECONDS,
385
+ DEFAULT_RETRY_AFTER_SECONDS,
386
+ DEFAULT_FACILITATOR_RETRIES,
387
+ WRITER_LEASE_REASONS,
388
+ REPLAYABLE_LEASE_REASONS,
389
+ AMBIGUOUS_LEASE_REASONS,
390
+ isReplayableLeaseReason,
391
+ isAmbiguousLeaseReason,
392
+ parseRetryAfterSeconds,
393
+ readFacilitatorError,
394
+ facilitatorFetch,
382
395
  } from './backend';
383
396
  export type {
384
397
  ResourceInfoV2,
@@ -391,4 +404,8 @@ export type {
391
404
  PaymentAcceptance,
392
405
  PaymentMiddlewareOptions,
393
406
  VerifiedPaymentState,
407
+ FacilitatorErrorInfo,
408
+ FacilitatorFailureFields,
409
+ FacilitatorFetchOptions,
410
+ WriterLeaseReason,
394
411
  } from './backend';