@btps/sdk 0.0.0-stage → 1.1.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 (155) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/LICENSE +190 -0
  3. package/NOTICE +25 -0
  4. package/README.md +261 -2
  5. package/dist/client/btpsAgent.d.ts +20 -0
  6. package/dist/client/btpsAgent.js +172 -0
  7. package/dist/client/btpsClient.d.ts +202 -0
  8. package/dist/client/btpsClient.js +602 -0
  9. package/dist/client/btpsTransporter.d.ts +52 -0
  10. package/dist/client/btpsTransporter.js +249 -0
  11. package/dist/client/constants/index.d.ts +11 -0
  12. package/dist/client/constants/index.js +20 -0
  13. package/dist/client/index.d.ts +12 -0
  14. package/dist/client/index.js +27 -0
  15. package/dist/client/libs/schema.js +56 -0
  16. package/dist/client/libs/timeouts.d.ts +22 -0
  17. package/dist/client/libs/timeouts.js +19 -0
  18. package/dist/client/types/index.d.ts +155 -0
  19. package/dist/client/types/index.js +7 -0
  20. package/dist/core/authentication/BtpsAuthentication.d.ts +128 -0
  21. package/dist/core/authentication/BtpsAuthentication.js +293 -0
  22. package/dist/core/authentication/index.d.ts +11 -0
  23. package/dist/core/authentication/index.js +12 -0
  24. package/dist/core/authentication/keyProof.d.ts +18 -0
  25. package/dist/core/authentication/keyProof.js +16 -0
  26. package/dist/core/authentication/storage/InMemoryAuthSessionStore.d.ts +55 -0
  27. package/dist/core/authentication/storage/InMemoryAuthSessionStore.js +62 -0
  28. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +63 -0
  29. package/dist/core/authentication/storage/InMemoryTokenStore.js +63 -0
  30. package/dist/core/authentication/types.d.ts +135 -0
  31. package/dist/core/authentication/types.js +7 -0
  32. package/dist/core/crypto/decryptVerify.d.ts +9 -0
  33. package/dist/core/crypto/decryptVerify.js +45 -0
  34. package/dist/core/crypto/decrypter-interface.d.ts +25 -0
  35. package/dist/core/crypto/decrypter-interface.js +7 -0
  36. package/dist/core/crypto/index.d.ts +77 -0
  37. package/dist/core/crypto/index.js +210 -0
  38. package/dist/core/crypto/jcs.d.ts +28 -0
  39. package/dist/core/crypto/jcs.js +60 -0
  40. package/dist/core/crypto/keygen.d.ts +9 -0
  41. package/dist/core/crypto/keygen.js +35 -0
  42. package/dist/core/crypto/pem-decrypter.d.ts +26 -0
  43. package/dist/core/crypto/pem-decrypter.js +52 -0
  44. package/dist/core/crypto/pem-signer.d.ts +21 -0
  45. package/dist/core/crypto/pem-signer.js +34 -0
  46. package/dist/core/crypto/signEncrypt.d.ts +34 -0
  47. package/dist/core/crypto/signEncrypt.js +75 -0
  48. package/dist/core/crypto/signer-interface.d.ts +22 -0
  49. package/dist/core/crypto/signer-interface.js +7 -0
  50. package/dist/core/crypto/types.d.ts +79 -0
  51. package/dist/core/crypto/types.js +7 -0
  52. package/dist/core/delegation/BtpsDelegator.d.ts +102 -0
  53. package/dist/core/delegation/BtpsDelegator.js +118 -0
  54. package/dist/core/delegation/index.d.ts +7 -0
  55. package/dist/core/delegation/index.js +8 -0
  56. package/dist/core/error/constant.d.ts +66 -0
  57. package/dist/core/error/constant.js +194 -0
  58. package/dist/core/error/index.d.ts +35 -0
  59. package/dist/core/error/index.js +52 -0
  60. package/dist/core/error/types.d.ts +16 -0
  61. package/dist/core/error/types.js +7 -0
  62. package/dist/core/server/constants/btps-protocol.d.ts +17 -0
  63. package/dist/core/server/constants/btps-protocol.js +25 -0
  64. package/dist/core/server/constants/control.d.ts +7 -0
  65. package/dist/core/server/constants/control.js +11 -0
  66. package/dist/core/server/constants/currency.d.ts +7 -0
  67. package/dist/core/server/constants/currency.js +332 -0
  68. package/dist/core/server/constants/index.d.ts +26 -0
  69. package/dist/core/server/constants/index.js +61 -0
  70. package/dist/core/server/constants/limits.d.ts +50 -0
  71. package/dist/core/server/constants/limits.js +50 -0
  72. package/dist/core/server/helpers/BtpsMessageQueue.d.ts +13 -0
  73. package/dist/core/server/helpers/BtpsMessageQueue.js +12 -0
  74. package/dist/core/server/helpers/InMemoryQueue.d.ts +16 -0
  75. package/dist/core/server/helpers/InMemoryQueue.js +35 -0
  76. package/dist/core/server/helpers/index.d.ts +8 -0
  77. package/dist/core/server/helpers/index.js +9 -0
  78. package/dist/core/server/schemas/artifacts/agentSchema.js +51 -0
  79. package/dist/core/server/schemas/artifacts/artifacts.js +21 -0
  80. package/dist/core/server/schemas/artifacts/controlSchema.js +18 -0
  81. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +21 -0
  82. package/dist/core/server/schemas/artifacts/transporterSchema.js +60 -0
  83. package/dist/core/server/schemas/btpsDocsSchema.d.ts +4519 -0
  84. package/dist/core/server/schemas/btpsDocsSchema.js +272 -0
  85. package/dist/core/server/schemas/helpers.js +87 -0
  86. package/dist/core/server/schemas/responseSchema.js +86 -0
  87. package/dist/core/server/schemas/schema.js +70 -0
  88. package/dist/core/server/schemas/shared.js +18 -0
  89. package/dist/core/server/types.d.ts +172 -0
  90. package/dist/core/server/types.js +7 -0
  91. package/dist/core/storage/AbstractIdentityStore.d.ts +17 -0
  92. package/dist/core/storage/AbstractIdentityStore.js +13 -0
  93. package/dist/core/storage/AbstractStorageStore.d.ts +16 -0
  94. package/dist/core/storage/AbstractStorageStore.js +17 -0
  95. package/dist/core/storage/JsonIdentityStore.d.ts +29 -0
  96. package/dist/core/storage/JsonIdentityStore.js +39 -0
  97. package/dist/core/storage/JsonStorageStore.d.ts +59 -0
  98. package/dist/core/storage/JsonStorageStore.js +110 -0
  99. package/dist/core/storage/index.d.ts +11 -0
  100. package/dist/core/storage/index.js +18 -0
  101. package/dist/core/storage/types.d.ts +28 -0
  102. package/dist/core/storage/types.js +7 -0
  103. package/dist/core/trust/index.d.ts +10 -0
  104. package/dist/core/trust/index.js +15 -0
  105. package/dist/core/trust/storage/AbstractTrustStore.d.ts +23 -0
  106. package/dist/core/trust/storage/AbstractTrustStore.js +13 -0
  107. package/dist/core/trust/storage/JsonTrustStore.d.ts +33 -0
  108. package/dist/core/trust/storage/JsonTrustStore.js +42 -0
  109. package/dist/core/trust/trustUtils.d.ts +78 -0
  110. package/dist/core/trust/trustUtils.js +41 -0
  111. package/dist/core/trust/types.d.ts +53 -0
  112. package/dist/core/trust/types.js +7 -0
  113. package/dist/core/utils/identity.d.ts +20 -0
  114. package/dist/core/utils/identity.js +22 -0
  115. package/dist/core/utils/index.d.ts +70 -0
  116. package/dist/core/utils/index.js +124 -0
  117. package/dist/core/utils/types.d.ts +10 -0
  118. package/dist/core/utils/types.js +7 -0
  119. package/dist/core/utils/validation.js +13 -0
  120. package/dist/index.d.ts +7 -0
  121. package/dist/index.js +8 -0
  122. package/dist/server/btpsServer.d.ts +292 -0
  123. package/dist/server/btpsServer.js +827 -0
  124. package/dist/server/index.d.ts +11 -0
  125. package/dist/server/index.js +15 -0
  126. package/dist/server/libs/abstractRateLimiter.d.ts +10 -0
  127. package/dist/server/libs/abstractRateLimiter.js +15 -0
  128. package/dist/server/libs/artifactSizeGuard.d.ts +27 -0
  129. package/dist/server/libs/artifactSizeGuard.js +44 -0
  130. package/dist/server/libs/artifactTimeWindow.d.ts +24 -0
  131. package/dist/server/libs/artifactTimeWindow.js +30 -0
  132. package/dist/server/libs/btpsFactory.d.ts +29 -0
  133. package/dist/server/libs/btpsFactory.js +49 -0
  134. package/dist/server/libs/btpsLightweightFactory.d.ts +35 -0
  135. package/dist/server/libs/btpsLightweightFactory.js +37 -0
  136. package/dist/server/libs/btpsRegistry.d.ts +14 -0
  137. package/dist/server/libs/btpsRegistry.js +16 -0
  138. package/dist/server/libs/btpsSimpleMetricsTracker.d.ts +13 -0
  139. package/dist/server/libs/btpsSimpleMetricsTracker.js +21 -0
  140. package/dist/server/libs/btpsSimpleRateLimiter.d.ts +28 -0
  141. package/dist/server/libs/btpsSimpleRateLimiter.js +46 -0
  142. package/dist/server/libs/connectionTimeout.d.ts +16 -0
  143. package/dist/server/libs/connectionTimeout.js +14 -0
  144. package/dist/server/libs/defaultMiddleware.d.ts +8 -0
  145. package/dist/server/libs/defaultMiddleware.js +128 -0
  146. package/dist/server/libs/inFlightLimit.d.ts +18 -0
  147. package/dist/server/libs/inFlightLimit.js +17 -0
  148. package/dist/server/libs/index.d.ts +18 -0
  149. package/dist/server/libs/index.js +34 -0
  150. package/dist/server/libs/middlewareManager.js +126 -0
  151. package/dist/server/libs/type.d.ts +22 -0
  152. package/dist/server/libs/type.js +7 -0
  153. package/dist/server/types.d.ts +236 -0
  154. package/dist/server/types.js +7 -0
  155. package/package.json +126 -4
