@ixo/action-protocol 0.5.0 → 0.7.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/index.js CHANGED
@@ -9,6 +9,8 @@ const HEX = /^[a-f0-9]{64}$/;
9
9
  const ADDRESS = /^ixo1[023456789acdefghjklmnpqrstuvwxyz]{38,59}$/;
10
10
  const INT = /^(0|[1-9][0-9]*)$/;
11
11
  const FIELD = /^[a-z][a-z0-9_]{0,39}$/;
12
+ /** 0.7.0 application and claim cards: an existing collection (never 0). */
13
+ const SUBMISSION_COLLECTION_ID = /^[1-9][0-9]{0,19}$/;
12
14
  /** Envelope tags. v1 carries only the 0.1 status/receipt set; v2 adds terminal non-execution outcomes. */
13
15
  export const OUTCOME_VERSION_V1 = "ixo.auth-outcome/1";
14
16
  export const OUTCOME_VERSION_V2 = "ixo.auth-outcome/2";
@@ -102,7 +104,14 @@ export async function digestOf(value) {
102
104
 
103
105
  export function parseOperation(input) {
104
106
  const op = object(input, "operation");
107
+ // 0.6.0: field-level errors first (`Invalid messages[1].toAddress`), then
108
+ // the JSON schema as a backstop.
109
+ if (op.kind === CHAIN_TX_KIND) {
110
+ const field = chainTxField(op);
111
+ if (field) fail(field);
112
+ }
105
113
  validateOperationSchema(op);
114
+ if (op.kind === CHAIN_TX_KIND) return op;
106
115
  if (op.kind === "statement.sign.v1") {
107
116
  utf8(op.statement, "statement");
108
117
  return op;
@@ -223,6 +232,24 @@ export function parseOperation(input) {
223
232
  if (new TextEncoder().encode(op.memo).length > MEMO_BYTES) fail("memo");
224
233
  return op.denom === undefined ? { ...op, denom: "uixo" } : op;
225
234
  }
235
+ if (op.kind === "ixo.bid.submit.v1" || op.kind === "ixo.claim.submit.v1") {
236
+ // Shape is checked by the schema; here the parts a schema cannot say.
237
+ jsonObject(op.data, "data");
238
+ // The card shows exactly what is sent and signed.
239
+ const issue = submissionSummaryIssue(op);
240
+ if (issue) fail(issue);
241
+ if (op.kind === "ixo.claim.submit.v1") {
242
+ const files = new Set();
243
+ for (const item of op.evidence) {
244
+ const url = new URL(item.url);
245
+ if (url.protocol !== "https:" || url.username || url.password || url.hash)
246
+ fail("evidence.url");
247
+ if (files.has(item.url)) fail("duplicate evidence");
248
+ files.add(item.url);
249
+ }
250
+ }
251
+ return op;
252
+ }
226
253
  if (op.kind === "resource.read.v1") {
227
254
  exact(
228
255
  op,
@@ -304,6 +331,7 @@ export function assertHubReferenceUrl(input, configuredOrigin) {
304
331
  export function parseReceipt(input) {
305
332
  const receipt = object(input, "receipt");
306
333
  if (p2ReceiptFields[receipt.kind]) return parseP2Receipt(receipt);
334
+ if (receipt.kind === CHAIN_TX_KIND) return parseChainTxReceipt(receipt);
307
335
  if (receipt.kind === "form.submission.v1") {
308
336
  exact(
309
337
  receipt,
@@ -371,6 +399,65 @@ export function parseReceipt(input) {
371
399
  }
372
400
  return receipt;
373
401
  }
402
+ if (receipt.kind === "ixo.bid.submission.v1") {
403
+ exact(
404
+ receipt,
405
+ ["kind", "actionId", "revision", "digest", "collectionId", "bidId", "submittedAt"],
406
+ "receipt",
407
+ );
408
+ tuple(receipt);
409
+ pattern(receipt.collectionId, SUBMISSION_COLLECTION_ID, "receipt.collectionId");
410
+ if (receipt.bidId !== null) str(receipt.bidId, "receipt.bidId", 1, 200);
411
+ num(receipt.submittedAt, "receipt.submittedAt");
412
+ return receipt;
413
+ }
414
+ if (receipt.kind === "ixo.claim.submission.v1") {
415
+ exact(
416
+ receipt,
417
+ [
418
+ "kind",
419
+ "actionId",
420
+ "revision",
421
+ "digest",
422
+ "collectionId",
423
+ "claimId",
424
+ "transactionHash",
425
+ "height",
426
+ "submittedAt",
427
+ ],
428
+ "receipt",
429
+ );
430
+ tuple(receipt);
431
+ pattern(receipt.collectionId, SUBMISSION_COLLECTION_ID, "receipt.collectionId");
432
+ str(receipt.claimId, "receipt.claimId", 1, 200);
433
+ pattern(receipt.transactionHash, HEX, "receipt.transactionHash");
434
+ // The block the claim's MsgExec(MsgSubmitClaim) was included in.
435
+ num(receipt.height, "receipt.height");
436
+ num(receipt.submittedAt, "receipt.submittedAt");
437
+ return receipt;
438
+ }
439
+ if (receipt.kind === "ixo.submission.failed.v1") {
440
+ exact(
441
+ receipt,
442
+ ["kind", "actionId", "revision", "digest", "step", "message", "detail", "failedAt"],
443
+ "receipt",
444
+ );
445
+ tuple(receipt);
446
+ if (!SUBMISSION_FAILURE_STEPS.includes(receipt.step)) fail("receipt.step");
447
+ // Plain words the Hub chose (never raw text): shown to the person and
448
+ // relayed by gateways and runtimes. Already in sanitized form.
449
+ if (sanitizeSubmissionText(str(receipt.message, "receipt.message", 1, 500)) !== receipt.message)
450
+ fail("receipt.message");
451
+ // Optional technical text, for the review page's closed disclosure only.
452
+ if (
453
+ "detail" in receipt &&
454
+ sanitizeSubmissionText(str(receipt.detail, "receipt.detail", 1, SUBMISSION_TEXT_MAX)) !==
455
+ receipt.detail
456
+ )
457
+ fail("receipt.detail");
458
+ num(receipt.failedAt, "receipt.failedAt");
459
+ return receipt;
460
+ }
374
461
  return fail("receipt.kind");
375
462
  }
376
463
 
@@ -395,10 +482,38 @@ export function parseReviewView(input) {
395
482
  "chatUrl",
396
483
  "service",
397
484
  "transfer",
485
+ "chainTx",
486
+ "networkFee",
487
+ "collectionName",
398
488
  ],
399
489
  "view",
400
490
  );
401
491
  parseReference(view.reference);
492
+ parseOperation(view.operation);
493
+ // 0.6.0: the Hub-computed chain transaction display (chain tx cards only).
494
+ if (view.chainTx !== undefined && view.chainTx !== null) {
495
+ if (view.operation?.kind !== CHAIN_TX_KIND) fail("view.chainTx");
496
+ const display = parseChainTxDisplay(view.chainTx);
497
+ if (
498
+ display.signer !== view.operation.signer ||
499
+ display.steps.length !== view.operation.messages.length ||
500
+ display.steps.some(
501
+ (step, i) => step.type !== view.operation.messages[i].type,
502
+ )
503
+ )
504
+ fail("view.chainTx");
505
+ }
506
+ // 0.7.0: who pays a claim's network fee, read once when the card was made.
507
+ if (view.networkFee !== undefined && view.networkFee !== null) {
508
+ if (view.operation?.kind !== "ixo.claim.submit.v1") fail("view.networkFee");
509
+ if (!SUBMISSION_NETWORK_FEES.includes(view.networkFee)) fail("view.networkFee");
510
+ }
511
+ // 0.7.0: the collection's name as the Hub read it when the card was made.
512
+ if (view.collectionName !== undefined && view.collectionName !== null) {
513
+ if (!SUBMISSION_KINDS.includes(view.operation?.kind)) fail("view.collectionName");
514
+ if (sanitizeSubmissionText(str(view.collectionName, "view.collectionName", 1, 120)) !== view.collectionName)
515
+ fail("view.collectionName");
516
+ }
402
517
  if (view.service !== undefined && view.service !== null) {
403
518
  object(view.service, "view.service");
404
519
  exact(
@@ -578,9 +693,21 @@ export function parseCapabilities(input) {
578
693
  "operations",
579
694
  "forms",
580
695
  "transfer",
696
+ "chainTx",
581
697
  ],
582
698
  "capabilities",
583
699
  );
700
+ // 0.6.0 (`?version=4`): what a chain transaction may carry. Required when
701
+ // the kind is listed; never present otherwise except as null.
702
+ if (data.chainTx !== undefined && data.chainTx !== null)
703
+ parseChainTxCapabilities(data.chainTx);
704
+ if (
705
+ Array.isArray(data.operations) &&
706
+ data.operations.includes(CHAIN_TX_KIND)
707
+ ? data.chainTx === undefined || data.chainTx === null
708
+ : data.chainTx !== undefined && data.chainTx !== null
709
+ )
710
+ fail("capabilities.chainTx");
584
711
  if (
585
712
  ![CAPABILITIES_VERSION_V1, CAPABILITIES_VERSION_V2].includes(data.version)
586
713
  )
@@ -703,6 +830,97 @@ export function parseCapabilities(input) {
703
830
  return data;
704
831
  }
705
832
 
833
+ /** 0.7.0: see index.d.ts. */
834
+ export function submissionDisplayValue(value) {
835
+ if (typeof value === "string") return value;
836
+ if (typeof value === "boolean") return String(value);
837
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : undefined;
838
+ if (value === null) return "";
839
+ if (
840
+ Array.isArray(value) &&
841
+ value.every((item) => ["string", "number", "boolean"].includes(typeof item))
842
+ ) {
843
+ const shown = value.map(submissionDisplayValue);
844
+ return shown.includes(undefined) ? undefined : shown.join(", ");
845
+ }
846
+ return undefined;
847
+ }
848
+ const plainObject = (value) =>
849
+ value !== null && typeof value === "object" && !Array.isArray(value);
850
+ /** The answers of `data`: path -> display form, or an issue string. */
851
+ function submissionAnswers(data) {
852
+ const answers = new Map();
853
+ const walk = (node, prefix) => {
854
+ for (const key of Object.keys(node)) {
855
+ if (key === "" || key.includes(".")) return `invalid_operation: data key ${JSON.stringify(key).slice(0, 60)}`;
856
+ const path = prefix ? `${prefix}.${key}` : key;
857
+ const value = node[key];
858
+ let issue = null;
859
+ if (plainObject(value)) issue = walk(value, path);
860
+ else if (Array.isArray(value) && value.length && value.every(plainObject)) {
861
+ for (const [index, item] of value.entries()) {
862
+ issue = walk(item, `${path}.${index}`);
863
+ if (issue) break;
864
+ }
865
+ } else {
866
+ const shown = submissionDisplayValue(value);
867
+ if (shown === undefined) return `invalid_operation: data.${path} has no display form`;
868
+ answers.set(path, shown);
869
+ }
870
+ if (issue) return issue;
871
+ }
872
+ return null;
873
+ };
874
+ const issue = walk(data, "");
875
+ return issue ?? answers;
876
+ }
877
+ /** The value at a dot path of `data` (objects by key, arrays by index), or undefined. */
878
+ function valueAt(data, path) {
879
+ let node = data;
880
+ for (const part of path.split(".")) {
881
+ if (Array.isArray(node) && /^\d+$/.test(part)) node = node[Number(part)];
882
+ else if (plainObject(node) && Object.prototype.hasOwnProperty.call(node, part)) node = node[part];
883
+ else return undefined;
884
+ }
885
+ return node;
886
+ }
887
+ /** 0.7.0: see index.d.ts. */
888
+ export function submissionSummaryIssue(op) {
889
+ let data;
890
+ try {
891
+ data = JSON.parse(op.data);
892
+ } catch {
893
+ return "invalid_operation: data";
894
+ }
895
+ if (!plainObject(data)) return "invalid_operation: data";
896
+ const answers = submissionAnswers(data);
897
+ if (typeof answers === "string") return answers;
898
+ const seen = new Set();
899
+ for (const [index, row] of (op.summary ?? []).entries()) {
900
+ if (seen.has(row.field)) return `invalid_operation: summary[${index}].field repeats`;
901
+ seen.add(row.field);
902
+ if (!answers.has(row.field)) return `invalid_operation: summary[${index}].field is not an answer`;
903
+ if (answers.get(row.field) !== row.value) return `invalid_operation: summary[${index}].value is not the answer`;
904
+ }
905
+ for (const path of answers.keys())
906
+ if (!seen.has(path)) return `invalid_operation: data.${path} has no summary row`;
907
+ if (op.kind === "ixo.claim.submit.v1")
908
+ for (const [index, item] of op.evidence.entries())
909
+ if (valueAt(data, item.field) !== undefined)
910
+ return `invalid_operation: evidence[${index}].field already holds an answer`;
911
+ return null;
912
+ }
913
+ /** 0.7.0: a string that must hold one JSON object (SurveyJS answers). */
914
+ const jsonObject = (value, field) => {
915
+ let parsed;
916
+ try {
917
+ parsed = JSON.parse(value);
918
+ } catch {
919
+ fail(field);
920
+ }
921
+ object(parsed, field);
922
+ return parsed;
923
+ };
706
924
  const utf8 = (value, field) => {
707
925
  str(value, field, 0, 8192);
708
926
  if (
@@ -777,7 +995,89 @@ const receiptKinds = {
777
995
  "calendar.event.create.v1": "calendar.event.created.v1",
778
996
  "vfs.access.request.v1": "vfs.access.requested.v1",
779
997
  "vfs.text.save.v1": "vfs.text.saved.v1",
998
+ "ixo.chain.tx.v1": "ixo.chain.tx.v1",
999
+ "ixo.bid.submit.v1": "ixo.bid.submission.v1",
1000
+ "ixo.claim.submit.v1": "ixo.claim.submission.v1",
780
1001
  };
1002
+ /** 0.7.0: kinds whose failed outcome carries `ixo.submission.failed.v1`. */
1003
+ const SUBMISSION_KINDS = ["ixo.bid.submit.v1", "ixo.claim.submit.v1"];
1004
+ /** 0.7.0: the step a bid or claim submission stopped at. */
1005
+ export const SUBMISSION_FAILURE_STEPS = [
1006
+ "collection",
1007
+ "evidence",
1008
+ "key",
1009
+ "bid_bot",
1010
+ "claim_bot",
1011
+ "chain",
1012
+ ];
1013
+ /**
1014
+ * 0.7.0: a claim card's network fee as read when the card was made: a
1015
+ * usable fee grant allowing MsgExec covers it, or the person's IXO balance
1016
+ * pays it (also when the grants could not be read).
1017
+ */
1018
+ export const SUBMISSION_NETWORK_FEES = ["covered", "balance"];
1019
+ /** 0.7.0: the longest failure `message` or `detail`, in UTF-16 units. */
1020
+ export const SUBMISSION_TEXT_MAX = 500;
1021
+ // Control characters (C0, DEL, C1, line/paragraph separators) become spaces.
1022
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/gu;
1023
+ // Invisible and direction-changing characters are dropped: zero-width
1024
+ // characters, bidi embeddings, overrides and isolates, word joiners and
1025
+ // invisible operators, variation selectors, the BOM, soft hyphen and the
1026
+ // Hangul and Mongolian fillers.
1027
+ const INVISIBLE_CHARACTERS =
1028
+ /[\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\u3164\ufe00-\ufe0f\ufeff\uffa0]/gu;
1029
+ // Anything a chat app or browser could turn into a link: a URL with a
1030
+ // scheme, a www. host, an email address, or a dotted host name ending in a
1031
+ // letters-only label (with an optional port and path). Every branch starts
1032
+ // at a word boundary and every repetition is bounded, so a match attempt
1033
+ // does a bounded amount of work at each position (no catastrophic
1034
+ // backtracking); the input is also cut to SANITIZE_INPUT_MAX first.
1035
+ const LINK_LIKE =
1036
+ /\b[a-z][a-z0-9+.-]{0,31}:\/\/\S{0,2048}|\bwww\.\S{0,2048}|\b[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{1,63}|\b(?:[a-z0-9-]{1,63}\.){1,16}[a-z]{2,63}\b(?::\d{1,5})?(?:\/\S{0,2048})?/giu;
1037
+ /** At most this much input is looked at (4 x SUBMISSION_TEXT_MAX). */
1038
+ const SANITIZE_INPUT_MAX = 2000;
1039
+ /**
1040
+ * 0.7.0: text safe to show as plain text: control characters become spaces,
1041
+ * invisible and bidi characters are dropped, anything link-like becomes
1042
+ * `[link]`, whitespace is collapsed and the result is cut to
1043
+ * SUBMISSION_TEXT_MAX (never inside a surrogate pair). The same text in
1044
+ * comes out unchanged, so a parser can check a value is already safe.
1045
+ */
1046
+ export function sanitizeSubmissionText(text) {
1047
+ // Bounded input before any expression runs; then unpaired surrogates (also
1048
+ // one the cut split) are dropped, so every pass sees well-formed text.
1049
+ let out = sanitizeOnce(String(text).slice(0, SANITIZE_INPUT_MAX));
1050
+ // A pass can only change the text again at its cut tail (a new link-like
1051
+ // tail, or a "[link]" pushed over the limit), so it settles within a few
1052
+ // passes; SANITIZE_PASSES is a hard bound. Should it ever not settle, the
1053
+ // empty string (itself stable) is returned: the result is ALWAYS a fixed
1054
+ // point, so sanitize(sanitize(x)) === sanitize(x) and a parser can check it.
1055
+ for (let pass = 0; pass < SANITIZE_PASSES; pass++) {
1056
+ const next = sanitizeOnce(out);
1057
+ if (next === out) return out;
1058
+ out = next;
1059
+ }
1060
+ return "";
1061
+ }
1062
+ const SANITIZE_PASSES = 8;
1063
+ // A high surrogate not followed by a low one, or a low one not after a high one.
1064
+ const UNPAIRED_SURROGATES = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
1065
+ function sanitizeOnce(text) {
1066
+ const cleaned = text
1067
+ .replace(UNPAIRED_SURROGATES, "")
1068
+ .replace(CONTROL_CHARACTERS, " ")
1069
+ .replace(INVISIBLE_CHARACTERS, "")
1070
+ .replace(LINK_LIKE, "[link]")
1071
+ .replace(/\s+/gu, " ")
1072
+ .trim();
1073
+ if (cleaned.length <= SUBMISSION_TEXT_MAX) return cleaned;
1074
+ let out = "";
1075
+ for (const point of cleaned) {
1076
+ if (out.length + point.length > SUBMISSION_TEXT_MAX) break;
1077
+ out += point;
1078
+ }
1079
+ return out.trimEnd();
1080
+ }
781
1081
  export function assertReceiptForOperation(
782
1082
  operation,
783
1083
  receipt,
@@ -795,11 +1095,33 @@ export function assertReceiptForOperation(
795
1095
  receipt.service === serviceForOperation(operation)
796
1096
  )
797
1097
  return receipt;
1098
+ if (
1099
+ status === "failed" &&
1100
+ receipt.kind === "ixo.submission.failed.v1" &&
1101
+ SUBMISSION_KINDS.includes(operation.kind)
1102
+ )
1103
+ return receipt;
798
1104
  if (
799
1105
  receiptKinds[operation.kind] !== receipt.kind ||
800
- receipt.kind === "service.failure.v1"
1106
+ receipt.kind === "service.failure.v1" ||
1107
+ receipt.kind === "ixo.submission.failed.v1"
801
1108
  )
802
1109
  fail("operation receipt");
1110
+ // 0.6.0: a chain tx receipt names the approved chain and steps, in order.
1111
+ if (
1112
+ operation.kind === CHAIN_TX_KIND &&
1113
+ (receipt.chainId !== operation.chainId ||
1114
+ receipt.steps.length !== operation.messages.length ||
1115
+ receipt.steps.some((step, i) => step.type !== operation.messages[i].type))
1116
+ )
1117
+ fail("receipt steps");
1118
+ // 0.7.0: an application or claim receipt names the approved collection.
1119
+ if (
1120
+ operation.kind !== CHAIN_TX_KIND &&
1121
+ "collectionId" in receipt &&
1122
+ receipt.collectionId !== operation.collectionId
1123
+ )
1124
+ fail("receipt collection");
803
1125
  // Every kind: the receipt must name the approved connection / target.
804
1126
  if (
805
1127
  "connectionId" in operation &&
@@ -1246,13 +1568,28 @@ function validCalendarInstant(value) {
1246
1568
 
1247
1569
  /** Status rules shared by review views and outcomes. */
1248
1570
  function receiptFitsStatus(receipt, status) {
1571
+ // 0.6.0: a chain tx receipt succeeds only included with code 0; a failure
1572
+ // always names its reason (tx_failed = included with code != 0).
1573
+ if (receipt.kind === CHAIN_TX_KIND) {
1574
+ if (status === "succeeded")
1575
+ return (
1576
+ receipt.code === 0 && receipt.height !== null && !("reason" in receipt)
1577
+ );
1578
+ if (status === "failed") return "reason" in receipt;
1579
+ return true;
1580
+ }
1249
1581
  const bank = receipt.kind === "ixo.bank.send.v1";
1250
1582
  if (status === "succeeded")
1251
1583
  return bank
1252
1584
  ? receipt.code === 0 && receipt.height !== null && !("reason" in receipt)
1253
- : receipt.kind !== "service.failure.v1";
1585
+ : receipt.kind !== "service.failure.v1" &&
1586
+ receipt.kind !== "ixo.submission.failed.v1";
1254
1587
  if (status === "failed") {
1255
- if (receipt.kind === "service.failure.v1") return true;
1588
+ if (
1589
+ receipt.kind === "service.failure.v1" ||
1590
+ receipt.kind === "ixo.submission.failed.v1"
1591
+ )
1592
+ return true;
1256
1593
  if (!bank) return false;
1257
1594
  if ("reason" in receipt) return true; // checked by parseReceipt
1258
1595
  return (
@@ -1325,6 +1662,356 @@ export function parseTransferDisplay(input) {
1325
1662
  return t;
1326
1663
  }
1327
1664
 
1665
+ // ---------------------------------------------------------------------------
1666
+ // 0.6.0 chain transactions (`ixo.chain.tx.v1`)
1667
+ // ---------------------------------------------------------------------------
1668
+
1669
+ /** One card kind for every chain transaction (1..8 messages, all or nothing). */
1670
+ export const CHAIN_TX_KIND = "ixo.chain.tx.v1";
1671
+ export const CHAIN_TX_MESSAGE_TYPES = [
1672
+ "cosmos.bank.send",
1673
+ "ixo.claims.submit",
1674
+ "ixo.claims.evaluate",
1675
+ "ixo.token.transfer",
1676
+ ];
1677
+ export const CHAIN_TX_MAX_MESSAGES = 8;
1678
+ export const CHAIN_TX_MAX_TOKEN_LINES = 32;
1679
+ /** `check_tx_rejected`/`expired_not_included`: never included; `tx_failed`: included with code != 0. */
1680
+ export const CHAIN_TX_FAILURE_REASONS = [
1681
+ "check_tx_rejected",
1682
+ "expired_not_included",
1683
+ "tx_failed",
1684
+ ];
1685
+ export const CHAIN_TX_RISK_LEVELS = ["low", "medium", "high", "critical"];
1686
+ /** EvaluationStatus values a chain tx may record (0 pending and 5 flagged are refused). */
1687
+ export const CHAIN_TX_EVALUATION_STATUSES = [1, 2, 3, 4];
1688
+ // The chain's DID rule (x/iid/types/iid.go didValidationRegexpStr): segments of
1689
+ // [A-Za-z0-9._-] or a `%` followed by two hex digits, joined by ':', the last
1690
+ // one non-empty. Anchored at both ends here (the chain's own regex anchors
1691
+ // only its start, so it accepts any suffix; this is stricter, never looser).
1692
+ const DID_TAIL = "(?:(?:[A-Za-z0-9._-]|%[0-9A-Fa-f]{2})*:)*(?:[A-Za-z0-9._-]|%[0-9A-Fa-f]{2})+";
1693
+ const IXO_DID = new RegExp(`^did:ixo:${DID_TAIL}$`);
1694
+ const ANY_DID = new RegExp(`^did:[a-z0-9]+:${DID_TAIL}$`);
1695
+ // The Hub's isIxoAddress: canonical lowercase bech32 with exactly 20 data
1696
+ // bytes (32 payload + 6 checksum characters). The Hub also checks the checksum.
1697
+ const ACCOUNT_ADDRESS = /^ixo1[023456789acdefghjklmnpqrstuvwxyz]{38}$/;
1698
+ const BASE_UNITS = /^[1-9][0-9]{0,77}$/;
1699
+ // A uint64 without leading zeros (checked against UINT64_MAX below).
1700
+ const COLLECTION_ID = /^(0|[1-9][0-9]{0,19})$/;
1701
+ const UINT64_MAX = 18446744073709551615n;
1702
+ const UINT32_MAX = 4294967295;
1703
+ // Claim ids, impact token ids and verification proofs (CIDs, UUIDs, `X:1`).
1704
+ const CHAIN_ID_CHARS = /^[A-Za-z0-9:._/-]+$/;
1705
+ // C0/C1 controls, zero-width and bidi marks (U+061C, U+200B-U+200F,
1706
+ // U+202A-U+202E, U+2066-U+2069), line/paragraph separators and the BOM would
1707
+ // let text render as something else.
1708
+ const CONTROL =
1709
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069\ufeff]/;
1710
+ const CHAIN_TX_MESSAGE_KEYS = {
1711
+ "cosmos.bank.send": ["type", "toAddress", "amountBaseUnits", "denom"],
1712
+ "ixo.claims.submit": [
1713
+ "type",
1714
+ "collectionId",
1715
+ "claimId",
1716
+ "agentDid",
1717
+ "adminAddress",
1718
+ "useIntent",
1719
+ ],
1720
+ "ixo.claims.evaluate": [
1721
+ "type",
1722
+ "claimId",
1723
+ "collectionId",
1724
+ "oracle",
1725
+ "agentDid",
1726
+ "agentAddress",
1727
+ "adminAddress",
1728
+ "status",
1729
+ "reason",
1730
+ "verificationProof",
1731
+ ],
1732
+ "ixo.token.transfer": ["type", "recipient", "tokens"],
1733
+ };
1734
+ const plain = (value) =>
1735
+ value !== null && typeof value === "object" && !Array.isArray(value);
1736
+ const isText = (value, min = 1, max = 200) =>
1737
+ typeof value === "string" && value.length >= min && value.length <= max;
1738
+ const isMatch = (value, regex, max = 200) =>
1739
+ isText(value, 1, max) && regex.test(value);
1740
+ const isId = (value, max) => isMatch(value, CHAIN_ID_CHARS, max);
1741
+ const isCollectionId = (value) =>
1742
+ isMatch(value, COLLECTION_ID, 20) && BigInt(value) <= UINT64_MAX;
1743
+ const utf8Length = (value) => new TextEncoder().encode(value).length;
1744
+
1745
+ /** The first bad field of one message (relative to the message), or null. */
1746
+ function chainTxMessageField(m) {
1747
+ if (m.type === "cosmos.bank.send") {
1748
+ if (!isMatch(m.toAddress, ACCOUNT_ADDRESS)) return "toAddress";
1749
+ if (!isMatch(m.amountBaseUnits, BASE_UNITS, 78)) return "amountBaseUnits";
1750
+ if (m.denom !== undefined && !isMatch(m.denom, DENOM, 128)) return "denom";
1751
+ return null;
1752
+ }
1753
+ if (m.type === "ixo.claims.submit") {
1754
+ if (!isCollectionId(m.collectionId)) return "collectionId";
1755
+ if (!isId(m.claimId, 256)) return "claimId";
1756
+ if (!isMatch(m.agentDid, IXO_DID)) return "agentDid";
1757
+ if (!isMatch(m.adminAddress, ACCOUNT_ADDRESS)) return "adminAddress";
1758
+ if (m.useIntent !== undefined && typeof m.useIntent !== "boolean")
1759
+ return "useIntent";
1760
+ return null;
1761
+ }
1762
+ if (m.type === "ixo.claims.evaluate") {
1763
+ if (!isId(m.claimId, 256)) return "claimId";
1764
+ if (!isCollectionId(m.collectionId)) return "collectionId";
1765
+ if (!isMatch(m.oracle, ANY_DID)) return "oracle";
1766
+ if (!isMatch(m.agentDid, IXO_DID)) return "agentDid";
1767
+ if (!isMatch(m.agentAddress, ACCOUNT_ADDRESS)) return "agentAddress";
1768
+ if (!isMatch(m.adminAddress, ACCOUNT_ADDRESS)) return "adminAddress";
1769
+ if (!CHAIN_TX_EVALUATION_STATUSES.includes(m.status)) return "status";
1770
+ if (
1771
+ m.reason !== undefined &&
1772
+ !(Number.isSafeInteger(m.reason) && m.reason >= 0 && m.reason <= UINT32_MAX)
1773
+ )
1774
+ return "reason";
1775
+ // Optional; omit it rather than sending ''. ≤ 300 so the review shows it whole.
1776
+ if (m.verificationProof !== undefined && !isId(m.verificationProof, 300))
1777
+ return "verificationProof";
1778
+ return null;
1779
+ }
1780
+ // ixo.token.transfer
1781
+ if (!isMatch(m.recipient, ACCOUNT_ADDRESS)) return "recipient";
1782
+ if (
1783
+ !Array.isArray(m.tokens) ||
1784
+ m.tokens.length < 1 ||
1785
+ m.tokens.length > CHAIN_TX_MAX_TOKEN_LINES
1786
+ )
1787
+ return "tokens";
1788
+ for (const [j, token] of m.tokens.entries()) {
1789
+ if (!plain(token)) return `tokens[${j}]`;
1790
+ for (const key of Object.keys(token))
1791
+ if (key !== "id" && key !== "amount") return `tokens[${j}].${key}`;
1792
+ if (!isId(token.id, 128)) return `tokens[${j}].id`;
1793
+ if (!isMatch(token.amount, BASE_UNITS, 78)) return `tokens[${j}].amount`;
1794
+ }
1795
+ return null;
1796
+ }
1797
+
1798
+ /** The first bad field of a chain tx operation (`messages[1].toAddress`), or null. */
1799
+ function chainTxField(op) {
1800
+ for (const key of Object.keys(op))
1801
+ if (!["kind", "chainId", "network", "signer", "memo", "messages"].includes(key))
1802
+ return key;
1803
+ if (!isText(op.chainId, 1, 100)) return "chainId";
1804
+ if (!NETWORKS.includes(op.network)) return "network";
1805
+ if (!isMatch(op.signer, ACCOUNT_ADDRESS)) return "signer";
1806
+ // Cosmos SDK x/auth max_memo_characters counts UTF-8 bytes. The memo is
1807
+ // shown as the "Note", so it carries no control or bidi characters either.
1808
+ if (
1809
+ !isText(op.memo, 0, 256) ||
1810
+ utf8Length(op.memo) > MEMO_BYTES ||
1811
+ CONTROL.test(op.memo)
1812
+ )
1813
+ return "memo";
1814
+ if (
1815
+ !Array.isArray(op.messages) ||
1816
+ op.messages.length < 1 ||
1817
+ op.messages.length > CHAIN_TX_MAX_MESSAGES
1818
+ )
1819
+ return "messages";
1820
+ for (const [i, m] of op.messages.entries()) {
1821
+ const at = `messages[${i}]`;
1822
+ if (!plain(m)) return at;
1823
+ if (!CHAIN_TX_MESSAGE_TYPES.includes(m.type)) return `${at}.type`;
1824
+ for (const key of Object.keys(m))
1825
+ if (!CHAIN_TX_MESSAGE_KEYS[m.type].includes(key)) return `${at}.${key}`;
1826
+ const field = chainTxMessageField(m);
1827
+ if (field) return `${at}.${field}`;
1828
+ }
1829
+ return null;
1830
+ }
1831
+
1832
+ /**
1833
+ * Why a proposed chain tx operation is malformed, as the Hub's 400 `reason`:
1834
+ * `invalid_message: messages[1].toAddress` (0-based message index) or
1835
+ * `invalid_operation: memo`; null when it parses.
1836
+ */
1837
+ export function chainTxIssue(input) {
1838
+ if (!plain(input) || input.kind !== CHAIN_TX_KIND)
1839
+ return "invalid_operation: kind";
1840
+ const field = chainTxField(input);
1841
+ if (field)
1842
+ return field.startsWith("messages[")
1843
+ ? `invalid_message: ${field}`
1844
+ : `invalid_operation: ${field}`;
1845
+ try {
1846
+ validateOperationSchema(input);
1847
+ } catch {
1848
+ return "invalid_operation: operation";
1849
+ }
1850
+ return null;
1851
+ }
1852
+
1853
+ /** `GET /capabilities?version=4` `chainTx`. */
1854
+ export function parseChainTxCapabilities(input) {
1855
+ const c = object(input, "capabilities.chainTx");
1856
+ exact(c, ["messageTypes", "maxMessages"], "capabilities.chainTx");
1857
+ if (
1858
+ !Array.isArray(c.messageTypes) ||
1859
+ c.messageTypes.length < 1 ||
1860
+ new Set(c.messageTypes).size !== c.messageTypes.length ||
1861
+ c.messageTypes.some((type) => !CHAIN_TX_MESSAGE_TYPES.includes(type))
1862
+ )
1863
+ fail("capabilities.chainTx.messageTypes");
1864
+ if (
1865
+ !Number.isSafeInteger(c.maxMessages) ||
1866
+ c.maxMessages < 1 ||
1867
+ c.maxMessages > CHAIN_TX_MAX_MESSAGES
1868
+ )
1869
+ fail("capabilities.chainTx.maxMessages");
1870
+ return c;
1871
+ }
1872
+
1873
+ /** The Hub-computed review display of a chain tx (the only thing a page renders). */
1874
+ export function parseChainTxDisplay(input) {
1875
+ const d = object(input, "view.chainTx");
1876
+ exact(
1877
+ d,
1878
+ [
1879
+ "riskLevel",
1880
+ "confirmTwice",
1881
+ "steps",
1882
+ "consent",
1883
+ "feeBaseUnits",
1884
+ "feeDenom",
1885
+ "feeDisplay",
1886
+ "gasLimit",
1887
+ "feeGranter",
1888
+ "signer",
1889
+ "wrapped",
1890
+ ],
1891
+ "view.chainTx",
1892
+ );
1893
+ if (!CHAIN_TX_RISK_LEVELS.includes(d.riskLevel)) fail("view.chainTx.riskLevel");
1894
+ if (
1895
+ typeof d.confirmTwice !== "boolean" ||
1896
+ d.confirmTwice !== (d.riskLevel === "high" || d.riskLevel === "critical")
1897
+ )
1898
+ fail("view.chainTx.confirmTwice");
1899
+ if (
1900
+ !Array.isArray(d.steps) ||
1901
+ d.steps.length < 1 ||
1902
+ d.steps.length > CHAIN_TX_MAX_MESSAGES
1903
+ )
1904
+ fail("view.chainTx.steps");
1905
+ let highest = 0;
1906
+ for (const [i, step] of d.steps.entries()) {
1907
+ object(step, "view.chainTx.step");
1908
+ exact(
1909
+ step,
1910
+ [
1911
+ "index",
1912
+ "type",
1913
+ "title",
1914
+ "whatItDoes",
1915
+ "facts",
1916
+ "riskLevel",
1917
+ "cannotUndo",
1918
+ "transfer",
1919
+ ],
1920
+ "view.chainTx.step",
1921
+ );
1922
+ if (step.index !== i + 1) fail("view.chainTx.step.index");
1923
+ if (!CHAIN_TX_MESSAGE_TYPES.includes(step.type)) fail("view.chainTx.step.type");
1924
+ str(step.title, "view.chainTx.step.title", 1, 60);
1925
+ str(step.whatItDoes, "view.chainTx.step.whatItDoes", 1, 160);
1926
+ if (!Array.isArray(step.facts) || step.facts.length > 40)
1927
+ fail("view.chainTx.step.facts");
1928
+ for (const fact of step.facts) {
1929
+ object(fact, "view.chainTx.fact");
1930
+ exact(fact, ["label", "value", "technical"], "view.chainTx.fact");
1931
+ str(fact.label, "view.chainTx.fact.label", 1, 60);
1932
+ str(fact.value, "view.chainTx.fact.value", 1, 300);
1933
+ if (fact.technical !== undefined && typeof fact.technical !== "boolean")
1934
+ fail("view.chainTx.fact.technical");
1935
+ }
1936
+ const risk = CHAIN_TX_RISK_LEVELS.indexOf(step.riskLevel);
1937
+ if (risk < 0) fail("view.chainTx.step.riskLevel");
1938
+ highest = Math.max(highest, risk);
1939
+ if (typeof step.cannotUndo !== "boolean") fail("view.chainTx.step.cannotUndo");
1940
+ if (step.transfer !== undefined) {
1941
+ if (step.type !== "cosmos.bank.send") fail("view.chainTx.step.transfer");
1942
+ parseTransferDisplay(step.transfer);
1943
+ }
1944
+ }
1945
+ if (CHAIN_TX_RISK_LEVELS[highest] !== d.riskLevel)
1946
+ fail("view.chainTx.riskLevel");
1947
+ str(d.consent, "view.chainTx.consent", 1, 160);
1948
+ pattern(d.feeBaseUnits, INT, "view.chainTx.feeBaseUnits");
1949
+ if (d.feeDenom !== "uixo") fail("view.chainTx.feeDenom");
1950
+ str(d.feeDisplay, "view.chainTx.feeDisplay", 1, 80);
1951
+ num(d.gasLimit, "view.chainTx.gasLimit");
1952
+ if (d.feeGranter !== null)
1953
+ pattern(d.feeGranter, ADDRESS, "view.chainTx.feeGranter");
1954
+ pattern(d.signer, ACCOUNT_ADDRESS, "view.chainTx.signer");
1955
+ if (typeof d.wrapped !== "boolean") fail("view.chainTx.wrapped");
1956
+ return d;
1957
+ }
1958
+
1959
+ function parseChainTxReceipt(r) {
1960
+ exact(
1961
+ r,
1962
+ [
1963
+ "kind",
1964
+ "actionId",
1965
+ "revision",
1966
+ "digest",
1967
+ "chainId",
1968
+ "txHash",
1969
+ "height",
1970
+ "code",
1971
+ "reason",
1972
+ "message",
1973
+ "steps",
1974
+ ],
1975
+ "receipt",
1976
+ );
1977
+ pattern(r.actionId, ID, "receipt.actionId");
1978
+ num(r.revision, "receipt.revision");
1979
+ pattern(r.digest, HEX, "receipt.digest");
1980
+ str(r.chainId, "receipt.chainId", 1, 100);
1981
+ pattern(r.txHash, HEX, "receipt.txHash");
1982
+ if (r.height !== null) num(r.height, "receipt.height");
1983
+ if (r.code !== null && (!Number.isSafeInteger(r.code) || r.code < 0))
1984
+ fail("receipt.code");
1985
+ if ("reason" in r) {
1986
+ const failedCode = r.code !== null && r.code !== 0;
1987
+ if (
1988
+ !CHAIN_TX_FAILURE_REASONS.includes(r.reason) ||
1989
+ (r.reason === "check_tx_rejected" && (r.height !== null || !failedCode)) ||
1990
+ (r.reason === "expired_not_included" &&
1991
+ (r.height !== null || r.code !== null)) ||
1992
+ (r.reason === "tx_failed" && (r.height === null || !failedCode))
1993
+ )
1994
+ fail("receipt.reason");
1995
+ }
1996
+ // Plain words for the person, only on a failure.
1997
+ if ("message" in r) {
1998
+ if (!("reason" in r)) fail("receipt.message");
1999
+ str(r.message, "receipt.message", 1, 240);
2000
+ }
2001
+ if (
2002
+ !Array.isArray(r.steps) ||
2003
+ r.steps.length < 1 ||
2004
+ r.steps.length > CHAIN_TX_MAX_MESSAGES
2005
+ )
2006
+ fail("receipt.steps");
2007
+ for (const step of r.steps) {
2008
+ object(step, "receipt.step");
2009
+ exact(step, ["type"], "receipt.step");
2010
+ if (!CHAIN_TX_MESSAGE_TYPES.includes(step.type)) fail("receipt.step.type");
2011
+ }
2012
+ return r;
2013
+ }
2014
+
1328
2015
  export * from "./outcome-signature.js";
1329
2016
 
1330
2017
  /** The exact 0.1.0 receipt shape (v1 callers): drops the 0.3.0 bank fields. */