@btps/sdk 1.1.2 → 1.1.3

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.
@@ -9,7 +9,23 @@ import { z } from "zod";
9
9
  import { CURRENCY_CODES } from "../constants/currency.js";
10
10
  import { BTPS_FIELD_LIMITS } from "../constants/limits.js";
11
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({
12
+ import { boundedArray, boundedRecord } from "./bounded.js";
13
+ const {
14
+ trustRequest,
15
+ trustResponse,
16
+ event,
17
+ receipt,
18
+ payslip,
19
+ letter,
20
+ attachments,
21
+ references,
22
+ lineItems,
23
+ query,
24
+ agentInfoValues,
25
+ recordKeys,
26
+ documentId,
27
+ referenceType
28
+ } = BTPS_FIELD_LIMITS, metadataSchema = boundedRecord(z.unknown(), recordKeys), 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
29
  content: z.string(),
14
30
 
15
31
  type: z.enum(["application/pdf", "image/jpeg", "image/png"]),
@@ -26,10 +42,10 @@ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId
26
42
  sha256: sha256Hex
27
43
  }), BtpStringQueryFilterSchema = z.object({
28
44
  like: z.string().optional(),
29
- in: z.array(z.string()).optional(),
45
+ in: boundedArray(z.string(), query.in).optional(),
30
46
  eq: z.string().optional(),
31
47
  ne: z.string().optional(),
32
- notIn: z.array(z.string()).optional(),
48
+ notIn: boundedArray(z.string(), query.notIn).optional(),
33
49
  notLike: z.string().optional()
34
50
  }), BtpTrustReqDocSchema = z.object({
35
51
  id: z.string().max(trustRequest.id),
@@ -54,16 +70,23 @@ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId
54
70
  message: z.string().max(trustResponse.message).optional(),
55
71
  privacyType: z.enum(["unencrypted", "encrypted", "mixed"]).optional()
56
72
  }), BtpLineItemsSchema = z.object({
57
- columns: z.array(z.string()),
73
+ columns: boundedArray(z.string(), lineItems.columns),
58
74
 
59
- rows: z.array(z.record(z.union([z.string(), z.number().int().safe()])))
75
+ rows: boundedArray(
76
+ boundedRecord(z.union([z.string(), z.number().int().safe()]), lineItems.columns),
77
+ lineItems.rows
78
+ )
60
79
  }), BtpIssuerSchema = z.object({
61
80
  name: z.string(),
62
81
  email: z.string().email().optional(),
63
82
  phone: z.string().optional(),
64
83
  address: z.string().optional(),
65
84
 
66
- identifiers: z.record(z.string().regex(/^[a-z0-9_]+:[a-z0-9_]+$/), z.string()).optional()
85
+ identifiers: boundedRecord(
86
+ z.string(),
87
+ recordKeys,
88
+ z.string().regex(/^[a-z0-9_]+:[a-z0-9_]+$/)
89
+ ).optional()
67
90
  }), BtpInvoiceDocSchema = z.object({
68
91
  type: z.literal("invoice"),
69
92
  title: z.string(),
@@ -79,15 +102,14 @@ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId
79
102
  url: z.string().url()
80
103
  }).optional(),
81
104
  description: z.string().optional(),
82
- attachments: z.array(BtpAttachmentSchema).optional(),
105
+ attachments: boundedArray(BtpAttachmentSchema, attachments).optional(),
83
106
 
84
- references: z.array(BtpDocReferenceSchema).optional(),
107
+ references: boundedArray(BtpDocReferenceSchema, references).optional(),
85
108
  template: z.object({
86
109
  name: z.string(),
87
- data: z.record(z.unknown())
110
+ data: boundedRecord(z.unknown(), recordKeys)
88
111
  }).optional(),
89
-
90
- metadata: z.record(z.unknown()).optional()
112
+ metadata: metadataSchema.optional()
91
113
  }).strict(), BtpPositiveMoneySchema = BtpMoneySchema.extend({
92
114
  amount: z.number().int().safe().positive()
93
115
  }), BtpReceiptDocSchema = BtpInvoiceDocSchema.omit({ dueAt: !0, paymentLink: !0 }).extend({
@@ -116,7 +138,7 @@ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId
116
138
  payPeriod: z.object({ start: z.string().datetime(), end: z.string().datetime() }).optional(),
117
139
  payDate: z.string().datetime().optional(),
118
140
  payRate: z.object({ amount: BtpMoneySchema, unit: payslipCode, asAt: z.string().datetime() }).optional(),
119
- earnings: z.array(
141
+ earnings: boundedArray(
120
142
  z.object({
121
143
  category: payslipCode,
122
144
  description: z.string().optional(),
@@ -124,18 +146,20 @@ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId
124
146
  rateUnit: payslipCode.optional(),
125
147
  quantity: decimalText.optional(),
126
148
  amount: BtpMoneySchema
127
- })
149
+ }),
150
+ payslip.earnings
128
151
  ),
129
- deductions: z.array(
152
+ deductions: boundedArray(
130
153
  z.object({
131
154
  category: payslipCode,
132
155
  description: z.string().optional(),
133
156
  amount: BtpMoneySchema,
134
157
  payee: z.object({ name: z.string(), accountRef: z.string().optional() }).optional()
135
- })
158
+ }),
159
+ payslip.deductions
136
160
  ),