@@ -0,0 +1,272 @@
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 { CURRENCY_CODES } from "../constants/currency.js";
10
+ import { BTPS_FIELD_LIMITS } from "../constants/limits.js";
11
+ import { BtpSignatureSchema, identitySchema } from "./shared.js";
12
+ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId, referenceType } = BTPS_FIELD_LIMITS, codeSchema = (max) => z.string().max(max).regex(/^[a-z0-9_]+(:[a-z0-9_]+)?$/, "must be a bare or prefixed code"), decimalText = z.string().regex(/^-?\d+(\.\d+)?$/, "must be a decimal written as text"), sha256Hex = z.string().regex(/^[0-9a-f]{64}$/, "must be a SHA-256 in lowercase hex"), BtpAttachmentSchema = z.object({
13
+ content: z.string(),
14
+
15
+ type: z.enum(["application/pdf", "image/jpeg", "image/png"]),
16
+ filename: z.string().optional(),
17
+ size: z.number().int().nonnegative(),
18
+ sha256: sha256Hex
19
+ }), BtpMoneySchema = z.object({
20
+ amount: z.number().int().safe(),
21
+ currency: z.enum(CURRENCY_CODES)
22
+ }), BtpDocReferenceSchema = z.object({
23
+ type: codeSchema(referenceType),
24
+ from: identitySchema,
25
+ id: z.string().min(1).max(documentId),
26
+ sha256: sha256Hex
27
+ }), BtpStringQueryFilterSchema = z.object({
28
+ like: z.string().optional(),
29
+ in: z.array(z.string()).optional(),
30
+ eq: z.string().optional(),
31
+ ne: z.string().optional(),
32
+ notIn: z.array(z.string()).optional(),
33
+ notLike: z.string().optional()
34
+ }), BtpTrustReqDocSchema = z.object({
35
+ id: z.string().max(trustRequest.id),
36
+ name: z.string().max(trustRequest.name),
37
+ email: z.string().max(trustRequest.email).email(),
38
+ reason: z.string().max(trustRequest.reason),
39
+ phone: z.string().max(trustRequest.phone),
40
+ address: z.string().max(trustRequest.address).optional(),
41
+ logoUrl: z.string().max(trustRequest.logoUrl).url().optional(),
42
+ displayName: z.string().max(trustRequest.displayName).optional(),
43
+ websiteUrl: z.string().max(trustRequest.websiteUrl).url().optional(),
44
+ message: z.string().max(trustRequest.message).optional(),
45
+ expiresAt: z.string().datetime().optional(),
46
+ privacyType: z.enum(["unencrypted", "encrypted", "mixed"]).optional()
47
+ }), BtpTrustResDocSchema = z.object({
48
+ id: z.string().max(trustResponse.id),
49
+ decision: z.enum(["accepted", "rejected", "revoked", "blocked"]),
50
+ decidedAt: z.string().datetime(),
51
+ decidedBy: z.string().max(trustResponse.decidedBy),
52
+ expiresAt: z.string().datetime().optional(),
53
+ retryAfterDate: z.string().datetime().optional(),
54
+ message: z.string().max(trustResponse.message).optional(),
55
+ privacyType: z.enum(["unencrypted", "encrypted", "mixed"]).optional()
56
+ }), BtpLineItemsSchema = z.object({
57
+ columns: z.array(z.string()),
58
+
59
+ rows: z.array(z.record(z.union([z.string(), z.number().int().safe()])))
60
+ }), BtpIssuerSchema = z.object({
61
+ name: z.string(),
62
+ email: z.string().email().optional(),
63
+ phone: z.string().optional(),
64
+ address: z.string().optional(),
65
+
66
+ identifiers: z.record(z.string().regex(/^[a-z0-9_]+:[a-z0-9_]+$/), z.string()).optional()
67
+ }), BtpInvoiceDocSchema = z.object({
68
+ type: z.literal("invoice"),
69
+ title: z.string(),
70
+ id: z.string().max(documentId),
71
+
72
+ issuedAt: z.string().datetime(),
73
+ dueAt: z.string().datetime().optional(),
74
+ totalAmount: BtpMoneySchema,
75
+ lineItems: BtpLineItemsSchema,
76
+ issuer: BtpIssuerSchema.optional(),
77
+ paymentLink: z.object({
78
+ linkText: z.string(),
79
+ url: z.string().url()
80
+ }).optional(),
81
+ description: z.string().optional(),
82
+ attachments: z.array(BtpAttachmentSchema).optional(),
83
+
84
+ references: z.array(BtpDocReferenceSchema).optional(),
85
+ template: z.object({
86
+ name: z.string(),
87
+ data: z.record(z.unknown())
88
+ }).optional(),
89
+
90
+ metadata: z.record(z.unknown()).optional()
91
+ }).strict(), BtpPositiveMoneySchema = BtpMoneySchema.extend({
92
+ amount: z.number().int().safe().positive()
93
+ }), BtpReceiptDocSchema = BtpInvoiceDocSchema.omit({ dueAt: !0, paymentLink: !0 }).extend({
94
+ type: z.literal("receipt"),
95
+ lineItems: BtpLineItemsSchema.optional(),
96
+ payment: z.object({
97
+ amount: BtpPositiveMoneySchema,
98
+ paidAt: z.string().datetime(),
99
+
100
+ method: codeSchema(receipt.paymentMethod).optional(),
101
+ reference: z.string().max(receipt.paymentReference).optional()
102
+ })
103
+ }).strict(), payslipCode = codeSchema(payslip.code), BtpPayslipDocSchema = z.object({
104
+ type: z.literal("payslip"),
105
+ title: z.string(),
106
+ id: z.string().max(documentId),
107
+ issuedAt: z.string().datetime(),
108
+ issuer: BtpIssuerSchema.optional(),
109
+
110
+ employee: z.object({
111
+ name: z.string(),
112
+ employeeId: z.string().optional(),
113
+ payBasis: z.enum(["hourly", "salaried"]).optional()
114
+ }),
115
+ jurisdiction: z.string().regex(/^[A-Z]{2}$/, "must be an ISO 3166-1 alpha-2 code").optional(),
116
+ payPeriod: z.object({ start: z.string().datetime(), end: z.string().datetime() }).optional(),
117
+ payDate: z.string().datetime().optional(),
118
+ payRate: z.object({ amount: BtpMoneySchema, unit: payslipCode, asAt: z.string().datetime() }).optional(),
119
+ earnings: z.array(
120
+ z.object({
121
+ category: payslipCode,
122
+ description: z.string().optional(),
123
+ rate: decimalText.optional(),
124
+ rateUnit: payslipCode.optional(),
125
+ quantity: decimalText.optional(),
126
+ amount: BtpMoneySchema
127
+ })
128
+ ),
129
+ deductions: z.array(
130
+ z.object({
131
+ category: payslipCode,
132
+ description: z.string().optional(),
133
+ amount: BtpMoneySchema,
134
+ payee: z.object({ name: z.string(), accountRef: z.string().optional() }).optional()
135
+ })
136
+ ),
137
+
138
+ contributions: z.array(
139
+ z.object({
140
+ category: payslipCode.optional(),
141
+ amount: BtpMoneySchema,
142
+ fund: z.object({
143
+ name: z.string().optional(),
144
+ memberNumber: z.string().optional(),
145
+ accountRef: z.string().optional()
146
+ }).optional()
147
+ })
148
+ ),
149
+ leave: z.array(
150
+ z.object({
151
+ category: payslipCode,
152
+ description: z.string().optional(),
153
+ unit: payslipCode,
154
+
155
+ balance: decimalText,
156
+ accrued: decimalText.optional(),
157
+ taken: decimalText.optional()
158
+ })
159
+ ).optional(),
160
+ taxWithheld: BtpMoneySchema.optional(),
161
+ gross: BtpMoneySchema,
162
+ net: BtpMoneySchema,
163
+ yearToDate: z.record(BtpMoneySchema).optional(),
164
+ attachments: z.array(BtpAttachmentSchema).optional(),
165
+ references: z.array(BtpDocReferenceSchema).optional(),
166
+ metadata: z.record(z.unknown()).optional()
167
+ }).strict(), BtpLetterDocSchema = z.object({
168
+ type: z.literal("letter"),
169
+ title: z.string().max(letter.title),
170
+ id: z.string().max(documentId),
171
+ issuedAt: z.string().datetime(),
172
+ body: z.object({
173
+ format: z.enum(["text", "markdown"]),
174
+ content: z.string().max(letter.content)
175
+ }),
176
+ issuer: BtpIssuerSchema.optional(),
177
+ attachments: z.array(BtpAttachmentSchema).max(letter.attachments).optional(),
178
+ references: z.array(BtpDocReferenceSchema).max(letter.references).optional(),
179
+ metadata: z.record(z.unknown()).optional()
180
+ }).strict(), BtpDocumentSchema = z.discriminatedUnion("type", [
181
+ BtpInvoiceDocSchema,
182
+ BtpReceiptDocSchema,
183
+ BtpPayslipDocSchema,
184
+ BtpLetterDocSchema
185
+ ]), lifecycleEventFields = {
186
+ type: z.literal("lifecycle_event"),
187
+ id: z.string().uuid(),
188
+
189
+ occurredAt: z.string().datetime(),
190
+
191
+ document: BtpDocReferenceSchema.omit({ type: !0 }),
192
+
193
+ message: z.string().max(event.message).optional()
194
+ }, BtpEventAmountSchema = BtpMoneySchema.extend({
195
+ amount: z.number().int().safe().positive()
196
+ }), BtpLifecycleEventSchema = z.discriminatedUnion("eventType", [
197
+ z.object({ ...lifecycleEventFields, eventType: z.literal("paid") }).strict(),
198
+ z.object({
199
+ ...lifecycleEventFields,
200
+ eventType: z.literal("partially_paid"),
201
+ amount: BtpEventAmountSchema
202
+ }).strict(),
203
+ z.object({
204
+ ...lifecycleEventFields,
205
+ eventType: z.literal("disputed"),
206
+
207
+ reason: codeSchema(event.reason)
208
+ }).strict(),
209
+ z.object({ ...lifecycleEventFields, eventType: z.literal("refund_requested") }).strict(),
210
+ z.object({
211
+ ...lifecycleEventFields,
212
+ eventType: z.literal("refund"),
213
+ amount: BtpEventAmountSchema,
214
+ inReplyTo: z.string().uuid()
215
+
216
+ }).strict(),
217
+ z.object({
218
+ ...lifecycleEventFields,
219
+ eventType: z.literal("response"),
220
+ decision: z.enum(["accepted", "rejected"]),
221
+ inReplyTo: z.string().uuid(),
222
+
223
+
224
+ remainingDueDate: z.string().datetime().optional()
225
+ }).strict()
226
+ ]).refine(
227
+ (event2) => event2.eventType !== "response" || event2.remainingDueDate === void 0 || event2.decision === "accepted",
228
+ { message: "remainingDueDate is only on an accepted response", path: ["remainingDueDate"] }
229
+ ), BtpAuthReqDocSchema = z.object({
230
+ identity: identitySchema,
231
+ authToken: z.string(),
232
+ publicKey: z.string(),
233
+ agentInfo: z.record(z.union([z.string(), z.array(z.string())])).optional(),
234
+ keyProof: BtpSignatureSchema.optional()
235
+ }), BtpAuthResDocSchema = z.object({
236
+ agentId: z.string(),
237
+ refreshToken: z.string(),
238
+ expiresAt: z.string().datetime(),
239
+ decryptBy: identitySchema
240
+ }), BtpIdentityResDocSchema = z.object({
241
+ selector: z.string(),
242
+ publicKey: z.string(),
243
+ keyType: z.literal("rsa"),
244
+ version: z.string()
245
+ }), BtpAgentQueryDocSchema = z.object({
246
+ title: BtpStringQueryFilterSchema.optional(),
247
+ from: BtpStringQueryFilterSchema.optional(),
248
+ to: BtpStringQueryFilterSchema.optional()
249
+ }), BtpDocSchema = z.union([
250
+ BtpTrustReqDocSchema,
251
+ BtpTrustResDocSchema,
252
+ BtpDocumentSchema,
253
+ BtpLifecycleEventSchema
254
+ ]);
255
+ export {
256
+ BtpAgentQueryDocSchema,
257
+ BtpAttachmentSchema,
258
+ BtpAuthReqDocSchema,
259
+ BtpAuthResDocSchema,
260
+ BtpDocReferenceSchema,
261
+ BtpDocSchema,
262
+ BtpDocumentSchema,
263
+ BtpIdentityResDocSchema,
264
+ BtpInvoiceDocSchema,
265
+ BtpLetterDocSchema,
266
+ BtpLifecycleEventSchema,
267
+ BtpPayslipDocSchema,
268
+ BtpReceiptDocSchema,
269
+ BtpStringQueryFilterSchema,
270
+ BtpTrustReqDocSchema,
271
+ BtpTrustResDocSchema
272
+ };
@@ -0,0 +1,87 @@
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 { AGENT_ACTIONS_REQUIRING_DOCUMENT } from "../constants/index.js";
9
+ import {
10
+ BtpAgentMutationSchema,
11
+ BtpIdsPayloadSchema,
12
+ BtpAgentQuerySchema,
13
+ BtpAgentCreateSchema
14
+ } from "./schema.js";
15
+ import {
16
+ BtpAuthReqDocSchema,
17
+ BtpDocumentSchema,
18
+ BtpLifecycleEventSchema,
19
+ BtpTrustReqDocSchema,
20
+ BtpTrustResDocSchema
21
+ } from "./btpsDocsSchema.js";
22
+ const processBtpDocSchema = (bptArtifactType) => {
23
+ switch (bptArtifactType) {
24
+ case "TRUST_RES":
25
+ return BtpTrustResDocSchema;
26
+ case "TRUST_REQ":
27
+ return BtpTrustReqDocSchema;
28
+ case "BTPS_DOC":
29
+ return BtpDocumentSchema;
30
+ case "BTPS_EVENT":
31
+ return BtpLifecycleEventSchema;
32
+ default:
33
+ return null;
34
+ }
35
+ }, lifecycleEventEnvelopeProblem = (event, envelope) => {
36
+ if (event.id !== envelope.id) return "an event's id must be the id of the artifact carrying it";
37
+ if (event.document.from !== envelope.from && event.document.from !== envelope.to)
38
+ return "an event may only be about an invoice between its own sender and receiver";
39
+ }, decryptedDocumentProblem = (document, envelope) => {
40
+ const schema = processBtpDocSchema(envelope.type);
41
+ if (!schema) return;
42
+ const parsed = schema.safeParse(document);
43
+ if (!parsed.success) return "Document type does not match the artifact type";
44
+ if (envelope.type !== "BTPS_EVENT") return;
45
+ 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 });
47
+ }, processBtpDocSchemaForAgent = (actionType) => ({
48
+ "trust.request": BtpTrustReqDocSchema,
49
+ "trust.respond": BtpTrustResDocSchema,
50
+ "trust.update": BtpAgentMutationSchema,
51
+ "trust.delete": BtpIdsPayloadSchema,
52
+ "artifact.send": BtpDocumentSchema,
53
+ "event.send": BtpLifecycleEventSchema,
54
+ "auth.request": BtpAuthReqDocSchema,
55
+ "auth.refresh": BtpAuthReqDocSchema,
56
+ "inbox.fetch": BtpAgentQuerySchema,
57
+ "inbox.seen": BtpIdsPayloadSchema,
58
+ "inbox.delete": BtpIdsPayloadSchema,
59
+ "sentbox.fetch": BtpAgentQuerySchema,
60
+ "sentbox.delete": BtpIdsPayloadSchema,
61
+ "outbox.fetch": BtpAgentQuerySchema,
62
+ "outbox.cancel": BtpIdsPayloadSchema,
63
+ "draft.fetch": BtpAgentQuerySchema,
64
+ "draft.create": BtpAgentCreateSchema,
65
+ "draft.update": BtpAgentMutationSchema,
66
+ "draft.delete": BtpIdsPayloadSchema,
67
+ "trash.fetch": BtpAgentQuerySchema,
68
+ "trash.delete": BtpIdsPayloadSchema
69
+ })[actionType] || null, validateAgentDocument = (action, encryption, document) => {
70
+ if (AGENT_ACTIONS_REQUIRING_DOCUMENT.includes(
71
+ action
72
+ ) && !document || encryption && typeof document != "string" || encryption && action === "auth.request")
73
+ return !1;
74
+ if (document) {
75
+ const expectedSchema = processBtpDocSchemaForAgent(action);
76
+ if (expectedSchema && !expectedSchema.safeParse(document).success)
77
+ return !1;
78
+ }
79
+ return !0;
80
+ };
81
+ export {
82
+ decryptedDocumentProblem,
83
+ lifecycleEventEnvelopeProblem,
84
+ processBtpDocSchema,
85
+ processBtpDocSchemaForAgent,
86
+ validateAgentDocument
87
+ };
@@ -0,0 +1,86 @@
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 { BtpSignatureSchema, BtpEncryptionSchema } from "./schema.js";
10
+ import { identitySchema } from "./shared.js";
11
+ import { BtpAuthResDocSchema, BtpIdentityResDocSchema } from "./btpsDocsSchema.js";
12
+ import { BtpTransporterArtifactSchema } from "./artifacts/transporterSchema.js";
13
+ const BtpStatusSchema = z.object({
14
+ ok: z.boolean(),
15
+ code: z.number(),
16
+ message: z.string().optional(),
17
+ error: z.string().optional()
18
+ }), BtpDeliveryFailureDocSchema = z.object({
19
+ id: z.string(),
20
+ reason: z.string(),
21
+ failedAt: z.string().datetime(),
22
+ retryCount: z.number().optional(),
23
+ document: BtpTransporterArtifactSchema.optional(),
24
+ errorLog: z.any().optional(),
25
+
26
+ recipient: identitySchema,
27
+ transportArtifactId: z.string(),
28
+ agentArtifactId: z.string().optional()
29
+ }), BtpDeliveryFailureArtifactSchema = z.object({
30
+ id: z.string(),
31
+ issuedAt: z.string().datetime(),
32
+ document: BtpDeliveryFailureDocSchema,
33
+ type: z.literal("BTP_DELIVERY_FAILURE"),
34
+ from: identitySchema,
35
+ to: identitySchema
36
+ }), BtpQueryResultEntrySchema = z.object({
37
+ artifact: z.union([BtpTransporterArtifactSchema, BtpDeliveryFailureArtifactSchema]),
38
+ meta: z.object({
39
+ seen: z.boolean().optional(),
40
+ seenAt: z.string().datetime().optional()
41
+ }).catchall(z.unknown()).optional()
42
+ }), BtpQueryResultSchema = z.object({
43
+ results: z.array(BtpQueryResultEntrySchema),
44
+ cursor: z.string().optional(),
45
+ total: z.number().optional(),
46
+ hasNext: z.boolean().optional()
47
+ }), BtpServerResDocsSchema = z.union([
48
+ BtpAuthResDocSchema,
49
+ BtpQueryResultSchema,
50
+ BtpIdentityResDocSchema
51
+ ]), BtpServerResponseSchema = z.object({
52
+ version: z.string().regex(/^\d+\.\d+\.\d+$/, "Version must be in semantic versioning format (e.g., 1.0.0)"),
53
+ status: BtpStatusSchema,
54
+ id: z.string(),
55
+ issuedAt: z.string().datetime(),
56
+ type: z.enum(["btps_error", "btps_response"]),
57
+ reqId: z.string().optional(),
58
+ document: z.union([BtpServerResDocsSchema, z.string()]).optional(),
59
+ signature: BtpSignatureSchema.optional(),
60
+ encryption: BtpEncryptionSchema.optional(),
61
+ signedBy: identitySchema.optional(),
62
+ selector: z.string().optional()
63
+ }).superRefine((data, ctx) => {
64
+ data.signature && (data.signedBy || ctx.addIssue({
65
+ path: ["signedBy"],
66
+ code: z.ZodIssueCode.custom,
67
+ message: "signedBy is required when signature is present"
68
+ }), data.selector || ctx.addIssue({
69
+ path: ["selector"],
70
+ code: z.ZodIssueCode.custom,
71
+ message: "selector is required when signature is present"
72
+ })), data.encryption && typeof data.document != "string" && ctx.addIssue({
73
+ path: ["document"],
74
+ code: z.ZodIssueCode.custom,
75
+ message: "When encrypted, document must be a string"
76
+ });
77
+ });
78
+ export {
79
+ BtpDeliveryFailureArtifactSchema,
80
+ BtpDeliveryFailureDocSchema,
81
+ BtpQueryResultEntrySchema,
82
+ BtpQueryResultSchema,
83
+ BtpServerResDocsSchema,
84
+ BtpServerResponseSchema,
85
+ BtpStatusSchema
86
+ };
@@ -0,0 +1,70 @@
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 { AGENT_ACTIONS, TRANSPORTER_ACTIONS } from "../constants/index.js";
10
+ import { BtpAgentQueryDocSchema, BtpDocSchema } from "./btpsDocsSchema.js";
11
+ import { BtpSignatureSchema, identitySchema } from "./shared.js";
12
+ const BtpCryptoOptionsSchema = z.object({
13
+ signature: z.object({
14
+ algorithmHash: z.literal("sha256")
15
+ }).optional(),
16
+ encryption: z.object({
17
+ algorithm: z.literal("aes-256-gcm"),
18
+ mode: z.enum(["none", "standardEncrypt", "2faEncrypt"])
19
+ }).optional()
20
+ }), BtpsAgentActionTypeSchema = z.enum(AGENT_ACTIONS), BtpEncryptionSchema = z.object({
21
+ algorithm: z.literal("aes-256-gcm"),
22
+ encryptedKey: z.string(),
23
+ iv: z.string(),
24
+ type: z.enum(["none", "standardEncrypt", "2faEncrypt"]),
25
+ authTag: z.string()
26
+ }), BtpDelegationSchema = z.object({
27
+ agentId: z.string(),
28
+ agentPubKey: z.string(),
29
+ signedBy: identitySchema,
30
+ signature: BtpSignatureSchema,
31
+ issuedAt: z.string().datetime(),
32
+ attestation: z.object({
33
+ signedBy: identitySchema,
34
+ issuedAt: z.string().datetime(),
35
+ signature: BtpSignatureSchema,
36
+ selector: z.string()
37
+ }).optional(),
38
+ selector: z.string()
39
+ }), BtpAgentQuerySchema = z.object({
40
+ since: z.string().datetime().optional(),
41
+ until: z.string().datetime().optional(),
42
+ limit: z.number().optional(),
43
+ cursor: z.string().optional(),
44
+ query: BtpAgentQueryDocSchema.optional(),
45
+ sort: z.enum(["asc", "desc"]).optional()
46
+ }).refine(
47
+ (data) => data.since !== void 0 || data.until !== void 0 || data.limit !== void 0 || data.cursor !== void 0 || data.query !== void 0 || data.sort !== void 0,
48
+ {
49
+ message: "At least one query field must be provided"
50
+ }
51
+ ), BtpAgentMutationSchema = z.object({
52
+ id: z.string(),
53
+ document: BtpDocSchema
54
+ }), BtpAgentCreateSchema = z.object({
55
+ type: z.enum(TRANSPORTER_ACTIONS),
56
+ document: BtpDocSchema
57
+ }), BtpIdsPayloadSchema = z.object({
58
+ ids: z.array(z.string())
59
+ });
60
+ export {
61
+ BtpAgentCreateSchema,
62
+ BtpAgentMutationSchema,
63
+ BtpAgentQuerySchema,
64
+ BtpCryptoOptionsSchema,
65
+ BtpDelegationSchema,
66
+ BtpEncryptionSchema,
67
+ BtpIdsPayloadSchema,
68
+ BtpSignatureSchema,
69
+ BtpsAgentActionTypeSchema
70
+ };
@@ -0,0 +1,18 @@
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 { isValidIdentity } from "../../utils/identity.js";
10
+ const identitySchema = z.string().regex(/^\S+\$\S+\.\S+$/, "From field must match pattern: {username}${domain}").refine(isValidIdentity, 'An identity has one separator and no ":"'), BtpSignatureSchema = z.object({
11
+ algorithmHash: z.literal("sha256"),
12
+ value: z.string(),
13
+ fingerprint: z.string()
14
+ });
15
+ export {
16
+ BtpSignatureSchema,
17
+ identitySchema
18
+ };