@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
@@ -0,0 +1,29 @@
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 type { BTPAgreementAnswers } from '../../core/trust/types.js';
8
+ import type { MiddlewareDefinition } from '../types.js';
9
+ /**
10
+ * The originator's platform's own record of an agreement, by the copy an
11
+ * answer names: its signers, how they answer, and the answers taken so far.
12
+ * Undefined when `relatesTo` is no agreement copy it sent to `signer`.
13
+ */
14
+ export type BTPAgreementAnswersLookup = (query: {
15
+ relatesTo: string;
16
+ signer: string;
17
+ originator: string;
18
+ }) => Promise<BTPAgreementAnswers | undefined>;
19
+ /**
20
+ * Since 1.2: middleware that refuses, in flight, an agreement's answer that is
21
+ * not its sender's turn (`agreementTurnProblem`): `BTP_ERROR_AGREEMENT_ORDER`,
22
+ * the broken rule in its message. It needs no decryption, so it works the same
23
+ * for an encrypted answer. An event about anything but an agreement copy passes.
24
+ * What needs the opened statement is the platform's after opening:
25
+ * `agreementStatementProblem`.
26
+ */
27
+ export declare const agreementOrderCheck: (lookups: {
28
+ answers: BTPAgreementAnswersLookup;
29
+ }) => MiddlewareDefinition<"after", "trustVerification">;
@@ -0,0 +1,29 @@
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 { BTP_ERROR_AGREEMENT_ORDER } from "../../core/error/constant.js";
9
+ import { agreementTurnProblem } from "../../core/trust/agreements.js";
10
+ const agreementOrderCheck = (lookups) => ({
11
+ phase: "after",
12
+ step: "trustVerification",
13
+ config: { name: "agreement-order-check" },
14
+ handler: async (req, res, next) => {
15
+ const { data } = req;
16
+ if (!req.isTrusted || data.type !== "transporter" || data.artifact.type !== "BTPS_EVENT")
17
+ return next();
18
+ const { from, to, relatesTo } = data.artifact;
19
+ if (relatesTo === void 0) return next();
20
+ const held = await lookups.answers({ relatesTo, signer: from, originator: to }), problem = held && agreementTurnProblem(from, held);
21
+ return problem ? res.sendError({
22
+ ...BTP_ERROR_AGREEMENT_ORDER,
23
+ message: `${BTP_ERROR_AGREEMENT_ORDER.message}: ${problem}`
24
+ }) : next();
25
+ }
26
+ });
27
+ export {
28
+ agreementOrderCheck
29
+ };
@@ -5,8 +5,8 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
  import { BTPErrorException } from '../../core/error/index.js';
8
- /** How far a server lets an artifact's `issuedAt` be from its own clock unless it sets `maxArtifactAgeSeconds`: 5 minutes. */
9
- export declare const DEFAULT_MAX_ARTIFACT_AGE_SECONDS = 300;
8
+ import { DEFAULT_MAX_ARTIFACT_AGE_SECONDS } from '../../core/server/constants/btps-protocol.js';
9
+ export { DEFAULT_MAX_ARTIFACT_AGE_SECONDS };
10
10
  /** The smallest time window a server may set: 1 minute. */
11
11
  export declare const MIN_MAX_ARTIFACT_AGE_SECONDS = 60;