137
161
 
138
- contributions: z.array(
162
+ contributions: boundedArray(
139
163
  z.object({
140
164
  category: payslipCode.optional(),
141
165
  amount: BtpMoneySchema,
@@ -144,9 +168,10 @@ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId
144
168
  memberNumber: z.string().optional(),
145
169
  accountRef: z.string().optional()
146
170
  }).optional()
147
- })
171
+ }),
172
+ payslip.contributions
148
173
  ),
149
- leave: z.array(
174
+ leave: boundedArray(
150
175
  z.object({
151
176
  category: payslipCode,
152
177
  description: z.string().optional(),
@@ -155,15 +180,16 @@ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId
155
180
  balance: decimalText,
156
181
  accrued: decimalText.optional(),
157
182
  taken: decimalText.optional()
158
- })
183
+ }),
184
+ payslip.leave
159
185
  ).optional(),
160
186
  taxWithheld: BtpMoneySchema.optional(),
161
187
  gross: BtpMoneySchema,
162
188
  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()
189
+ yearToDate: boundedRecord(BtpMoneySchema, recordKeys).optional(),
190
+ attachments: boundedArray(BtpAttachmentSchema, attachments).optional(),
191
+ references: boundedArray(BtpDocReferenceSchema, references).optional(),
192
+ metadata: metadataSchema.optional()
167
193
  }).strict(), BtpLetterDocSchema = z.object({
168
194
  type: z.literal("letter"),
169
195
  title: z.string().max(letter.title),
@@ -174,9 +200,9 @@ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId
174
200
  content: z.string().max(letter.content)
175
201
  }),
176
202
  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()
