@mysten-incubation/suipay-buyer 0.3.0-dev.17 → 0.3.0-dev.18

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 (2) hide show
  1. package/dist/index.js +402 -24
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -4681,12 +4681,6 @@ import { fromBase64 as fromBase645, toBase64 as toBase643 } from "@mysten/sui/ut
4681
4681
 
4682
4682
  // ../sdk/dist/protocol/auth-params.js
4683
4683
  var TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
4684
- function formatAuthParams(params) {
4685
- return Object.entries(params).map(([k, v]) => `${k}=${TOKEN.test(v) ? v : quote(v)}`).join(", ");
4686
- }
4687
- function quote(value) {
4688
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
4689
- }
4690
4684
  function parseAuthHeader(header) {
4691
4685
  const trimmed = header.trim();
4692
4686
  const firstSpace = trimmed.indexOf(" ");
@@ -4765,6 +4759,19 @@ function bytesToBase64Url(bytes) {
4765
4759
  const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
4766
4760
  return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
4767
4761
  }
4762
+ function bytesFromBase64Url(s) {
4763
+ const normalized = s.replace(/-/g, "+").replace(/_/g, "/");
4764
+ const pad = (4 - normalized.length % 4) % 4;
4765
+ const base64 = normalized + "=".repeat(pad);
4766
+ if (typeof globalThis.atob === "function") {
4767
+ const binary = globalThis.atob(base64);
4768
+ const out = new Uint8Array(binary.length);
4769
+ for (let i = 0; i < binary.length; i++)
4770
+ out[i] = binary.charCodeAt(i);
4771
+ return out;
4772
+ }
4773
+ return Uint8Array.from(Buffer.from(base64, "base64"));
4774
+ }
4768
4775
 
4769
4776
  // ../sdk/dist/protocol/challenge.js
4770
4777
  import { Ed25519PublicKey } from "@mysten/sui/keypairs/ed25519";
@@ -5109,9 +5116,220 @@ function offerToBase64Url(offer) {
5109
5116
  }
5110
5117
  var MPP_SCHEME = "Payment";
5111
5118
  var MPP_METHOD = "sui.charge";
5119
+ var MPP_SUI_METHOD = "sui";
5120
+ var MPP_CHARGE_INTENT = "charge";
5121
+ var MPP_RECEIPT_STATUS = "success";
5122
+ var LEGACY_RECEIPT_STATUS = "settled";
5112
5123
  var MPP_CHALLENGE_HEADER = "WWW-Authenticate";
5113
5124
  var MPP_CREDENTIAL_HEADER = "Authorization";
5114
5125
  var MPP_RECEIPT_HEADER = "Payment-Receipt";
5126
+ var HEADER_TEXT_REPLACEMENTS = {
5127
+ "\u2264": "<=",
5128
+ // ≤ less-than-or-equal
5129
+ "\u2265": ">=",
5130
+ // ≥ greater-than-or-equal
5131
+ "\u2014": "-",
5132
+ // — em dash
5133
+ "\u2013": "-",
5134
+ // – en dash
5135
+ "\u2018": "'",
5136
+ // ' left single quote
5137
+ "\u2019": "'",
5138
+ // ' right single quote
5139
+ "\u201C": '"',
5140
+ // " left double quote
5141
+ "\u201D": '"'
5142
+ // " right double quote
5143
+ };
5144
+ function latin1HeaderText(value) {
5145
+ let out = "";
5146
+ for (const ch of value) {
5147
+ const mapped = HEADER_TEXT_REPLACEMENTS[ch];
5148
+ if (mapped !== void 0)
5149
+ out += mapped;
5150
+ else if (ch.codePointAt(0) > 255)
5151
+ out += "?";
5152
+ else
5153
+ out += ch;
5154
+ }
5155
+ return out;
5156
+ }
5157
+ var DAY_MS = 864e5;
5158
+ function billingPeriod(periodMs) {
5159
+ if (!Number.isInteger(periodMs) || periodMs < DAY_MS || periodMs % DAY_MS !== 0)
5160
+ return null;
5161
+ const days = periodMs / DAY_MS;
5162
+ if (days % 7 === 0)
5163
+ return { periodCount: String(days / 7), periodUnit: "week" };
5164
+ return { periodCount: String(days), periodUnit: "day" };
5165
+ }
5166
+ function billingPeriodMs(unit, count) {
5167
+ if (!Number.isInteger(count) || count <= 0)
5168
+ return null;
5169
+ if (unit === "day")
5170
+ return count * DAY_MS;
5171
+ if (unit === "week")
5172
+ return count * 7 * DAY_MS;
5173
+ return null;
5174
+ }
5175
+ function expiresWire(offer) {
5176
+ if (typeof offer.expiresAt !== "number" || !Number.isFinite(offer.expiresAt))
5177
+ return void 0;
5178
+ return new Date(offer.expiresAt).toISOString();
5179
+ }
5180
+ function flatParams(offer) {
5181
+ const params = {
5182
+ amount: offer.amount,
5183
+ asset: offer.asset,
5184
+ network: offer.network,
5185
+ recipient: offer.payTo,
5186
+ package: offer.packageId,
5187
+ resource: offer.resource,
5188
+ digest: offer.digest
5189
+ };
5190
+ if (typeof offer.decimals === "number")
5191
+ params.decimals = String(offer.decimals);
5192
+ if (typeof offer.description === "string") {
5193
+ params.description = latin1HeaderText(offer.description);
5194
+ }
5195
+ if (typeof offer.issuedAt === "number" && Number.isFinite(offer.issuedAt)) {
5196
+ params.issued = new Date(offer.issuedAt).toISOString();
5197
+ }
5198
+ if (typeof offer.expiresAt === "number" && Number.isFinite(offer.expiresAt)) {
5199
+ params.expires = new Date(offer.expiresAt).toISOString();
5200
+ }
5201
+ if (offer.netAmount !== void 0)
5202
+ params.net_amount = offer.netAmount;
5203
+ if (offer.platformFee !== void 0)
5204
+ params.platform_fee = offer.platformFee;
5205
+ if (offer.digestVersion !== void 0)
5206
+ params.digest_version = String(offer.digestVersion);
5207
+ if (offer.settlementRail !== void 0)
5208
+ params.settlement_rail = offer.settlementRail;
5209
+ if (offer.serviceId !== void 0)
5210
+ params.service_id = offer.serviceId;
5211
+ if (offer.serviceRevision !== void 0) {
5212
+ params.service_revision = String(offer.serviceRevision);
5213
+ }
5214
+ if (offer.targetHash !== void 0)
5215
+ params.target_hash = offer.targetHash;
5216
+ if (offer.authorizationEpoch !== void 0) {
5217
+ params.authorization_epoch = String(offer.authorizationEpoch);
5218
+ }
5219
+ if (offer.method !== void 0)
5220
+ params.http_method = offer.method;
5221
+ if (offer.path !== void 0)
5222
+ params.http_path = offer.path;
5223
+ if (offer.bodyHash !== void 0)
5224
+ params.body_hash = offer.bodyHash;
5225
+ if (offer.contentType !== void 0)
5226
+ params.content_type = offer.contentType;
5227
+ if (offer.intent !== void 0)
5228
+ params.intent = offer.intent;
5229
+ if (offer.periodMs !== void 0)
5230
+ params.period_ms = String(offer.periodMs);
5231
+ if (offer.periodCount !== void 0)
5232
+ params.period_count = String(offer.periodCount);
5233
+ if (offer.refundable !== void 0)
5234
+ params.refundable = offer.refundable ? "true" : "false";
5235
+ if (offer.refundWindowMs !== void 0) {
5236
+ params.refund_window_ms = String(offer.refundWindowMs);
5237
+ }
5238
+ if (offer.decideWindowMs !== void 0) {
5239
+ params.decide_window_ms = String(offer.decideWindowMs);
5240
+ }
5241
+ if (offer.chainId !== void 0)
5242
+ params.chain_id = String(offer.chainId);
5243
+ if (offer.paymentSalt !== void 0)
5244
+ params.payment_salt = offer.paymentSalt;
5245
+ if (offer.refundConfigId !== void 0)
5246
+ params.refund_config_id = offer.refundConfigId;
5247
+ if (offer.refundTo !== void 0)
5248
+ params.refund_to = offer.refundTo;
5249
+ if (offer.sponsorGasOwner !== void 0) {
5250
+ params.sponsor_gas_owner = offer.sponsorGasOwner;
5251
+ }
5252
+ if (offer.sponsorGasBudget !== void 0) {
5253
+ params.sponsor_gas_budget = offer.sponsorGasBudget;
5254
+ }
5255
+ if (offer.sponsorGasPrice !== void 0) {
5256
+ params.sponsor_gas_price = offer.sponsorGasPrice;
5257
+ }
5258
+ if (offer.sponsorGasPayment !== void 0) {
5259
+ params.sponsor_gas_payment = offer.sponsorGasPayment;
5260
+ }
5261
+ if (offer.acceptedRails !== void 0) {
5262
+ params.accepted_rails = offer.acceptedRails.join(",");
5263
+ }
5264
+ if (offer.exclusionProtocolVersion !== void 0) {
5265
+ params.exclusion_protocol_version = String(offer.exclusionProtocolVersion);
5266
+ }
5267
+ if (offer.registryIdentity !== void 0) {
5268
+ params.registry_identity = offer.registryIdentity;
5269
+ }
5270
+ if (offer.sig !== void 0)
5271
+ params.sig = offer.sig;
5272
+ if (offer.sigKid !== void 0)
5273
+ params.sig_kid = offer.sigKid;
5274
+ return params;
5275
+ }
5276
+ function legacyRequestBlob(offer, copies = false) {
5277
+ const params = flatParams(offer);
5278
+ if (copies) {
5279
+ params.method = MPP_SUI_METHOD;
5280
+ params.realm = "suipay";
5281
+ params.challenge = offer.challengeId;
5282
+ if (typeof offer.mimeType === "string")
5283
+ params.type = offer.mimeType;
5284
+ }
5285
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJson(params)));
5286
+ }
5287
+ function requestBlob(offer) {
5288
+ const flat = flatParams(offer);
5289
+ const details = { ...flat };
5290
+ delete details.amount;
5291
+ delete details.asset;
5292
+ delete details.recipient;
5293
+ delete details.description;
5294
+ delete details.expires;
5295
+ const body = {
5296
+ amount: flat.amount,
5297
+ currency: flat.asset,
5298
+ methodDetails: details
5299
+ };
5300
+ if (flat.recipient !== void 0)
5301
+ body.recipient = flat.recipient;
5302
+ if (flat.description !== void 0)
5303
+ body.description = flat.description;
5304
+ if (wireIntent(offer) === "subscription") {
5305
+ delete details.period_ms;
5306
+ const periodMs = offer.periodMs;
5307
+ const billing = typeof periodMs === "number" ? billingPeriod(periodMs) : null;
5308
+ if (!billing) {
5309
+ throw new Error("subscription periodMs is not an exact number of days");
5310
+ }
5311
+ body.periodCount = billing.periodCount;
5312
+ body.periodUnit = billing.periodUnit;
5313
+ const periodCount = offer.periodCount;
5314
+ const issuedAt = offer.issuedAt;
5315
+ if (typeof periodMs === "number" && typeof periodCount === "number" && typeof issuedAt === "number" && Number.isSafeInteger(periodMs) && Number.isSafeInteger(periodCount) && Number.isSafeInteger(issuedAt) && Number.isSafeInteger(periodMs * periodCount)) {
5316
+ const end = issuedAt + periodMs * periodCount;
5317
+ if (Number.isSafeInteger(end))
5318
+ body.subscriptionExpires = new Date(end).toISOString();
5319
+ }
5320
+ }
5321
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)));
5322
+ }
5323
+ function issuedRequestBlob(offer) {
5324
+ return requestBlob(offer);
5325
+ }
5326
+ function echoedRequestBlob(offer) {
5327
+ try {
5328
+ return issuedRequestBlob(offer);
5329
+ } catch {
5330
+ return legacyRequestBlob(offer);
5331
+ }
5332
+ }
5115
5333
  function splitChallenges(header) {
5116
5334
  const scheme = `${MPP_SCHEME} `;
5117
5335
  const value = header.trim();
@@ -5171,11 +5389,120 @@ function decodeChallenge(header, opts) {
5171
5389
  }
5172
5390
  return null;
5173
5391
  }