12
12
  /**
@@ -7,7 +7,8 @@
7
7
 
8
8
  import { BTPErrorException } from "../../core/error/index.js";
9
9
  import { BTP_ERROR_ARTIFACT_TIME_WINDOW } from "../../core/error/constant.js";
10
- const DEFAULT_MAX_ARTIFACT_AGE_SECONDS = 300, MIN_MAX_ARTIFACT_AGE_SECONDS = 60, resolveMaxArtifactAgeSeconds = (configured) => configured === void 0 ? DEFAULT_MAX_ARTIFACT_AGE_SECONDS : !Number.isFinite(configured) || configured <= 0 ? (console.warn(
10
+ import { DEFAULT_MAX_ARTIFACT_AGE_SECONDS } from "../../core/server/constants/btps-protocol.js";
11
+ const MIN_MAX_ARTIFACT_AGE_SECONDS = 60, resolveMaxArtifactAgeSeconds = (configured) => configured === void 0 ? DEFAULT_MAX_ARTIFACT_AGE_SECONDS : !Number.isFinite(configured) || configured <= 0 ? (console.warn(
11
12
  `[BtpsServer] maxArtifactAgeSeconds ${configured} is not a usable time; using the default ${DEFAULT_MAX_ARTIFACT_AGE_SECONDS} seconds`
12
13
  ), DEFAULT_MAX_ARTIFACT_AGE_SECONDS) : configured < MIN_MAX_ARTIFACT_AGE_SECONDS ? (console.warn(
13
14
  `[BtpsServer] maxArtifactAgeSeconds ${configured} is below the ${MIN_MAX_ARTIFACT_AGE_SECONDS} second minimum; using ${MIN_MAX_ARTIFACT_AGE_SECONDS} seconds`
@@ -0,0 +1,27 @@
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 type { MiddlewareDefinition } from '../types.js';
8
+ /**
9
+ * The provider's own limit, asked once for each request: `true` takes it,
10
+ * `{ retryAfter }` refuses it, in whole seconds until it may ask again.
11
+ */
12
+ export type BTPDetailsRequestAllowance = (request: {
13
+ from: string;
14
+ to: string;
15
+ names: string[];
16
+ }) => true | {
17
+ retryAfter: number;
18
+ } | Promise<true | {
19
+ retryAfter: number;
20
+ }>;
21
+ /**
22
+ * Since 1.2: middleware that refuses, in flight, a `DETAILS_REQ` over the
23
+ * provider's own limit: `BTP_ERROR_DETAILS_RATE_LIMITED`, telling the asker in
24
+ * `status.retryAfter` how many seconds to wait. Add it after every other
25
+ * check, so the provider counts only requests that are taken.
26
+ */
27
+ export declare const detailsRequestLimit: (allow: BTPDetailsRequestAllowance) => MiddlewareDefinition<"after", "trustVerification">;
@@ -0,0 +1,28 @@
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 { BTPErrorException } from "../../core/error/index.js";
9
+ import { BTP_ERROR_DETAILS_RATE_LIMITED } from "../../core/error/constant.js";
10
+ const detailsRequestLimit = (allow) => ({
11
+ phase: "after",
12
+ step: "trustVerification",
13
+ config: { name: "details-request-limit" },
14
+ handler: async (req, res, next) => {
15
+ const { data } = req;
16
+ if (!req.isTrusted || data.type !== "transporter" || data.artifact.type !== "DETAILS_REQ")
17
+ return next();
18
+ const { from, to, details = [] } = data.artifact, allowed = await allow({ from, to, names: [...details] });
19
+ return allowed !== !0 ? res.sendError(
20
+ new BTPErrorException(BTP_ERROR_DETAILS_RATE_LIMITED, {
21
+ meta: { retryAfter: allowed.retryAfter }
22
+ })
23
+ ) : next();
24
+ }
25
+ });
26
+ export {
27
+ detailsRequestLimit
28
+ };
@@ -0,0 +1,27 @@
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 { type BTPDetailsEnvelope } from '../../core/trust/permissions.js';
8
+ import type { MiddlewareDefinition } from '../types.js';
9
+ /**
10
+ * The envelope of the artifact with this id that passed between these two
11
+ * identities, as the platform recorded it, or undefined when it holds none.
12
+ */
13
+ export type BTPArtifactLookup = (query: {
14
+ artifactId: string;
15
+ from: string;
16
+ to: string;
17
+ }) => Promise<BTPDetailsEnvelope | undefined>;
18
+ /**
19
+ * Since 1.2: middleware that refuses, in flight, a `DETAILS_RES` that does not
20
+ * answer a `DETAILS_REQ` its receiver sent to its sender, or names what was
21
+ * not asked for (`detailsRequestRefusal`): `BTP_ERROR_PERMISSION`, the reason
22
+ * in its message. It reads only envelopes, so it works the same for an
23
+ * encrypted response, arriving or carried by a device's `artifact.send`.
24
+ */
25
+ export declare const detailsResponseCheck: (lookups: {
26
+ getArtifact: BTPArtifactLookup;
27
+ }) => MiddlewareDefinition<"after", "trustVerification">;
@@ -0,0 +1,27 @@
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 { detailsRequestRefusal } from "../../core/trust/permissions.js";
9
+ const detailsResponseCheck = (lookups) => ({
10
+ phase: "after",
11
+ step: "trustVerification",
12
+ config: { name: "details-response-check" },
13
+ handler: async (req, res, next) => {
14
+ const { data } = req;
15
+ if (!req.isTrusted) return next();
16
+ const response = data.type === "transporter" ? data.artifact : data.artifact.document;
17
+ if (response?.type !== "DETAILS_RES") return next();
18
+ const { relatesTo = "", from, to } = response, sentRequest = await lookups.getArtifact({ artifactId: relatesTo, from: to, to: from }), refusal = detailsRequestRefusal(response, sentRequest);
19
+ return refusal ? res.sendError({
20
+ ...refusal.error,
21
+ message: `${refusal.error.message}: ${refusal.problem}`
22
+ }) : next();
23
+ }
24
+ });
25
+ export {
26
+ detailsResponseCheck
27
+ };
@@ -0,0 +1,31 @@
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 type { BTPEventFacts } from '../../core/trust/types.js';
8
+ import type { MiddlewareDefinition } from '../types.js';
9
+ /**
10
+ * What the platform holds of the lifecycle event with this id between these
11
+ * two identities, in either direction, with the invoice it is about, or
12
+ * undefined when it holds none.
13
+ */
14
+ export type BTPEventLookup = (query: {
15
+ id: string;
16
+ from: string;
17
+ to: string;
18
+ }) => Promise<BTPEventFacts | undefined>;
19
+ /**
20
+ * Since 1.2: middleware that refuses, in flight, an event whose chain is wrong
21
+ * (`lifecycleEventChainProblem`): `BTP_ERROR_EVENT_CHAIN`, the broken rule in
22
+ * its message. With `getEvent`, a `withdrawn` must take back the payer's own
23
+ * open proposal about the same invoice, and a `follows` must name a
24
+ * `withdrawn` about it; without it, only that the payer, never the invoice's
25
+ * issuer, withdraws or proposes again. It reads the event, so an encrypted
26
+ * one passes: its platform checks it with `lifecycleEventChainProblem` once
27
+ * opened.
28
+ */
29
+ export declare const eventChainCheck: (lookups?: {
30
+ getEvent?: BTPEventLookup;
31
+ }) => MiddlewareDefinition<"after", "trustVerification">;
@@ -0,0 +1,39 @@
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 { BTP_ERROR_EVENT_CHAIN } from "../../core/error/constant.js";
9
+ import { BtpLifecycleEventSchema } from "../../core/server/schemas/btpsDocsSchema.js";
10
+ import {
11
+ lifecycleEventChainProblem,
12
+ lifecycleEventChainReference,
13
+ lifecycleEventSenderProblem
14
+ } from "../../core/server/schemas/helpers.js";
15
+ const eventChainCheck = (lookups = {}) => ({
16
+ phase: "after",
17
+ step: "trustVerification",
18
+ config: { name: "event-chain-check" },
19
+ handler: async (req, res, next) => {
20
+ const { data } = req;
21
+ if (!req.isTrusted || data.type !== "transporter" || data.artifact.type !== "BTPS_EVENT" || data.artifact.encryption) return next();
22
+ const parsed = BtpLifecycleEventSchema.safeParse(data.artifact.document);
23
+ if (!parsed.success) return next();
24
+ const named = lifecycleEventChainReference(parsed.data);
25
+ if (named === void 0) return next();
26
+ const { from, to } = data.artifact, problem = lookups.getEvent ? lifecycleEventChainProblem(
27
+ parsed.data,
28
+ { from },
29
+ await lookups.getEvent({ id: named, from, to })
30
+ ) : lifecycleEventSenderProblem(parsed.data, { from });
31
+ return problem ? res.sendError({
32
+ ...BTP_ERROR_EVENT_CHAIN,
33
+ message: `${BTP_ERROR_EVENT_CHAIN.message}: ${problem}`
34
+ }) : next();
35
+ }
36
+ });
37
+ export {
38
+ eventChainCheck
39
+ };
@@ -16,3 +16,13 @@ export declare const MIN_MAX_IN_FLIGHT_PER_CONNECTION = 1;
16
16
  * small) or the default (when not a whole number).