203
+ attachments: boundedArray(BtpAttachmentSchema, letter.attachments).optional(),
204
+ references: boundedArray(BtpDocReferenceSchema, letter.references).optional(),
205
+ metadata: metadataSchema.optional()
180
206
  }).strict(), BtpDocumentSchema = z.discriminatedUnion("type", [
181
207
  BtpInvoiceDocSchema,
182
208
  BtpReceiptDocSchema,
@@ -230,7 +256,10 @@ const { trustRequest, trustResponse, event, receipt, payslip, letter, documentId
230
256
  identity: identitySchema,
231
257
  authToken: z.string(),
232
258
  publicKey: z.string(),
233
- agentInfo: z.record(z.union([z.string(), z.array(z.string())])).optional(),
259
+ agentInfo: boundedRecord(
260
+ z.union([z.string(), boundedArray(z.string(), agentInfoValues)]),
261
+ recordKeys
262
+ ).optional(),
234
263
  keyProof: BtpSignatureSchema.optional()
235
264
  }), BtpAuthResDocSchema = z.object({
236
265
  agentId: z.string(),
@@ -10,7 +10,9 @@ import { BtpSignatureSchema, BtpEncryptionSchema } from "./schema.js";
10
10
  import { identitySchema } from "./shared.js";
11
11
  import { BtpAuthResDocSchema, BtpIdentityResDocSchema } from "./btpsDocsSchema.js";
12
12
  import { BtpTransporterArtifactSchema } from "./artifacts/transporterSchema.js";
13
- const BtpStatusSchema = z.object({
13
+ import { boundedArray, boundedRecord } from "./bounded.js";
14
+ import { BTPS_FIELD_LIMITS } from "../constants/limits.js";
15
+ const { query, trustRecord, recordKeys } = BTPS_FIELD_LIMITS, BtpStatusSchema = z.object({
14
16
  ok: z.boolean(),
15
17
  code: z.number(),
16
18
  message: z.string().optional(),
@@ -33,14 +35,44 @@ const BtpStatusSchema = z.object({
33
35
  type: z.literal("BTP_DELIVERY_FAILURE"),
34
36
  from: identitySchema,
35
37
  to: identitySchema
38
+ }), BtpTrustRecordSchema = z.object({
39
+ id: z.string(),
40
+ createdAt: z.string().datetime(),
41
+ senderId: identitySchema,
42
+ receiverId: identitySchema,
43
+ status: z.enum(["accepted", "rejected", "revoked", "pending", "blocked"]),
44
+
45
+ decidedBy: z.string(),
46
+ decidedAt: z.union([z.string().datetime(), z.literal("")]),
47
+ expiresAt: z.string().datetime().optional(),
48
+ publicKeyBase64: z.string(),
49
+ publicKeyFingerprint: z.string(),
50
+ keyHistory: boundedArray(
51
+ z.object({
52
+ fingerprint: z.string(),
53
+ firstSeen: z.string().datetime(),
54
+ lastSeen: z.string().datetime()
55
+ }),
56
+ trustRecord.keyHistory
57
+ ),
58
+ privacyType: z.enum(["unencrypted", "encrypted", "mixed"]),
59
+ retryAfterDate: z.string().datetime().optional(),
60
+ metadata: boundedRecord(z.unknown(), recordKeys).optional()
61
+ }).refine((record) => record.status === "pending" || record.decidedAt !== "", {
62
+ message: "only a pending trust has no decidedAt",
63
+ path: ["decidedAt"]
36
64
  }), BtpQueryResultEntrySchema = z.object({
37
- artifact: z.union([BtpTransporterArtifactSchema, BtpDeliveryFailureArtifactSchema]),
65
+ artifact: z.union([
66
+ BtpTransporterArtifactSchema,
67
+ BtpDeliveryFailureArtifactSchema,
68
+ BtpTrustRecordSchema
69
+ ]),
38
70
  meta: z.object({
39
71
  seen: z.boolean().optional(),
40
72
  seenAt: z.string().datetime().optional()
41
73
  }).catchall(z.unknown()).optional()
42
74
  }), BtpQueryResultSchema = z.object({
43
- results: z.array(BtpQueryResultEntrySchema),
75
+ results: boundedArray(BtpQueryResultEntrySchema, query.results),
44
76
  cursor: z.string().optional(),
45
77
  total: z.number().optional(),
46
78
  hasNext: z.boolean().optional()
@@ -82,5 +114,6 @@ export {
82
114
  BtpQueryResultSchema,
83
115
  BtpServerResDocsSchema,
84
116
  BtpServerResponseSchema,
85
- BtpStatusSchema
117
+ BtpStatusSchema,
118
+ BtpTrustRecordSchema
86
119
  };
@@ -9,6 +9,8 @@ import { z } from "zod";
9
9
  import { AGENT_ACTIONS, TRANSPORTER_ACTIONS } from "../constants/index.js";
10
10
  import { BtpAgentQueryDocSchema, BtpDocSchema } from "./btpsDocsSchema.js";
11
11
  import { BtpSignatureSchema, identitySchema } from "./shared.js";
12
+ import { boundedArray } from "./bounded.js";
13
+ import { BTPS_FIELD_LIMITS } from "../constants/limits.js";
12
14
  const BtpCryptoOptionsSchema = z.object({
13
15
  signature: z.object({
14
16
  algorithmHash: z.literal("sha256")
@@ -55,7 +57,7 @@ const BtpCryptoOptionsSchema = z.object({
55
57
  type: z.enum(TRANSPORTER_ACTIONS),
56
58
  document: BtpDocSchema
57
59
  }), BtpIdsPayloadSchema = z.object({
58
- ids: z.array(z.string())
60
+ ids: boundedArray(z.string(), BTPS_FIELD_LIMITS.ids)
59
61
  });
60
62
  export {
61
63
  BtpAgentCreateSchema,
@@ -232,7 +232,8 @@ export declare class BtpsServer {
232
232
  *
233
233
  * @param error The encountered error
234
234
  * @param socket The TLS socket associated with the connection
235
- * @param action 'destroy' (the default) tears the socket down at once; 'end' sends the error and closes gently
235
+ * @param action 'destroy' (the default) tears the socket down at once; 'end' sends the error and closes gently;
236
+ * 'answer' sends the error and leaves the connection open
236
237
  */
237
238
  private handleOnSocketError;
238
239
  /**
@@ -160,14 +160,15 @@ class BtpsServer {
160
160
  errorReq.error = error, this.handleOnSocketError(error, { req: errorReq, res: resCtx }, "end");
161
161
  });
162
162
  socket.pipe(sizeGuard);
163
- const stream = sizeGuard.pipe(split2());
164
- let fromIdentity, toIdentity;
165
- const identityRef = {
166
- update: (to, from) => {
167
- toIdentity = to, fromIdentity = from;
168
- },
169
- get: () => ({ to: toIdentity, from: fromIdentity })
170
- }, createContexts = () => {
163
+ const stream = sizeGuard.pipe(split2()), createIdentityRef = () => {
164
+ let toIdentity, fromIdentity;
165
+ return {
166
+ update: (to, from) => {
167
+ toIdentity = to, fromIdentity = from;
168
+ },
169
+ get: () => ({ to: toIdentity, from: fromIdentity })
170
+ };
171
+ }, connectionIdentity = createIdentityRef(), createContexts = (identityRef = connectionIdentity) => {
171
172
  const context = {
172
173
  socket,
173
174
  remoteAddress: ipAddress,
@@ -196,7 +197,7 @@ class BtpsServer {
196
197
  let inFlight = 0;
197
198
  stream.on("data", async (line) => {
198
199
  if (!line.trim()) return;
199
- const { reqCtx: parseReq, resCtx: parseRes } = createContexts();
200
+ const lineIdentity = createIdentityRef(), { reqCtx: parseReq, resCtx: parseRes } = createContexts(lineIdentity);
200
201
  parseReq.rawPacket = line, inFlight++, inFlight >= this.maxInFlightPerConnection && stream.pause();
201
202
  try {
202
203
  const beforeParseMiddleware = this.middlewareManager.getMiddleware("before", "parsing");
@@ -207,7 +208,9 @@ class BtpsServer {
207
208
  ))
208
209
  return;
209
210
  const { data, error } = this._parseAndValidateArtifact(line), parseError = error ? error === "VALIDATION" ? BTP_ERROR_VALIDATION : BTP_ERROR_INVALID_JSON : void 0, parseErrException = parseError ? new BTPErrorException(parseError) : void 0;
210
- if (parseRes.reqId = data?.artifact?.id, parseRes.data = data, parseRes.error = parseErrException, parseReq.data = data, parseReq.error = parseErrException, parseReq.getIdentity = identityRef.get, await this.updateIdentityInfo(data, identityRef, ipAddress), await this.executeMiddleware(
211
+ parseRes.reqId = data?.artifact?.id, parseRes.data = data, parseRes.error = parseErrException, parseReq.data = data, parseReq.error = parseErrException;
212
+ const { to, from } = await this.updateIdentityInfo(data, lineIdentity, ipAddress);
213
+ if (connectionIdentity.update(to, from), await this.executeMiddleware(
211
214
  this.middlewareManager.getMiddleware("after", "parsing"),
212
215
  parseReq,
213
216
  parseRes
@@ -227,12 +230,12 @@ class BtpsServer {
227
230
  parseRes.reqId
228
231
  );
229
232
  if (data.type === "control")
230
- return this.handleControl(data.artifact, {
233
+ return await this.handleControl(data.artifact, {
231
234
  req: parseReq,
232
235
  res: parseRes
233
236
  });
234
237
  if (data.type === "identityLookup")
235
- return this.handleIdentityLookup(data.artifact, {
238
+ return await this.handleIdentityLookup(data.artifact, {
236
239
  req: parseReq,
237
240
  res: parseRes
238
241
  });
@@ -246,7 +249,7 @@ class BtpsServer {
246
249
  req: errorReq,
247
250
  res: parseRes
248
251
  },
249
- "end"
252
+ "answer"
250
253
  );
251
254
  } finally {
252
255
  inFlight--, stream.isPaused() && !stream.destroyed && stream.resume();
@@ -738,7 +741,7 @@ class BtpsServer {
738
741
  this.middlewareManager.getMiddleware("before", "onError"),
739
742
  req,
740
743
  res
741
- ), this.onError?.(error), this.sendBtpsError(req.socket, error, res.reqId, action), action === "destroy" && !req.socket.destroyed && req.socket.destroy(), await this.executeMiddleware(
744
+ ), this.onError?.(error), this.sendBtpsError(req.socket, error, res.reqId, action === "answer" ? void 0 : action), action === "destroy" && !req.socket.destroyed && req.socket.destroy(), await this.executeMiddleware(
742
745
  this.middlewareManager.getMiddleware("after", "onError"),
743
746
  req,
744
747
  res
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@btps/sdk",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "description": "The reference implementation of BTPS, the Billing Trust Protocol Secure: signed, encrypted, trust-first delivery of invoices and documents between organisations.",
5
5
  "keywords": [
6
6
  "btps",