@btps/sdk 1.1.3 → 1.2.0-rc.1

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 (111) hide show
  1. package/CHANGELOG.md +422 -0
  2. package/bin/verify-evidence-bundle.mjs +96 -0
  3. package/dist/client/btpsAgent.d.ts +10 -1
  4. package/dist/client/btpsAgent.js +116 -18
  5. package/dist/client/btpsClient.d.ts +53 -7
  6. package/dist/client/btpsClient.js +265 -147
  7. package/dist/client/index.d.ts +1 -1
  8. package/dist/client/index.js +3 -1
  9. package/dist/client/libs/schema.js +78 -13
  10. package/dist/client/libs/timeouts.d.ts +6 -0
  11. package/dist/client/libs/timeouts.js +2 -1
  12. package/dist/client/types/index.d.ts +54 -2
  13. package/dist/core/authentication/BtpsAuthentication.d.ts +43 -1
  14. package/dist/core/authentication/BtpsAuthentication.js +152 -36
  15. package/dist/core/authentication/refreshSuccessor.js +47 -0
  16. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +17 -1
  17. package/dist/core/authentication/storage/InMemoryTokenStore.js +16 -4
  18. package/dist/core/authentication/types.d.ts +82 -0
  19. package/dist/core/crypto/contentKey.d.ts +34 -0
  20. package/dist/core/crypto/contentKey.js +64 -0
  21. package/dist/core/crypto/decryptVerify.d.ts +7 -1
  22. package/dist/core/crypto/decryptVerify.js +23 -5
  23. package/dist/core/crypto/decrypter-interface.d.ts +6 -0
  24. package/dist/core/crypto/index.d.ts +12 -0
  25. package/dist/core/crypto/index.js +7 -1
  26. package/dist/core/crypto/keyResolver.d.ts +48 -0
  27. package/dist/core/crypto/keyResolver.js +46 -0
  28. package/dist/core/crypto/pem-decrypter.d.ts +2 -0
  29. package/dist/core/crypto/pem-decrypter.js +13 -8
  30. package/dist/core/crypto/signEncrypt.d.ts +4 -1
  31. package/dist/core/crypto/signEncrypt.js +20 -5
  32. package/dist/core/crypto/types.d.ts +8 -1
  33. package/dist/core/delegation/BtpsDelegator.d.ts +4 -0
  34. package/dist/core/delegation/BtpsDelegator.js +3 -2
  35. package/dist/core/delegation/verifyTransporterSignature.d.ts +104 -0
  36. package/dist/core/delegation/verifyTransporterSignature.js +224 -0
  37. package/dist/core/error/constant.d.ts +39 -0
  38. package/dist/core/error/constant.js +55 -0
  39. package/dist/core/server/constants/btps-protocol.d.ts +21 -5
  40. package/dist/core/server/constants/btps-protocol.js +46 -8
  41. package/dist/core/server/constants/index.d.ts +7 -3
  42. package/dist/core/server/constants/index.js +19 -4
  43. package/dist/core/server/constants/limits.d.ts +18 -0
  44. package/dist/core/server/constants/limits.js +19 -1
  45. package/dist/core/server/constants/permissions.d.ts +38 -0
  46. package/dist/core/server/constants/permissions.js +38 -0
  47. package/dist/core/server/schemas/artifacts/agentSchema.js +2 -1
  48. package/dist/core/server/schemas/artifacts/artifacts.js +7 -1
  49. package/dist/core/server/schemas/artifacts/controlSchema.js +1 -1
  50. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +10 -1
  51. package/dist/core/server/schemas/artifacts/transporterSchema.js +92 -12
  52. package/dist/core/server/schemas/bounded.js +2 -2
  53. package/dist/core/server/schemas/btpsDocsSchema.d.ts +34185 -1084
  54. package/dist/core/server/schemas/btpsDocsSchema.js +300 -42
  55. package/dist/core/server/schemas/helpers.d.ts +9580 -0
  56. package/dist/core/server/schemas/helpers.js +76 -12
  57. package/dist/core/server/schemas/keyChainSchema.js +53 -0
  58. package/dist/core/server/schemas/responseSchema.js +52 -9
  59. package/dist/core/server/schemas/schema.js +3 -1
  60. package/dist/core/server/schemas/trustValues.d.ts +105 -0
  61. package/dist/core/server/schemas/trustValues.js +117 -0
  62. package/dist/core/server/types.d.ts +104 -6
  63. package/dist/core/storage/AbstractIdentityStore.d.ts +9 -0
  64. package/dist/core/storage/JsonIdentityStore.d.ts +3 -0
  65. package/dist/core/storage/JsonIdentityStore.js +3 -0
  66. package/dist/core/storage/types.d.ts +2 -0
  67. package/dist/core/trust/agreements.d.ts +107 -0
  68. package/dist/core/trust/agreements.js +116 -0
  69. package/dist/core/trust/evidence.d.ts +220 -0
  70. package/dist/core/trust/evidence.js +334 -0
  71. package/dist/core/trust/index.d.ts +10 -0
  72. package/dist/core/trust/index.js +14 -1
  73. package/dist/core/trust/keyRotation.d.ts +148 -0
  74. package/dist/core/trust/keyRotation.js +267 -0
  75. package/dist/core/trust/permissions.d.ts +114 -0
  76. package/dist/core/trust/permissions.js +115 -0
  77. package/dist/core/trust/shaping.d.ts +42 -0
  78. package/dist/core/trust/shaping.js +47 -0
  79. package/dist/core/trust/storage/AbstractTrustStore.d.ts +2 -1
  80. package/dist/core/trust/storage/JsonTrustStore.d.ts +3 -2
  81. package/dist/core/trust/timestamps.d.ts +49 -0
  82. package/dist/core/trust/timestamps.js +78 -0
  83. package/dist/core/trust/trustUtils.d.ts +13 -2
  84. package/dist/core/trust/trustUtils.js +28 -3
  85. package/dist/core/trust/types.d.ts +302 -2
  86. package/dist/core/trust/verification.d.ts +52 -0
  87. package/dist/core/trust/verification.js +55 -0
  88. package/dist/server/btpsServer.d.ts +70 -5
  89. package/dist/server/btpsServer.js +263 -143
  90. package/dist/server/index.d.ts +3 -0
  91. package/dist/server/index.js +17 -1
  92. package/dist/server/libs/agreementOrderCheck.d.ts +29 -0
  93. package/dist/server/libs/agreementOrderCheck.js +29 -0
  94. package/dist/server/libs/artifactTimeWindow.d.ts +2 -2
  95. package/dist/server/libs/artifactTimeWindow.js +2 -1
  96. package/dist/server/libs/detailsRequestLimit.d.ts +27 -0
  97. package/dist/server/libs/detailsRequestLimit.js +28 -0
  98. package/dist/server/libs/detailsResponseCheck.d.ts +27 -0
  99. package/dist/server/libs/detailsResponseCheck.js +27 -0
  100. package/dist/server/libs/eventChainCheck.d.ts +31 -0
  101. package/dist/server/libs/eventChainCheck.js +39 -0
  102. package/dist/server/libs/inFlightLimit.d.ts +10 -0
  103. package/dist/server/libs/inFlightLimit.js +7 -1
  104. package/dist/server/libs/index.d.ts +5 -0
  105. package/dist/server/libs/index.js +10 -0
  106. package/dist/server/libs/keyChains.d.ts +14 -0
  107. package/dist/server/libs/keyChains.js +17 -0
  108. package/dist/server/libs/wrapForAgent.d.ts +20 -0
  109. package/dist/server/libs/wrapForAgent.js +36 -0
  110. package/dist/server/types.d.ts +95 -9
  111. package/package.json +12 -3