17
17
  */
18
18
  export declare const resolveMaxInFlightPerConnection: (configured: number | undefined) => number;
19
+ /** Since 1.2: how many unreadable lines in a row one connection may send unless the server sets `maxConsecutiveInvalidLines`. */
20
+ export declare const DEFAULT_MAX_CONSECUTIVE_INVALID_LINES = 10;
21
+ /**
22
+ * The number a server uses. It answers that many lines in a row it cannot
23
+ * read, then answers the last and ends the connection: a sender that sends
24
+ * only what cannot be read gets no more answers made for it, signed or not.
25
+ * A value it cannot use is warned about and replaced by 1 (when too small) or
26
+ * the default (when not a whole number).
27
+ */
28
+ export declare const resolveMaxConsecutiveInvalidLines: (configured: number | undefined) => number;
@@ -9,9 +9,15 @@ const DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION = 32, MIN_MAX_IN_FLIGHT_PER_CONNECTIO
9
9
  `[BtpsServer] maxInFlightPerConnection ${configured} is below the minimum 1; using 1`
10
10
  ), 1) : configured : (console.warn(
11
11
  `[BtpsServer] maxInFlightPerConnection ${configured} is not a whole number; using the default 32`
12
- ), 32);
12
+ ), 32), DEFAULT_MAX_CONSECUTIVE_INVALID_LINES = 10, resolveMaxConsecutiveInvalidLines = (configured) => configured === void 0 ? 10 : Number.isInteger(configured) ? configured < 1 ? (console.warn(
13
+ `[BtpsServer] maxConsecutiveInvalidLines ${configured} is below the minimum 1; using 1`
14
+ ), 1) : configured : (console.warn(
15
+ `[BtpsServer] maxConsecutiveInvalidLines ${configured} is not a whole number; using the default 10`
16
+ ), 10);
13
17
  export {
18
+ DEFAULT_MAX_CONSECUTIVE_INVALID_LINES,
14
19
  DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION,
15
20
  MIN_MAX_IN_FLIGHT_PER_CONNECTION,
21
+ resolveMaxConsecutiveInvalidLines,
16
22
  resolveMaxInFlightPerConnection
17
23
  };