5392
+ function canonicalJson(fields) {
5393
+ const keys = Object.keys(fields).sort();
5394
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${JSON.stringify(fields[key])}`).join(",")}}`;
5395
+ }
5396
+ function canonicalJsonValue(value) {
5397
+ if (value === null || typeof value !== "object")
5398
+ return JSON.stringify(value);
5399
+ if (Array.isArray(value))
5400
+ return `[${value.map(canonicalJsonValue).join(",")}]`;
5401
+ const fields = value;
5402
+ const keys = Object.keys(fields).sort();
5403
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJsonValue(fields[key])}`).join(",")}}`;
5404
+ }
5405
+ function wireIntent(offer) {
5406
+ return offer.intent === "subscription" ? "subscription" : MPP_CHARGE_INTENT;
5407
+ }
5408
+ var REQUEST_TOP_LEVEL = /* @__PURE__ */ new Set([
5409
+ "amount",
5410
+ "asset",
5411
+ "currency",
5412
+ "description",
5413
+ "externalId",
5414
+ "recipient",
5415
+ "subscriptionExpires"
5416
+ ]);
5417
+ function takeStrings(source, into) {
5418
+ for (const [key, value] of Object.entries(source)) {
5419
+ if (typeof value !== "string")
5420
+ return false;
5421
+ into[key] = value;
5422
+ }
5423
+ return true;
5424
+ }
5425
+ function officialParams(params) {
5426
+ if (params.method !== MPP_SUI_METHOD || !params.request)
5427
+ return null;
5428
+ if (params.intent !== MPP_CHARGE_INTENT && params.intent !== "subscription")
5429
+ return null;
5430
+ let body;
5431
+ try {
5432
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(params.request)));
5433
+ } catch {
5434
+ return null;
5435
+ }
5436
+ if (!body || typeof body !== "object" || Array.isArray(body))
5437
+ return null;
5438
+ const record = body;
5439
+ const fields = {};
5440
+ const details = record.methodDetails;
5441
+ if (details !== void 0) {
5442
+ if (!details || typeof details !== "object" || Array.isArray(details))
5443
+ return null;
5444
+ if (!takeStrings(details, fields))
5445
+ return null;
5446
+ for (const [key, value] of Object.entries(record)) {
5447
+ if (key === "methodDetails" || key === "periodCount" || key === "periodUnit")
5448
+ continue;
5449
+ if (typeof value !== "string" || !REQUEST_TOP_LEVEL.has(key))
5450
+ return null;
5451
+ if (fields[key] !== void 0 && fields[key] !== value)
5452
+ return null;
5453
+ fields[key] = value;
5454
+ }
5455
+ const periodCount = record.periodCount;
5456
+ const periodUnit = record.periodUnit;
5457
+ if (periodCount !== void 0 || periodUnit !== void 0) {
5458
+ if (typeof periodCount !== "string" || typeof periodUnit !== "string")
5459
+ return null;
5460
+ if (!/^[1-9]\d*$/.test(periodCount))
5461
+ return null;
5462
+ const ms = billingPeriodMs(periodUnit, Number(periodCount));
5463
+ if (ms === null)
5464
+ return null;
5465
+ if (fields.period_ms !== void 0 && fields.period_ms !== String(ms))
5466
+ return null;
5467
+ fields.period_ms = String(ms);
5468
+ }
5469
+ if (params.intent === "subscription" && fields.period_ms === void 0)
5470
+ return null;
5471
+ } else if (!takeStrings(record, fields)) {
5472
+ return null;
5473
+ }
5474
+ if (fields.currency !== void 0) {
5475
+ if (fields.asset !== void 0 && fields.asset !== fields.currency)
5476
+ return null;
5477
+ fields.asset = fields.currency;
5478
+ }
5479
+ if (params.expires !== void 0) {
5480
+ if (fields.expires !== void 0 && fields.expires !== params.expires)
5481
+ return null;
5482
+ if (fields.expires === void 0)
5483
+ fields.expires = params.expires;
5484
+ }
5485
+ if (!fields.challenge && params.id)
5486
+ fields.challenge = params.id;
5487
+ if (fields.method === void 0)
5488
+ fields.method = MPP_SUI_METHOD;
5489
+ if (fields.method !== MPP_METHOD && fields.method !== MPP_SUI_METHOD)
5490
+ return null;
5491
+ if (fields.intent !== void 0 && fields.intent !== params.intent)
5492
+ return null;
5493
+ if (fields.intent === void 0 && params.intent === "subscription")
5494
+ return null;
5495
+ fields.method = MPP_METHOD;
5496
+ return fields;
5497
+ }
5174
5498
  function decodeSingleChallenge(header) {
5175
5499
  const parsed = parseAuthHeader(header);
5176
5500
  if (!parsed || parsed.scheme !== MPP_SCHEME)
5177
5501
  return null;
5178
- const p = parsed.params;
5502
+ const pinned = officialParams(parsed.params);
5503
+ const p = { ...pinned ?? parsed.params };
5504
+ if (p.method === MPP_SUI_METHOD)
5505
+ p.method = MPP_METHOD;
5179
5506
  if (p.method !== MPP_METHOD)
5180
5507
  return null;
5181
5508
  const required = [
@@ -5260,13 +5587,15 @@ function decodeSingleChallenge(header) {
5260
5587
  offer.intent = p.intent;
5261
5588
  if (p.period_ms !== void 0) {
5262
5589
  const ms = Number(p.period_ms);
5263
- if (Number.isFinite(ms))
5264
- offer.periodMs = ms;
5590
+ if (!Number.isSafeInteger(ms) || ms <= 0)
5591
+ return null;
5592
+ offer.periodMs = ms;
5265
5593
  }
5266
5594
  if (p.period_count !== void 0) {
5267
5595
  const count = Number(p.period_count);
5268
- if (Number.isFinite(count))
5269
- offer.periodCount = count;
5596
+ if (!Number.isSafeInteger(count) || count <= 0)
5597
+ return null;
5598
+ offer.periodCount = count;
5270
5599
  }
5271
5600
  if (p.refundable === "true")
5272
5601
  offer.refundable = true;
@@ -5326,25 +5655,46 @@ function decodeSingleChallenge(header) {
5326
5655
  offer.sigKid = p.sig_kid;
5327
5656
  return offer;
5328
5657
  }
5658
+ function echoedChallenge(offer, challengeId) {
5659
+ const challenge = {
5660
+ id: challengeId,
5661
+ realm: "suipay",
5662
+ method: MPP_SUI_METHOD,
5663
+ intent: wireIntent(offer),
5664
+ // Section 5.2 echoes the original challenge, including its request.
5665
+ request: echoedRequestBlob(offer)
5666
+ };
5667
+ const expires = expiresWire(offer);
5668
+ if (expires !== void 0)
5669
+ challenge.expires = expires;
5670
+ return challenge;
5671
+ }
5672
+ function encodeOfficialMessage(body) {
5673
+ return `${MPP_SCHEME} ${bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)))}`;
5674
+ }
5329
5675
  function encodeProof(proof) {
5330
- return `${MPP_SCHEME} ${formatAuthParams({
5331
- method: MPP_METHOD,
5332
- challenge: proof.challengeId,
5333
- payer: proof.payer,
5334
- offer: offerToBase64Url(proof.offer),
5335
- digest: proof.txDigest
5336
- })}`;
5676
+ return encodeOfficialMessage({
5677
+ challenge: echoedChallenge(proof.offer, proof.challengeId),
5678
+ payload: {
5679
+ payer: proof.payer,
5680
+ offer: offerToBase64Url(proof.offer),
5681
+ digest: proof.txDigest
5682
+ }
5683
+ });
5337
5684
  }
5338
- function decodeReceipt(header) {
5339
- const parsed = parseAuthHeader(`X ${header}`);
5340
- if (!parsed)
5685
+ function receiptFromParams(p) {
5686
+ if (p.method !== MPP_METHOD && p.method !== MPP_SUI_METHOD)
5687
+ return null;
5688
+ if (p.status !== MPP_RECEIPT_STATUS && p.status !== LEGACY_RECEIPT_STATUS)
5341
5689
  return null;
5342
- const p = parsed.params;
5343
- if (!p.challenge || !p.tx_digest || !p.payer || !p.amount || !p.asset || !p.network)
5690
+ if (p.tx_digest && p.reference && p.tx_digest !== p.reference)
5691
+ return null;
5692
+ const txDigest = p.tx_digest || p.reference;
5693
+ if (!p.challenge || !txDigest || !p.payer || !p.amount || !p.asset || !p.network)
5344
5694
  return null;
5345
5695
  const receipt = {
5346
5696
  challengeId: p.challenge,
5347
- txDigest: p.tx_digest,
5697
+ txDigest,
5348
5698
  network: p.network,
5349
5699
  payer: p.payer,
5350
5700
  amount: p.amount,
@@ -5365,6 +5715,34 @@ function decodeReceipt(header) {
5365
5715
  receipt.periodIndex = p.period_index;
5366
5716
  return receipt;
5367
5717
  }
5718
+ function decodeOfficialReceipt(header) {
5719
+ const token = header.trim();
5720
+ if (!/^[A-Za-z0-9_-]+$/.test(token))
5721
+ return null;
5722
+ let body;
5723
+ try {
5724
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(token)));
5725
+ } catch {
5726
+ return null;
5727
+ }
5728
+ if (!body || typeof body !== "object" || Array.isArray(body))
5729
+ return null;
5730
+ const fields = {};
5731
+ for (const [key, value] of Object.entries(body)) {
5732
+ if (typeof value !== "string")
5733
+ return null;
5734
+ fields[key] = value;
5735
+ }
5736
+ return receiptFromParams(fields);
5737
+ }
5738
+ function decodeReceipt(header) {
5739
+ if (/^[A-Za-z0-9_-]+$/.test(header.trim()))
5740
+ return decodeOfficialReceipt(header);
5741
+ const parsed = parseAuthHeader(`X ${header}`);
5742
+ if (!parsed)
5743
+ return null;
5744
+ return receiptFromParams(parsed.params);
5745
+ }
5368
5746
 
5369
5747
  // ../sdk/dist/protocol/x402.js
5370
5748
  import { fromBase64 as fromBase644, toBase64 as toBase642 } from "@mysten/sui/utils";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mysten-incubation/suipay-buyer",
3
- "version": "0.3.0-dev.17",
3
+ "version": "0.3.0-dev.18",
4
4
  "type": "module",
5
5
  "description": "SuiPay buyer SDK — delegated spend-account pay plus a typed /v1 control-plane client.",
6
6
  "license": "MIT",