@@ -5,7 +5,13 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
 
8
- import { AGENT_ACTIONS_REQUIRING_DOCUMENT } from "../constants/index.js";
8
+ import {
9
+ AGENT_ACTIONS_REQUIRING_DOCUMENT,
10
+ AGENT_TRANSPORTER_ACTIONS,
11
+ MIN_SUPPORTED_VERSION,
12
+ artifactVersion,
13
+ isVersionBelow
14
+ } from "../constants/index.js";
9
15
  import {
10
16
  BtpAgentMutationSchema,
11
17
  BtpIdsPayloadSchema,
@@ -14,21 +20,41 @@ import {
14
20
  } from "./schema.js";
15
21
  import {
16
22
  BtpAuthReqDocSchema,
23
+ BtpDetailsNoteDocSchema,
17
24
  BtpDocumentSchema,
18
- BtpLifecycleEventSchema,
25
+ BtpDocumentV1_1Schema,
26
+ BtpEventSchema,
27
+ BtpLifecycleEventV1_1Schema,
19
28
  BtpTrustReqDocSchema,
20
- BtpTrustResDocSchema
29
+ BtpTrustReqDocV1_1Schema,
30
+ BtpTrustResDocSchema,
31
+ BtpTrustResDocV1_1Schema
21
32
  } from "./btpsDocsSchema.js";
22
- const processBtpDocSchema = (bptArtifactType) => {
33
+ import {
34
+ BtpDetailsResDocSchema,
35
+ detailsValuesProblem,
36
+ trustRequestProblem,
37
+ trustResponseProblem
38
+ } from "./trustValues.js";
39
+ import { trustRequestProblem as trustRequestProblem2, trustResponseProblem as trustResponseProblem2, BtpDetailValueSchemas } from "./trustValues.js";
40
+ import { trustGrantProblem, documentTypeProblem, detailsProblem } from "../../trust/permissions.js";
41
+ const processBtpDocSchema = (bptArtifactType, version = MIN_SUPPORTED_VERSION) => {
42
+ const before1_2 = isVersionBelow(version, "1.2.0");
23
43
  switch (bptArtifactType) {
24
44
  case "TRUST_RES":
25
- return BtpTrustResDocSchema;
45
+ return before1_2 ? BtpTrustResDocV1_1Schema : BtpTrustResDocSchema;
26
46
  case "TRUST_REQ":
27
- return BtpTrustReqDocSchema;
47
+ return before1_2 ? BtpTrustReqDocV1_1Schema : BtpTrustReqDocSchema;
28
48
  case "BTPS_DOC":
29
- return BtpDocumentSchema;
49
+ return before1_2 ? BtpDocumentV1_1Schema : BtpDocumentSchema;
30
50
  case "BTPS_EVENT":
31
- return BtpLifecycleEventSchema;
51
+ return before1_2 ? BtpLifecycleEventV1_1Schema : BtpEventSchema;
52
+
53
+ case "DETAILS_CHANGED":
54
+ case "DETAILS_REQ":
55
+ return BtpDetailsNoteDocSchema;
56
+ case "DETAILS_RES":
57
+ return BtpDetailsResDocSchema;
32
58
  default:
33
59
  return null;
34
60
  }
@@ -36,21 +62,48 @@ const processBtpDocSchema = (bptArtifactType) => {
36
62
  if (event.id !== envelope.id) return "an event's id must be the id of the artifact carrying it";
37
63
  if (event.document.from !== envelope.from && event.document.from !== envelope.to)
38
64
  return "an event may only be about an invoice between its own sender and receiver";
65
+ }, agreementEventEnvelopeProblem = (event, envelope) => {
66
+ if (event.id !== envelope.id) return "an event's id must be the id of the artifact carrying it";
67
+ const { originator } = event.agreement;
68
+ if (!sameIdentity(originator, envelope.from) && !sameIdentity(originator, envelope.to))
69
+ return "an agreement's event travels between its originator and a signer";
70
+ }, PROPOSALS = ["paid", "partially_paid", "disputed", "refund_requested"], lifecycleEventChainReference = (event) => event.eventType === "withdrawn" ? event.inReplyTo : "follows" in event ? event.follows : void 0, sameIdentity = (a, b) => a.toLowerCase() === b.toLowerCase(), sameDocument = (a, b) => sameIdentity(a.from, b.from) && a.id === b.id, lifecycleEventSenderProblem = (event, envelope) => {
71
+ if (lifecycleEventChainReference(event) !== void 0 && sameIdentity(envelope.from, event.document.from))
72
+ return "only the payer withdraws or proposes again, never the invoice's issuer";
73
+ }, lifecycleEventChainProblem = (event, envelope, named) => {
74
+ if (lifecycleEventChainReference(event) === void 0) return;
75
+ const senderProblem = lifecycleEventSenderProblem(event, envelope);
76
+ if (senderProblem) return senderProblem;
77
+ if (event.eventType === "withdrawn")
78
+ return named ? PROPOSALS.includes(named.eventType) ? sameIdentity(named.from, envelope.from) ? sameDocument(named.document, event.document) ? named.state !== "open" ? "a proposal already answered or withdrawn stays as it is" : void 0 : "a withdrawn is about the same invoice as the proposal it takes back" : "only its sender can withdraw a proposal" : "only a proposal can be withdrawn" : "a withdrawn must name an event between the same two parties";
79
+ if (named?.eventType !== "withdrawn")
80
+ return "follows must name a withdrawn event between the same two parties";
81
+ if (!sameDocument(named.document, event.document))
82
+ return "a proposal follows a withdrawn about the same invoice";
39
83
  }, decryptedDocumentProblem = (document, envelope) => {
40
- const schema = processBtpDocSchema(envelope.type);
84
+ const version = typeof envelope.version == "string" ? envelope.version : void 0, schema = processBtpDocSchema(envelope.type, version);
41
85
  if (!schema) return;
42
86
  const parsed = schema.safeParse(document);
43
87
  if (!parsed.success) return "Document type does not match the artifact type";
88
+ const names = envelope;
89
+ if (envelope.type === "TRUST_REQ") return trustRequestProblem({ given: names.given, document });
90
+ if (envelope.type === "TRUST_RES")
91
+ return trustResponseProblem({ granted: names.granted, document });
92
+ if (envelope.type === "DETAILS_RES")
93
+ return detailsValuesProblem({
94
+ details: envelope.details,
95
+ document
96
+ });
44
97
  if (envelope.type !== "BTPS_EVENT") return;
45
98
  const event = parsed.data, { id, from, to } = envelope;
46
- return typeof id != "string" || typeof from != "string" || typeof to != "string" ? "an event must travel in an artifact with an id, from and to" : lifecycleEventEnvelopeProblem(event, { id, from, to });
99
+ return typeof id != "string" || typeof from != "string" || typeof to != "string" ? "an event must travel in an artifact with an id, from and to" : event.type === "agreement_event" ? agreementEventEnvelopeProblem(event, { id, from, to }) : lifecycleEventEnvelopeProblem(event, { id, from, to });
47
100
  }, processBtpDocSchemaForAgent = (actionType) => ({
48
101
  "trust.request": BtpTrustReqDocSchema,
49
102
  "trust.respond": BtpTrustResDocSchema,
50
103
  "trust.update": BtpAgentMutationSchema,
51
104
  "trust.delete": BtpIdsPayloadSchema,
52
105
  "artifact.send": BtpDocumentSchema,
53
- "event.send": BtpLifecycleEventSchema,
106
+ "event.send": BtpEventSchema,
54
107
  "auth.request": BtpAuthReqDocSchema,
55
108
  "auth.refresh": BtpAuthReqDocSchema,
56
109
  "inbox.fetch": BtpAgentQuerySchema,
@@ -72,16 +125,27 @@ const processBtpDocSchema = (bptArtifactType) => {
72
125
  ) && !document || encryption && typeof document != "string" || encryption && action === "auth.request")
73
126
  return !1;
74
127
  if (document) {
75
- const expectedSchema = processBtpDocSchemaForAgent(action);
128
+ const sendsAs = action in AGENT_TRANSPORTER_ACTIONS ? AGENT_TRANSPORTER_ACTIONS[action] : void 0, expectedSchema = sendsAs ? processBtpDocSchema(sendsAs, artifactVersion({ type: sendsAs, document })) : processBtpDocSchemaForAgent(action);
76
129
  if (expectedSchema && !expectedSchema.safeParse(document).success)
77
130
  return !1;
78
131
  }
79
132
  return !0;
80
133
  };
81
134
  export {
135
+ BtpDetailValueSchemas,
136
+ agreementEventEnvelopeProblem,
82
137
  decryptedDocumentProblem,
138
+ detailsProblem,
139
+ documentTypeProblem,
140
+ lifecycleEventChainProblem,
141
+ lifecycleEventChainReference,
83
142
  lifecycleEventEnvelopeProblem,
143
+ lifecycleEventSenderProblem,
84
144
  processBtpDocSchema,
85
145
  processBtpDocSchemaForAgent,
146
+ sameIdentity,
147
+ trustGrantProblem,
148
+ trustRequestProblem2 as trustRequestProblem,
149
+ trustResponseProblem2 as trustResponseProblem,
86
150
  validateAgentDocument
87
151
  };
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+
8
+ import { z } from "zod";
9
+ import { BTPS_FIELD_LIMITS } from "../constants/limits.js";
10
+ import { BtpSignatureSchema, identitySchema } from "./shared.js";
11
+ import { boundedArray } from "./bounded.js";
12
+ const { keyChain: LIMITS } = BTPS_FIELD_LIMITS, sha256Hex = z.string().regex(/^[0-9a-f]{64}$/, "must be a SHA-256 in lowercase hex"), selector = z.string().regex(/^[A-Za-z0-9_-]{1,63}$/, "must be a DNS label"), fingerprint = z.string().regex(/^[A-Za-z0-9+/]{43}=$/, "must be a SHA-256 in base64"), time = z.string().datetime(), reason = z.enum(["compromised", "lost"]), BtpRotatedKeySchema = z.object({
13
+ selector,
14
+ fingerprint,
15
+ publicKey: z.string().max(LIMITS.publicKey).regex(/^[A-Za-z0-9+/]+={0,2}$/, "must be a DER SPKI in base64")
16
+ }).strict(), BtpKeyRotationSchema = z.object({
17
+ type: z.literal("btps.keyRotation.v1"),
18
+ identity: identitySchema,
19
+ from: BtpRotatedKeySchema,
20
+ to: BtpRotatedKeySchema,
21
+ at: time,
22
+ expiry: z.enum(["planned", "immediate"]),
23
+ compromisedSince: time.optional(),
24
+ reason: reason.optional(),
25
+ prev: sha256Hex.nullable()
26
+ }).strict().superRefine((rotation, ctx) => {
27
+ const immediate = rotation.expiry === "immediate";
28
+ for (const field of ["compromisedSince", "reason"])
29
+ rotation[field] !== void 0 !== immediate && ctx.addIssue({
30
+ code: z.ZodIssueCode.custom,
31
+ path: [field],
32
+ message: `${field} is on a rotation with immediate expiry, and only there`
33
+ });
34
+ }), BtpKeyExpirySchema = z.object({
35
+ type: z.literal("btps.keyExpiry.v1"),
36
+ identity: identitySchema,
37
+ key: z.object({ selector, fingerprint }).strict(),
38
+ compromisedSince: time,
39
+ reason,
40
+ at: time,
41
+ prev: sha256Hex
42
+ }).strict(), BtpKeyChainSignatureSchema = BtpSignatureSchema.extend({
43
+ by: z.enum(["from", "to", "current"])
44
+ }).strict(), signatures = boundedArray(BtpKeyChainSignatureSchema, 2, 1), timestamp = z.string().min(1).optional(), BtpKeyChainRecordSchema = z.union([
45
+ z.object({ rotation: BtpKeyRotationSchema, signatures, timestamp }).strict(),
46
+ z.object({ expiry: BtpKeyExpirySchema, signatures, timestamp }).strict()
47
+ ]), BtpKeyChainSchema = boundedArray(BtpKeyChainRecordSchema, LIMITS.records);
48
+ export {
49
+ BtpKeyChainRecordSchema,
50
+ BtpKeyChainSchema,
51
+ BtpKeyExpirySchema,
52
+ BtpKeyRotationSchema
53
+ };
@@ -8,15 +8,25 @@
8
8
  import { z } from "zod";
9
9
  import { BtpSignatureSchema, BtpEncryptionSchema } from "./schema.js";
10
10
  import { identitySchema } from "./shared.js";
11
- import { BtpAuthResDocSchema, BtpIdentityResDocSchema } from "./btpsDocsSchema.js";
12
- import { BtpTransporterArtifactSchema } from "./artifacts/transporterSchema.js";
11
+ import {
12
+ BtpAuthResDocSchema,
13
+ BtpCreatedResDocSchema,
14
+ BtpIdentityResDocSchema
15
+ } from "./btpsDocsSchema.js";
16
+ import {
17
+ BtpTransporterArtifactSchema,
18
+ BtpTrustRecordPermissionsSchema
19
+ } from "./artifacts/transporterSchema.js";
13
20
  import { boundedArray, boundedRecord } from "./bounded.js";
14
21
  import { BTPS_FIELD_LIMITS } from "../constants/limits.js";
22
+ import { isVersionBelow } from "../constants/index.js";
15
23
  const { query, trustRecord, recordKeys } = BTPS_FIELD_LIMITS, BtpStatusSchema = z.object({
16
24
  ok: z.boolean(),
17
25
  code: z.number(),
18
26
  message: z.string().optional(),
19
- error: z.string().optional()
27
+ error: z.string().optional(),
28
+ retryAfter: z.number().int().nonnegative().optional(),
29
+ closing: z.literal(!0).optional()
20
30
  }), BtpDeliveryFailureDocSchema = z.object({
21
31
  id: z.string(),
22
32
  reason: z.string(),
@@ -57,7 +67,9 @@ const { query, trustRecord, recordKeys } = BTPS_FIELD_LIMITS, BtpStatusSchema =
57
67
  ),
58
68
  privacyType: z.enum(["unencrypted", "encrypted", "mixed"]),
59
69
  retryAfterDate: z.string().datetime().optional(),
60
- metadata: boundedRecord(z.unknown(), recordKeys).optional()
70
+ metadata: boundedRecord(z.unknown(), recordKeys).optional(),
71
+
72
+ permissions: BtpTrustRecordPermissionsSchema.optional()
61
73
  }).refine((record) => record.status === "pending" || record.decidedAt !== "", {
62
74
  message: "only a pending trust has no decidedAt",
63
75
  path: ["decidedAt"]
@@ -69,8 +81,20 @@ const { query, trustRecord, recordKeys } = BTPS_FIELD_LIMITS, BtpStatusSchema =
69
81
  ]),
70
82
  meta: z.object({
71
83
  seen: z.boolean().optional(),
72
- seenAt: z.string().datetime().optional()
73
- }).catchall(z.unknown()).optional()
84
+ seenAt: z.string().datetime().optional(),
85
+
86
+ delivery: z.object({
87
+ status: z.enum(["pending", "delivered", "failed"]),
88
+ code: z.string().min(1).optional(),
89
+ at: z.string().datetime()
90
+ }).strict().optional()
91
+ }).catchall(z.unknown()).optional(),
92
+
93
+ agentKey: z.object({
94
+ key: z.string().min(1),
95
+ fingerprint: z.string().min(1),
96
+ wrappedAt: z.string().datetime()
97
+ }).strict().optional()
74
98
  }), BtpQueryResultSchema = z.object({
75
99
  results: boundedArray(BtpQueryResultEntrySchema, query.results),
76
100
  cursor: z.string().optional(),
@@ -79,7 +103,8 @@ const { query, trustRecord, recordKeys } = BTPS_FIELD_LIMITS, BtpStatusSchema =
79
103
  }), BtpServerResDocsSchema = z.union([
80
104
  BtpAuthResDocSchema,
81
105
  BtpQueryResultSchema,
82
- BtpIdentityResDocSchema
106
+ BtpIdentityResDocSchema,
107
+ BtpCreatedResDocSchema
83
108
  ]), BtpServerResponseSchema = z.object({
84
109
  version: z.string().regex(/^\d+\.\d+\.\d+$/, "Version must be in semantic versioning format (e.g., 1.0.0)"),
85
110
  status: BtpStatusSchema,
@@ -93,7 +118,7 @@ const { query, trustRecord, recordKeys } = BTPS_FIELD_LIMITS, BtpStatusSchema =
93
118
  signedBy: identitySchema.optional(),
94
119
  selector: z.string().optional()
95
120
  }).superRefine((data, ctx) => {
96
- data.signature && (data.signedBy || ctx.addIssue({
121
+ if (data.signature && (data.signedBy || ctx.addIssue({
97
122
  path: ["signedBy"],
98
123
  code: z.ZodIssueCode.custom,
99
124
  message: "signedBy is required when signature is present"
@@ -105,7 +130,25 @@ const { query, trustRecord, recordKeys } = BTPS_FIELD_LIMITS, BtpStatusSchema =
105
130
  path: ["document"],
106
131
  code: z.ZodIssueCode.custom,
107
132
  message: "When encrypted, document must be a string"
108
- });
133
+ }), data.status.retryAfter !== void 0 && (data.status.code !== 429 && ctx.addIssue({
134
+ path: ["status", "retryAfter"],
135
+ code: z.ZodIssueCode.custom,
136
+ message: "retryAfter is only on a 429"
137
+ }), isVersionBelow(data.version, "1.2.0") && ctx.addIssue({
138
+ path: ["status", "retryAfter"],
139
+ code: z.ZodIssueCode.custom,
140
+ message: "retryAfter is only in a 1.2.0 response"
141
+ })), data.status.closing !== void 0 && isVersionBelow(data.version, "1.2.0") && ctx.addIssue({
142
+ path: ["status", "closing"],
143
+ code: z.ZodIssueCode.custom,
144
+ message: "closing is only in a 1.2.0 response"
145
+ }), typeof data.document == "object" && "keyType" in data.document && isVersionBelow(data.version, "1.2.0"))
146
+ for (const field of ["identity", "keyChain"])
147
+ field in data.document && ctx.addIssue({
148
+ path: ["document", field],
149
+ code: z.ZodIssueCode.custom,
150
+ message: `${field} is only in a 1.2.0 response`
151
+ });
109
152
  });
110
153
  export {
111
154
  BtpDeliveryFailureArtifactSchema,
@@ -18,7 +18,9 @@ const BtpCryptoOptionsSchema = z.object({
18
18
  encryption: z.object({
19
19
  algorithm: z.literal("aes-256-gcm"),
20
20
  mode: z.enum(["none", "standardEncrypt", "2faEncrypt"])
21
- }).optional()
21
+ }).optional(),
22
+
23
+ versionFallback: z.boolean().optional()
22
24
  }), BtpsAgentActionTypeSchema = z.enum(AGENT_ACTIONS), BtpEncryptionSchema = z.object({
23
25
  algorithm: z.literal("aes-256-gcm"),
24
26
  encryptedKey: z.string(),
@@ -0,0 +1,105 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ import { z } from 'zod';
8
+ /** Since 1.2: the value each detail permission carries. */
9
+ export declare const BtpDetailValueSchemas: Record<string, z.ZodTypeAny>;
10
+ /**
11
+ * Since 1.2: a provider's signed statement that it checked a sender, in a
12
+ * trust request's document. Its claims are keyed by the protocol's names only:
13
+ * `entityType`, and `detail:` names with their values' shapes.
14
+ */
15
+ export declare const BtpVerificationSchema: z.ZodObject<{
16
+ verifiedBy: z.ZodEffects<z.ZodString, string, string>;
17
+ claims: z.ZodEffects<z.ZodObject<{
18
+ entityType: z.ZodOptional<z.ZodEnum<["person", "organisation"]>>;
19
+ }, "strict", z.ZodTypeAny, {
20
+ entityType?: "person" | "organisation" | undefined;
21
+ }, {
22
+ entityType?: "person" | "organisation" | undefined;
23
+ }>, {
24
+ entityType?: "person" | "organisation" | undefined;
25
+ }, {
26
+ entityType?: "person" | "organisation" | undefined;
27
+ }>;
28
+ verifiedAt: z.ZodString;
29
+ expiresAt: z.ZodString;
30
+ selector: z.ZodString;
31
+ signature: z.ZodObject<{
32
+ algorithmHash: z.ZodLiteral<"sha256">;
33
+ value: z.ZodString;
34
+ fingerprint: z.ZodString;
35
+ }, "strip", z.ZodTypeAny, {
36
+ value: string;
37
+ algorithmHash: "sha256";
38
+ fingerprint: string;
39
+ }, {
40
+ value: string;
41
+ algorithmHash: "sha256";
42
+ fingerprint: string;
43
+ }>;
44
+ }, "strict", z.ZodTypeAny, {
45
+ signature: {
46
+ value: string;
47
+ algorithmHash: "sha256";
48
+ fingerprint: string;
49
+ };
50
+ selector: string;
51
+ expiresAt: string;
52
+ verifiedBy: string;
53
+ claims: {
54
+ entityType?: "person" | "organisation" | undefined;
55
+ };
56
+ verifiedAt: string;
57
+ }, {
58
+ signature: {
59
+ value: string;
60
+ algorithmHash: "sha256";
61
+ fingerprint: string;
62
+ };
63
+ selector: string;
64
+ expiresAt: string;
65
+ verifiedBy: string;
66
+ claims: {
67
+ entityType?: "person" | "organisation" | undefined;
68
+ };
69
+ verifiedAt: string;
70
+ }>;
71
+ /**
72
+ * Since 1.2: why an opened trust request's values do not match the names it
73
+ * gives (`given`), or undefined. Each name given has its value, in the 1.1
74
+ * field it has or else in `own`; `own` holds only names given that 1.1 has no
75
+ * field for.
76
+ */
77
+ export declare const trustRequestProblem: (artifact: {
78
+ given?: readonly string[];
79
+ document?: unknown;
80
+ }) => string | undefined;
81
+ /**
82
+ * Since 1.2: why an opened trust answer's values do not match the names it
83
+ * grants, or undefined. `details` holds a value for every `detail:` name
84
+ * granted, by name, and nothing else.
85
+ */
86
+ export declare const trustResponseProblem: (artifact: {
87
+ granted?: readonly string[];
88
+ document?: unknown;
89
+ }) => string | undefined;
90
+ /** Since 1.2: a DETAILS_RES's document: the value of each detail it answers, by name. */
91
+ export declare const BtpDetailsResDocSchema: z.ZodObject<{
92
+ [k: string]: z.ZodOptional<z.ZodTypeAny>;
93
+ }, "strict", z.ZodTypeAny, {
94
+ [x: string]: any;
95
+ }, {
96
+ [x: string]: any;
97
+ }>;
98
+ /**
99
+ * Since 1.2: why an opened DETAILS_RES's values do not match the names on its
100
+ * envelope (`details`), or undefined: a value for every name, valid for it, and no others.
101
+ */
102
+ export declare const detailsValuesProblem: (artifact: {
103
+ details?: readonly string[];
104
+ document?: unknown;
105
+ }) => string | undefined;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+
8
+ import { z } from "zod";
9
+ import { BTPS_FIELD_LIMITS } from "../constants/limits.js";
10
+ import { httpsUrl, sha256Hex } from "./btpsDocsSchema.js";
11
+ import { BtpSignatureSchema, identitySchema } from "./shared.js";
12
+ import { ENTITY_TYPES } from "../constants/permissions.js";
13
+ const { trustRequest, detailNumber } = BTPS_FIELD_LIMITS, text = (max) => z.string().min(1).max(max), numberInCountry = z.object({
14
+ number: text(detailNumber),
15
+ country: z.string().regex(/^[A-Z]{2}$/, "must be an ISO 3166-1 alpha-2 code")
16
+ }).strict(), dateOfBirth = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "must be YYYY-MM-DD").refine(
17
+ (date) => {
18
+ const time = Date.parse(`${date}T00:00:00.000Z`);
19
+ return !Number.isNaN(time) && new Date(time).toISOString().startsWith(date);
20
+ },
21
+ { message: "must be a real date" }
22
+ ), BtpDetailValueSchemas = {
23
+ "detail:legalName": text(trustRequest.name),
24
+ "detail:profile": z.object({
25
+ displayName: text(trustRequest.displayName),
26
+ logo: z.object({ sha256: sha256Hex, source: httpsUrl }).strict().optional(),
27
+ website: httpsUrl.optional()
28
+ }).strict(),
29
+ "detail:email": z.string().max(trustRequest.email).email(),
30
+ "detail:phone": text(trustRequest.phone),
31
+ "detail:address": text(trustRequest.address),
32
+ "detail:taxNo": numberInCountry,
33
+ "detail:dob": dateOfBirth,
34
+ "detail:registrationNumber": numberInCountry
35
+ }, BtpVerificationSchema = z.object({
36
+ verifiedBy: identitySchema,
37
+ claims: z.object({
38
+ entityType: z.enum(ENTITY_TYPES).optional(),
39
+ ...Object.fromEntries(
40
+ Object.entries(BtpDetailValueSchemas).map(([name, schema]) => [name, schema.optional()])
41
+ )
42
+ }).strict().refine((claims) => Object.keys(claims).length > 0, {
43
+ message: "claims names what was checked"
44
+ }),
45
+ verifiedAt: z.string().datetime(),
46
+ expiresAt: z.string().datetime(),
47
+ selector: z.string().min(1),
48
+ signature: BtpSignatureSchema
49
+ }).strict(), REQUEST_FIELDS = {
50
+ "detail:legalName": "name",
51
+ "detail:email": "email",
52
+ "detail:phone": "phone",
53
+ "detail:address": "address",
54
+ "detail:profile": "displayName"
55
+ }, recordOf = (value) => typeof value == "object" && value !== null && !Array.isArray(value) ? value : void 0, valueProblem = (where, name, value) => BtpDetailValueSchemas[name]?.safeParse(value).success ? void 0 : `${where}'s ${name} is not a valid ${name}`, trustRequestProblem = (artifact) => {
56
+ const document = recordOf(artifact.document);
57
+ if (!document) return "a trust request is checked once it is opened";
58
+ const own = document.own === void 0 ? {} : recordOf(document.own);
59
+ if (!own) return "own holds values by name";
60
+ const given = artifact.given ?? [];
61
+ for (const name of given) {
62
+ const field = REQUEST_FIELDS[name];
63
+ if (field !== void 0) {
64
+ if (document[field] === void 0) return `${name} is given, so the request has its ${field}`;
65
+ continue;
66
+ }
67
+ if (own[name] === void 0) return `${name} is given, so own holds its value`;
68
+ const problem = valueProblem("own", name, own[name]);
69
+ if (problem) return problem;
70
+ }
71
+ for (const name of Object.keys(own)) {
72
+ if (!given.includes(name)) return `own holds ${name}, which is not given`;
73
+ const field = REQUEST_FIELDS[name];
74
+ if (field !== void 0) return `${name} is the request's ${field}, never repeated in own`;
75
+ }
76
+ if (document.verification !== void 0) {
77
+ const verification = BtpVerificationSchema.safeParse(document.verification);
78
+ if (!verification.success)
79
+ return `verification is not well formed: ${verification.error.issues.map((issue) => issue.message).join("; ")}`;
80
+ }
81
+ }, trustResponseProblem = (artifact) => {
82
+ const document = recordOf(artifact.document);
83
+ if (!document) return "a trust answer is checked once it is opened";
84
+ const details = document.details === void 0 ? {} : recordOf(document.details);
85
+ if (!details) return "details holds values by name";
86
+ const granted = (artifact.granted ?? []).filter((name) => name.startsWith("detail:"));
87
+ for (const name of granted) {
88
+ if (details[name] === void 0) return `${name} is granted, so details holds its value`;
89
+ const problem = valueProblem("details", name, details[name]);
90
+ if (problem) return problem;
91
+ }
92
+ for (const name of Object.keys(details))
93
+ if (!granted.includes(name)) return `details holds ${name}, which is not granted`;
94
+ }, BtpDetailsResDocSchema = z.object(
95
+ Object.fromEntries(
96
+ Object.entries(BtpDetailValueSchemas).map(([name, schema]) => [name, schema.optional()])
97
+ )
98
+ ).strict(), detailsValuesProblem = (artifact) => {
99
+ const document = recordOf(artifact.document);
100
+ if (!document) return "a details response is checked once it is opened";
101
+ const names = artifact.details ?? [];
102
+ for (const name of names) {
103
+ if (document[name] === void 0) return `${name} is named, so the response holds its value`;
104
+ const problem = valueProblem("the response", name, document[name]);
105
+ if (problem) return problem;
106
+ }
107
+ for (const name of Object.keys(document))
108
+ if (!names.includes(name)) return `the response holds ${name}, which it does not name`;
109
+ };
110
+ export {
111
+ BtpDetailValueSchemas,
112
+ BtpDetailsResDocSchema,
113
+ BtpVerificationSchema,
114
+ detailsValuesProblem,
115
+ trustRequestProblem,
116
+ trustResponseProblem
117
+ };