@@ -8,6 +8,7 @@ export * from './abstractRateLimiter.js';
8
8
  export { DEFAULT_MAX_ARTIFACT_SIZE_KB, MIN_MAX_ARTIFACT_SIZE_KB } from './artifactSizeGuard.js';
9
9
  export { DEFAULT_MAX_ARTIFACT_AGE_SECONDS, MIN_MAX_ARTIFACT_AGE_SECONDS, } from './artifactTimeWindow.js';
10
10
  export { DEFAULT_CONNECTION_TIMEOUT_MS } from './connectionTimeout.js';
11
+ export { DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS, DEFAULT_RETIRED_KEY_GRACE_SECONDS, } from './keyChains.js';
11
12
  export { DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION, MIN_MAX_IN_FLIGHT_PER_CONNECTION, } from './inFlightLimit.js';
12
13
  export * from './btpsFactory.js';
13
14
  export * from './btpsLightweightFactory.js';
@@ -15,4 +16,8 @@ export * from './btpsRegistry.js';
15
16
  export * from './btpsSimpleMetricsTracker.js';
16
17
  export * from './btpsSimpleRateLimiter.js';
17
18
  export * from './defaultMiddleware.js';
19
+ export * from './agreementOrderCheck.js';
20
+ export * from './eventChainCheck.js';
21
+ export * from './detailsResponseCheck.js';
22
+ export * from './detailsRequestLimit.js';
18
23
  export * from './type.js';
@@ -12,6 +12,10 @@ import {
12
12
  MIN_MAX_ARTIFACT_AGE_SECONDS
13
13
  } from "./artifactTimeWindow.js";
14
14
  import { DEFAULT_CONNECTION_TIMEOUT_MS } from "./connectionTimeout.js";
15
+ import {
16
+ DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS,
17
+ DEFAULT_RETIRED_KEY_GRACE_SECONDS
18
+ } from "./keyChains.js";
15
19
  import {
16
20
  DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION,
17
21
  MIN_MAX_IN_FLIGHT_PER_CONNECTION
@@ -22,12 +26,18 @@ export * from "./btpsRegistry.js";
22
26
  export * from "./btpsSimpleMetricsTracker.js";
23
27
  export * from "./btpsSimpleRateLimiter.js";
24
28
  export * from "./defaultMiddleware.js";
29
+ export * from "./agreementOrderCheck.js";
30
+ export * from "./eventChainCheck.js";
31
+ export * from "./detailsResponseCheck.js";
32
+ export * from "./detailsRequestLimit.js";
25
33
  export * from "./type.js";
26
34
  export {
27
35
  DEFAULT_CONNECTION_TIMEOUT_MS,
36
+ DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS,
28
37
  DEFAULT_MAX_ARTIFACT_AGE_SECONDS,
29
38
  DEFAULT_MAX_ARTIFACT_SIZE_KB,
30
39
  DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION,
40
+ DEFAULT_RETIRED_KEY_GRACE_SECONDS,
31
41
  MIN_MAX_ARTIFACT_AGE_SECONDS,
32
42
  MIN_MAX_ARTIFACT_SIZE_KB,
33
43
  MIN_MAX_IN_FLIGHT_PER_CONNECTION
@@ -0,0 +1,14 @@
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 { DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS } from '../../core/crypto/keyResolver.js';
8
+ /** Since 1.2: how long a key rotated away as planned still signs for a server, unless it sets `retiredKeyGraceSeconds`: 1 day. */
9
+ export declare const DEFAULT_RETIRED_KEY_GRACE_SECONDS = 86400;
10
+ export { DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS };
11
+ /** Since 1.2: the grace a key rotated away as planned gets, in seconds. */
12
+ export declare const resolveRetiredKeyGraceSeconds: (configured: number | undefined) => number;
13
+ /** Since 1.2: the longest a key chain is trusted from a cache, in seconds: the worst-case live revocation delay. */
14
+ export declare const resolveKeyChainMaxCacheSeconds: (configured: number | undefined) => number;
@@ -0,0 +1,17 @@
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 { DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS } from "../../core/crypto/keyResolver.js";
9
+ const DEFAULT_RETIRED_KEY_GRACE_SECONDS = 86400, resolveSeconds = (name, configured, fallback) => configured === void 0 ? fallback : !Number.isFinite(configured) || configured < 0 ? (console.warn(
10
+ `[BtpsServer] ${name} ${configured} is not a usable time; using the default ${fallback} seconds`
11
+ ), fallback) : configured, resolveRetiredKeyGraceSeconds = (configured) => resolveSeconds("retiredKeyGraceSeconds", configured, DEFAULT_RETIRED_KEY_GRACE_SECONDS), resolveKeyChainMaxCacheSeconds = (configured) => resolveSeconds("keyChainMaxCacheSeconds", configured, DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS);
12
+ export {
13
+ DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS,
14
+ DEFAULT_RETIRED_KEY_GRACE_SECONDS,
15
+ resolveKeyChainMaxCacheSeconds,
16
+ resolveRetiredKeyGraceSeconds
17
+ };
@@ -0,0 +1,20 @@
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 type { BTPDecryptionKey } from '../../core/crypto/types.js';
8
+ import type { BTPAgentKey, BTPTransporterArtifact } from '../../core/server/types.js';
9
+ import type { BTPTrustRecord } from '../../core/trust/types.js';
10
+ /**
11
+ * Since 1.2: an encrypted artifact's content key, unwrapped with the identity's
12
+ * key and wrapped again to one of its devices, for a query result's `agentKey`.
13
+ * The artifact is untouched. It always wraps to the key the device's record
14
+ * holds now, and names that key's fingerprint, so a device that has not
15
+ * finished moving to a new key can tell the wrap is not for the key it holds.
16
+ * @param artifact - The encrypted transporter artifact, as received
17
+ * @param identityKey - The identity's own key: a PEM private key, or a Decrypter with `unwrapKey`
18
+ * @param device - The device's record (its trust record)
19
+ */
20
+ export declare const wrapForAgent: (artifact: Pick<BTPTransporterArtifact, "encryption">, identityKey: BTPDecryptionKey, device: Pick<BTPTrustRecord, "publicKeyBase64" | "publicKeyFingerprint">) => Promise<BTPAgentKey>;
@@ -0,0 +1,36 @@
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 { BTPErrorException } from "../../core/error/index.js";
9
+ import { BTP_ERROR_UNSUPPORTED_ENCRYPT } from "../../core/error/constant.js";
10
+ import { decryptRSA, encryptRSA } from "../../core/crypto/index.js";
11
+ import { base64ToPem } from "../../core/utils/index.js";
12
+ const wrapForAgent = async (artifact, identityKey, device) => {
13
+ const encryptedKey = artifact.encryption?.encryptedKey;
14
+ if (!encryptedKey)
15
+ throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT, {
16
+ cause: "Only an encrypted artifact has a content key to wrap for a device"
17
+ });
18
+ const wrapped = Buffer.from(encryptedKey, "base64");
19
+ let contentKey;
20
+ if (typeof identityKey == "string")
21
+ contentKey = decryptRSA(identityKey, wrapped);
22
+ else if (identityKey.unwrapKey)
23
+ contentKey = Buffer.from(await identityKey.unwrapKey(wrapped));
24
+ else
25
+ throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT, {
26
+ cause: "The Decrypter has no unwrapKey, so it cannot wrap a content key for a device"
27
+ });
28
+ return {
29
+ key: encryptRSA(base64ToPem(device.publicKeyBase64), contentKey).toString("base64"),
30
+ fingerprint: device.publicKeyFingerprint,
31
+ wrappedAt: ( new Date()).toISOString()
32
+ };
33
+ };
34
+ export {
35
+ wrapForAgent
36
+ };
@@ -13,22 +13,39 @@ import { BTPErrorException } from '../core/error/index.js';
13
13
  import { BTPIdentityRecord } from '../core/storage/types.js';
14
14
  import { AbstractIdentityStore } from '../core/storage/AbstractIdentityStore.js';
15
15
  import type { Signer } from '../core/crypto/signer-interface.js';
16
+ import type { BtpsKeyResolver } from '../core/crypto/keyResolver.js';
16
17
  import type { z } from 'zod';
17
- import type { BtpLetterDocSchema, BtpPayslipDocSchema } from '../core/server/schemas/btpsDocsSchema.js';
18
+ import type { BtpAgreementDocSchema, BtpLetterDocSchema, BtpPayslipDocSchema } from '../core/server/schemas/btpsDocsSchema.js';
18
19
  export interface BtpsTlsOptions extends TlsOptions {
19
20
  cert: string;
20
21
  key: string;
21
22
  }
22
23
  export interface BtpsServerOptions {
23
- /** The server's own key, as a PEM key pair or a Signer holding it elsewhere (a KMS). */
24
+ /**
25
+ * The server's own key, as a PEM key pair or a Signer holding it elsewhere (a KMS).
26
+ * `selector` (since 1.2) is the selector its key is published under; `signAnswers` needs it.
27
+ */
24
28
  serverIdentity: {
25
29
  identity: string;
26
30
  publicKey: string;
27
31
  privateKey: string;
32
+ selector?: string;
28
33
  } | {
29
34
  identity: string;
30
35
  signer: Signer;
36
+ selector?: string;
31
37
  };
38
+ /**
39
+ * Since 1.2: sign every answer, errors included, as `serverIdentity` under its `selector`, so a
40
+ * device that requires its server's signature (`requireSignedBy`) can read it. Off by default.
41
+ * `serverIdentity` is the domain's operator, which signs identity-lookup answers too: one key pair.
42
+ */
43
+ signAnswers?: boolean;
44
+ /**
45
+ * Since 1.2: finds every key this server checks a signature with (a sender's, a delegator's,
46
+ * an attestor's), so a provider can cache them. Without it, each is looked up in DNS, as before.
47
+ */
48
+ keyResolver?: BtpsKeyResolver;
32
49
  trustStore: AbstractTrustStore<BTPTrustRecord>;
33
50
  tlsOptions: BtpsTlsOptions;
34
51
  identityStore?: AbstractIdentityStore<BTPIdentityRecord>;
@@ -41,9 +58,34 @@ export interface BtpsServerOptions {
41
58
  maxArtifactSizeKb?: number;
42
59
  /** How far an artifact's issuedAt may be from this server's clock, in seconds, either way. Default 300 (5 minutes), minimum 60. */
43
60
  maxArtifactAgeSeconds?: number;
44
- /** How many requests one connection may have handled at once; at the limit the server stops reading it until one finishes. Default 32, minimum 1. */
61
+ /** How many requests one connection may have handled at once; at the limit the server stops reading it until one finishes. A request is handled until its answer is written. Default 32, minimum 1. */
45
62
  maxInFlightPerConnection?: number;
63
+ /** Since 1.2: how many lines in a row one connection may send that this server cannot read; it answers the last and ends the connection. Default 10, minimum 1. */
64
+ maxConsecutiveInvalidLines?: number;
65
+ /** Since 1.2: how long, in seconds, a key its identity rotated away from as planned still signs for this server. Default 86400 (1 day). A key rotated with immediate expiry gets none. */
66
+ retiredKeyGraceSeconds?: number;
67
+ /**
68
+ * Since 1.2: the longest, in seconds, this server trusts an identity's key chain from a cache,
69
+ * and so the longest a revoked key can still be taken. Default 300. Used by the server's own
70
+ * lookups; a `keyResolver` with `resolveKeyChain` keeps its own cache, and must honour it.
71
+ */
72
+ keyChainMaxCacheSeconds?: number;
46
73
  }
74
+ /** Since 1.2: a details request arrived: who asked whom for which details, and when. */
75
+ export interface BTPDetailsRequestedInfo {
76
+ from: string;
77
+ to: string;
78
+ names: string[];
79
+ /** ISO 8601 */
80
+ at: string;
81
+ }
82
+ /** Since 1.2: a device's details response was taken to be sent: who gave whom which details, and when. */
83
+ export type BTPDetailsSharedInfo = BTPDetailsRequestedInfo;
84
+ /** Since 1.2: what `BtpsServer.on(…)` tells its listeners. */
85
+ export type BtpsServerEvents = {
86
+ detailsRequested: (info: BTPDetailsRequestedInfo) => void;
87
+ detailsShared: (info: BTPDetailsSharedInfo) => void;
88
+ };
47
89
  export type Phase = 'before' | 'after';
48
90
  export type Step = 'parsing' | 'signatureVerification' | 'trustVerification' | 'onArtifact' | 'onError';
49
91
  export interface MiddlewareConfig {
@@ -207,15 +249,57 @@ export interface BTPInvoiceDoc {
207
249
  linkText: string;
208
250
  url: string;
209
251
  };
210
- description?: string;
252
+ description?: BTPNote;
253
+ /** Since 1.2: a discount on the whole invoice, before tax */
254
+ discount?: BTPDiscount;
211
255
  attachments?: BTPAttachment[];
212
256
  references?: BTPDocReference[];
213
- template?: {
214
- name: string;
215
- data: Record<string, unknown>;
216
- };
257
+ template?: BTPTemplate;
217
258
  metadata?: Record<string, unknown>;
218
259
  }
260
+ /**
261
+ * A person's note. Since 1.2 it says how it is written, `text` or `markdown`
262
+ * (CommonMark, raw HTML off), as a letter's body does; a 1.1 note is a plain
263
+ * string, read as `text`.
264
+ */
265
+ export type BTPNote = string | {
266
+ format: 'text' | 'markdown';
267
+ content: string;
268
+ };
269
+ /** Since 1.2: a discount before tax, an amount in minor units of the currency or whole basis points (1 to 10000). */
270
+ export type BTPDiscount = {
271
+ amount: number;
272
+ } | {
273
+ percent: number;
274
+ };
275
+ /** A template by reference. Since 1.2 its named data fields, each optional, are well formed when present. */
276
+ export interface BTPTemplate {
277
+ name: string;
278
+ data: {
279
+ version?: string;
280
+ sha256?: string;
281
+ source?: string;
282
+ logo?: {
283
+ sha256: string;
284
+ source: string;
285
+ };
286
+ values?: BTPTemplateValues;
287
+ [key: string]: unknown;
288
+ };
289
+ }
290
+ /**
291
+ * Since 1.2: what a letter template's signature slots show, from the sender and
292
+ * signed with the document. A drawn signature is integer strokes, `[x, y, x, y, …]`,
293
+ * on a canvas 1000 by 300: data a receiver draws itself, never markup.
294
+ */
295
+ export interface BTPTemplateValues {
296
+ 'signature.typed'?: string;
297
+ 'signature.name'?: string;
298
+ 'signature.title'?: string;
299
+ 'signature.drawn'?: {
300
+ strokes: number[][];
301
+ };
302
+ }
219
303
  /** Proof of a payment: the invoice without what asks for payment, plus `payment`. */
220
304
  export interface BTPReceiptDoc extends Omit<BTPInvoiceDoc, 'type' | 'dueAt' | 'paymentLink' | 'lineItems'> {
221
305
  type: 'receipt';
@@ -231,6 +315,8 @@ export interface BTPReceiptDoc extends Omit<BTPInvoiceDoc, 'type' | 'dueAt' | 'p
231
315
  export type BTPPayslipDoc = z.infer<typeof BtpPayslipDocSchema>;
232
316
  /** A letter: a title and one body, `text` or `markdown`. */
233
317
  export type BTPLetterDoc = z.infer<typeof BtpLetterDocSchema>;
318
+ /** Since 1.2: an agreement, a letter that asks its signers to accept it. */
319
+ export type BTPAgreementDoc = z.infer<typeof BtpAgreementDocSchema>;
234
320
  /** What a `BTPS_DOC` carries. */
235
- export type BTPDocument = BTPInvoiceDoc | BTPReceiptDoc | BTPPayslipDoc | BTPLetterDoc;
321
+ export type BTPDocument = BTPInvoiceDoc | BTPReceiptDoc | BTPPayslipDoc | BTPLetterDoc | BTPAgreementDoc;
236
322
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@btps/sdk",
3
- "version": "1.1.3",
3
+ "version": "1.2.0-rc.1",
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",
@@ -65,8 +65,12 @@
65
65
  "import": "./dist/core/storage/index.js"
66
66
  }
67
67
  },
68
+ "bin": {
69
+ "btps-verify-evidence": "./bin/verify-evidence-bundle.mjs"
70
+ },
68
71
  "files": [
69
72
  "dist",
73
+ "bin",
70
74
  "NOTICE",
71
75
  "CHANGELOG.md"
72
76
  ],
@@ -81,8 +85,9 @@
81
85
  "base64": "bash -c 'base64 -i \"$1\" | tr -d \"\\n\"' --",
82
86
  "typecheck": "tsc --noEmit",
83
87
  "test": "vitest run --coverage",
84
- "test:e2e": "vitest run -c vitest.e2e.config.ts",
85
- "test:security": "vitest run -c vitest.security.config.ts",
88
+ "bench": "vitest bench --run",
89
+ "test:e2e": "yarn build && vitest run -c vitest.e2e.config.ts",
90
+ "test:security": "yarn build && vitest run -c vitest.security.config.ts",
86
91
  "test:watch": "vitest --watch",
87
92
  "test:coverage": "vitest run --coverage",
88
93
  "verify:btps-vectors": "node packages/verify-btps-vectors/bin/verify-btps-vectors.mjs --known-failing test/vectors/known-failing.json",
@@ -97,6 +102,8 @@
97
102
  "@typescript-eslint/parser": "^6.0.0",
98
103
  "@vitest/coverage-v8": "3.2.4",
99
104
  "@vitest/ui": "^3.2.4",
105
+ "ajv": "^8.17.1",
106
+ "btps-sdk-1-1-3": "https://registry.npmjs.org/@btps/sdk/-/sdk-1.1.3.tgz",
100
107
  "chalk": "^5.4.1",
101
108
  "cli-table3": "^0.6.5",
102
109
  "esbuild": "^0.25.5",
@@ -119,8 +126,10 @@
119
126
  },
120
127
  "dependencies": {
121
128
  "@humanwhocodes/momoa": "^3.3.13",
129
+ "asn1js": "^4.0.0",
122
130
  "canonicalize": "^5.1.0",
123
131
  "lodash": "^4.17.21",
132
+ "pkijs": "^4.0.1",
124
133
  "proper-lockfile": "^4.1.2",
125
134
  "split2": "^4.2.0",
126
135
  "zod": "^3.25.67"