@btps/sdk 1.1.2 → 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 (112) hide show
  1. package/CHANGELOG.md +475 -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 +117 -19
  5. package/dist/client/btpsClient.d.ts +53 -7
  6. package/dist/client/btpsClient.js +266 -137
  7. package/dist/client/btpsTransporter.js +2 -1
  8. package/dist/client/index.d.ts +1 -1
  9. package/dist/client/index.js +3 -1
  10. package/dist/client/libs/schema.js +92 -15
  11. package/dist/client/libs/timeouts.d.ts +6 -0
  12. package/dist/client/libs/timeouts.js +2 -1
  13. package/dist/client/types/index.d.ts +60 -2
  14. package/dist/core/authentication/BtpsAuthentication.d.ts +43 -1
  15. package/dist/core/authentication/BtpsAuthentication.js +152 -36
  16. package/dist/core/authentication/refreshSuccessor.js +47 -0
  17. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +17 -1
  18. package/dist/core/authentication/storage/InMemoryTokenStore.js +16 -4
  19. package/dist/core/authentication/types.d.ts +82 -0
  20. package/dist/core/crypto/contentKey.d.ts +34 -0
  21. package/dist/core/crypto/contentKey.js +64 -0
  22. package/dist/core/crypto/decryptVerify.d.ts +7 -1
  23. package/dist/core/crypto/decryptVerify.js +23 -5
  24. package/dist/core/crypto/decrypter-interface.d.ts +6 -0
  25. package/dist/core/crypto/index.d.ts +28 -3
  26. package/dist/core/crypto/index.js +34 -20
  27. package/dist/core/crypto/keyResolver.d.ts +48 -0
  28. package/dist/core/crypto/keyResolver.js +46 -0
  29. package/dist/core/crypto/pem-decrypter.d.ts +2 -0
  30. package/dist/core/crypto/pem-decrypter.js +13 -8
  31. package/dist/core/crypto/signEncrypt.d.ts +4 -1
  32. package/dist/core/crypto/signEncrypt.js +20 -5
  33. package/dist/core/crypto/types.d.ts +8 -1
  34. package/dist/core/delegation/BtpsDelegator.d.ts +4 -0
  35. package/dist/core/delegation/BtpsDelegator.js +3 -2
  36. package/dist/core/delegation/verifyTransporterSignature.d.ts +104 -0
  37. package/dist/core/delegation/verifyTransporterSignature.js +224 -0
  38. package/dist/core/error/constant.d.ts +41 -0
  39. package/dist/core/error/constant.js +60 -0
  40. package/dist/core/server/constants/btps-protocol.d.ts +21 -5
  41. package/dist/core/server/constants/btps-protocol.js +46 -8
  42. package/dist/core/server/constants/index.d.ts +7 -3
  43. package/dist/core/server/constants/index.js +19 -4
  44. package/dist/core/server/constants/limits.d.ts +41 -1
  45. package/dist/core/server/constants/limits.js +45 -2
  46. package/dist/core/server/constants/permissions.d.ts +38 -0
  47. package/dist/core/server/constants/permissions.js +38 -0
  48. package/dist/core/server/schemas/artifacts/agentSchema.js +2 -1
  49. package/dist/core/server/schemas/artifacts/artifacts.js +7 -1
  50. package/dist/core/server/schemas/artifacts/controlSchema.js +1 -1
  51. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +10 -1
  52. package/dist/core/server/schemas/artifacts/transporterSchema.js +92 -12
  53. package/dist/core/server/schemas/bounded.js +41 -0
  54. package/dist/core/server/schemas/btpsDocsSchema.d.ts +34522 -1421
  55. package/dist/core/server/schemas/btpsDocsSchema.js +355 -68
  56. package/dist/core/server/schemas/helpers.d.ts +9580 -0
  57. package/dist/core/server/schemas/helpers.js +76 -12
  58. package/dist/core/server/schemas/keyChainSchema.js +53 -0
  59. package/dist/core/server/schemas/responseSchema.js +88 -12
  60. package/dist/core/server/schemas/schema.js +6 -2
  61. package/dist/core/server/schemas/trustValues.d.ts +105 -0
  62. package/dist/core/server/schemas/trustValues.js +117 -0
  63. package/dist/core/server/types.d.ts +104 -6
  64. package/dist/core/storage/AbstractIdentityStore.d.ts +9 -0
  65. package/dist/core/storage/JsonIdentityStore.d.ts +3 -0
  66. package/dist/core/storage/JsonIdentityStore.js +3 -0
  67. package/dist/core/storage/types.d.ts +2 -0
  68. package/dist/core/trust/agreements.d.ts +107 -0
  69. package/dist/core/trust/agreements.js +116 -0
  70. package/dist/core/trust/evidence.d.ts +220 -0
  71. package/dist/core/trust/evidence.js +334 -0
  72. package/dist/core/trust/index.d.ts +10 -0
  73. package/dist/core/trust/index.js +14 -1
  74. package/dist/core/trust/keyRotation.d.ts +148 -0
  75. package/dist/core/trust/keyRotation.js +267 -0
  76. package/dist/core/trust/permissions.d.ts +114 -0
  77. package/dist/core/trust/permissions.js +115 -0
  78. package/dist/core/trust/shaping.d.ts +42 -0
  79. package/dist/core/trust/shaping.js +47 -0
  80. package/dist/core/trust/storage/AbstractTrustStore.d.ts +2 -1
  81. package/dist/core/trust/storage/JsonTrustStore.d.ts +3 -2
  82. package/dist/core/trust/timestamps.d.ts +49 -0
  83. package/dist/core/trust/timestamps.js +78 -0
  84. package/dist/core/trust/trustUtils.d.ts +13 -2
  85. package/dist/core/trust/trustUtils.js +28 -3
  86. package/dist/core/trust/types.d.ts +302 -2
  87. package/dist/core/trust/verification.d.ts +52 -0
  88. package/dist/core/trust/verification.js +55 -0
  89. package/dist/server/btpsServer.d.ts +72 -6
  90. package/dist/server/btpsServer.js +280 -157
  91. package/dist/server/index.d.ts +3 -0
  92. package/dist/server/index.js +17 -1
  93. package/dist/server/libs/agreementOrderCheck.d.ts +29 -0
  94. package/dist/server/libs/agreementOrderCheck.js +29 -0
  95. package/dist/server/libs/artifactTimeWindow.d.ts +2 -2
  96. package/dist/server/libs/artifactTimeWindow.js +2 -1
  97. package/dist/server/libs/detailsRequestLimit.d.ts +27 -0
  98. package/dist/server/libs/detailsRequestLimit.js +28 -0
  99. package/dist/server/libs/detailsResponseCheck.d.ts +27 -0
  100. package/dist/server/libs/detailsResponseCheck.js +27 -0
  101. package/dist/server/libs/eventChainCheck.d.ts +31 -0
  102. package/dist/server/libs/eventChainCheck.js +39 -0
  103. package/dist/server/libs/inFlightLimit.d.ts +10 -0
  104. package/dist/server/libs/inFlightLimit.js +7 -1
  105. package/dist/server/libs/index.d.ts +5 -0
  106. package/dist/server/libs/index.js +10 -0
  107. package/dist/server/libs/keyChains.d.ts +14 -0
  108. package/dist/server/libs/keyChains.js +17 -0
  109. package/dist/server/libs/wrapForAgent.d.ts +20 -0
  110. package/dist/server/libs/wrapForAgent.js +36 -0
  111. package/dist/server/types.d.ts +95 -9
  112. package/package.json +12 -3
@@ -5,11 +5,11 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
  import { BTPSignature, BTPEncryption } from '../crypto/types.js';
8
- import { BTPTrustReqDoc, BTPTrustResDoc } from '../trust/types.js';
8
+ import { BTPDetailValues, BTPKeyChainRecord, BTPTrustReqDoc, BTPTrustResDoc } from '../trust/types.js';
9
9
  import { BTPDocument } from '../../server/types.js';
10
10
  import type { z } from 'zod';
11
- import type { BtpLifecycleEventSchema } from './schemas/btpsDocsSchema.js';
12
- import { AGENT_ACTIONS, AGENT_ACTIONS_REQUIRING_DOCUMENT, TRANSPORTER_ACTIONS } from './constants/index.js';
11
+ import type { BtpAgreementEventSchema, BtpLifecycleEventSchema } from './schemas/btpsDocsSchema.js';
12
+ import { AGENT_ACTIONS, AGENT_ACTIONS_REQUIRING_DOCUMENT, DETAIL_PERMISSIONS, DOCUMENT_TYPES, ENTITY_TYPES, SEND_PERMISSIONS, TRANSPORTER_ACTIONS } from './constants/index.js';
13
13
  import { CURRENCY_CODES } from './constants/currency.js';
14
14
  import { BTPErrorException } from '../error/index.js';
15
15
  import { IdentityPubKeyRecord } from '../storage/types.js';
@@ -19,7 +19,16 @@ export type AgentAction = (typeof AGENT_ACTIONS)[number];
19
19
  export type AgentActionRequiringDocument = (typeof AGENT_ACTIONS_REQUIRING_DOCUMENT)[number];
20
20
  /** A lifecycle event: what a `BTPS_EVENT` carries (paid, partially paid, disputed, refund, response). */
21
21
  export type BTPLifecycleEvent = z.infer<typeof BtpLifecycleEventSchema>;
22
- export type BTPDocType = BTPDocument | BTPLifecycleEvent | BTPTrustReqDoc | BTPTrustResDoc;
22
+ /** Since 1.2: an agreement's answer, or the statements its originator forwards, as a `BTPS_EVENT` carries them. */
23
+ export type BTPAgreementEvent = z.infer<typeof BtpAgreementEventSchema>;
24
+ /** Since 1.2: what a DETAILS_CHANGED or DETAILS_REQ carries: no values, an optional note. */
25
+ export type BTPDetailsNoteDoc = {
26
+ message?: string | {
27
+ format: 'text' | 'markdown';
28
+ content: string;
29
+ };
30
+ };
31
+ export type BTPDocType = BTPDocument | BTPLifecycleEvent | BTPAgreementEvent | BTPTrustReqDoc | BTPTrustResDoc | BTPDetailsNoteDoc | BTPDetailValues;
23
32
  export type BTPAttestation = {
24
33
  signedBy: string;
25
34
  issuedAt: string;
@@ -97,6 +106,8 @@ export interface BTPIdentityLookupRequest extends Omit<BTPGenericArtifact, 'docu
97
106
  from: string;
98
107
  hostSelector: string;
99
108
  identitySelector?: string;
109
+ /** Since 1.2, under 1.2.0 only: answer with the identity's key chain too */
110
+ keyChain?: true;
100
111
  }
101
112
  export type BTPAgentDocument = BTPTransporterArtifact | BTPAuthReqDoc | BTPAgentMutation | BTPAgentQuery | BTPIdsPayload | string;
102
113
  export interface BTPAgentArtifact extends BTPGenericArtifact<BTPAgentDocument> {
@@ -113,6 +124,53 @@ export interface BTPTransporterArtifact extends BTPGenericArtifact<BTPDocType |
113
124
  selector: string;
114
125
  /** On a BTPS_EVENT only: the id of the BTPS_DOC artifact that delivered the invoice it is about. */
115
126
  relatesTo?: string;
127
+ /** Since 1.2, on a sync only (from equals to, inside a device's artifact.send): the send it copies. */
128
+ syncOf?: BTPSyncOf;
129
+ /** Since 1.2, on a TRUST_REQ: the permissions it asks for. */
130
+ permissions?: BTPTrustPermissions;
131
+ /** Since 1.2, on a TRUST_REQ with permissions and an accepted TRUST_RES: what owns the sender's address. */
132
+ entityType?: BTPEntityType;
133
+ /** Since 1.2, on a TRUST_REQ: the details the sender gives about itself, by name. */
134
+ given?: BTPDetailPermission[];
135
+ /** Since 1.2, on a TRUST_REQ: a change to an active trust, asking for the whole set now wanted. */
136
+ change?: true;
137
+ /** Since 1.2, on an accepted TRUST_RES: the permission names given. */
138
+ granted?: BTPPermissionName[];
139
+ /** Since 1.2, on a BTPS_DOC under a trust with permissions: the type of the document it carries. */
140
+ documentType?: BTPDocumentType;
141
+ /** Since 1.2, on a DETAILS_CHANGED, DETAILS_REQ or DETAILS_RES: the details it is about, by name. */
142
+ details?: BTPDetailPermission[];
143
+ }
144
+ export type BTPDocumentType = (typeof DOCUMENT_TYPES)[number];
145
+ /** Since 1.2: what a trust request leaves out when its receiver's server speaks 1.1. */
146
+ export type BTPShapedField = 'permissions' | 'given' | 'entityType' | 'change' | 'own' | 'verification';
147
+ /**
148
+ * Since 1.2: a trust request with permissions, sent as its 1.1 receiver allows:
149
+ * the version it went as, and what it left out. Never silent: the trust it asks
150
+ * for will carry no permissions.
151
+ */
152
+ export type BTPShaped = {
153
+ sentAs: string;
154
+ leftOut: BTPShapedField[];
155
+ };
156
+ export type BTPEntityType = (typeof ENTITY_TYPES)[number];
157
+ export type BTPSendPermission = (typeof SEND_PERMISSIONS)[number];
158
+ export type BTPDetailPermission = (typeof DETAIL_PERMISSIONS)[number];
159
+ export type BTPPermissionName = BTPSendPermission | BTPDetailPermission;
160
+ /** Since 1.2: one permission a trust request asks for. */
161
+ export interface BTPPermission {
162
+ name: BTPPermissionName;
163
+ required: boolean;
164
+ }
165
+ /**
166
+ * Since 1.2: what a trust request asks for, signed and readable on its envelope.
167
+ * One flat list, the prefix saying each name's kind: each name once, at least one `send:`.
168
+ */
169
+ export type BTPTrustPermissions = BTPPermission[];
170
+ /** Since 1.2: the send a sync copies, by the sent artifact's id and the lowercase hex SHA-256 of its RFC 8785 form. */
171
+ export interface BTPSyncOf {
172
+ id: string;
173
+ sha256: string;
116
174
  }
117
175
  export type BTPArtifact = BTPAgentArtifact | BTPTransporterArtifact | BTPIdentityLookupRequest | BTPControlArtifact;
118
176
  export type BTPStatus = {
@@ -121,14 +179,45 @@ export type BTPStatus = {
121
179
  message?: string;
122
180
  /** On an error, its BTPS code, e.g. 'BTP_ERROR_TRUST_EXPIRED' */
123
181
  error?: string;
182
+ /** Since 1.2, on a 429 only: whole seconds to wait before sending again */
183
+ retryAfter?: number;
184
+ /** Since 1.2: the server ends the connection after this answer, so send nothing more on it */
185
+ closing?: true;
124
186
  };
125
187
  export interface BTPQueryResultEntry<T = BTPTransporterArtifact | BTPDeliveryFailureArtifact> {
126
188
  artifact: T;
127
189
  meta?: {
128
190
  seen?: boolean;
129
191
  seenAt?: string;
192
+ /** Since 1.2, on a sentbox result: what became of the send, by the provider's own record. */
193
+ delivery?: BTPDelivery;
130
194
  [key: string]: unknown;
131
195
  };
196
+ /** Since 1.2: the encrypted artifact's content key, wrapped again to the device that asked (`wrapForAgent`). */
197
+ agentKey?: BTPAgentKey;
198
+ }
199
+ /**
200
+ * Since 1.2: an encrypted artifact's AES content key wrapped with RSA-OAEP /
201
+ * SHA-256 to a device's own key, so the device opens the document without the
202
+ * identity's key. The artifact itself is untouched, so its signature still verifies.
203
+ */
204
+ export interface BTPAgentKey {
205
+ /** The wrapped content key, base64 */
206
+ key: string;
207
+ /** The fingerprint of the device key it is wrapped to, as the device's record holds it */
208
+ fingerprint: string;
209
+ /** When it was wrapped, as an ISO 8601 timestamp */
210
+ wrappedAt: string;
211
+ }
212
+ /**
213
+ * Since 1.2: a send's outcome as its sender's provider knows it, with no receipt
214
+ * from the receiver. `code` is the BTPS error code of a failure.
215
+ */
216
+ export interface BTPDelivery {
217
+ status: 'pending' | 'delivered' | 'failed';
218
+ code?: string;
219
+ /** When it reached this status, as an ISO 8601 timestamp */
220
+ at: string;
132
221
  }
133
222
  export interface BTPQueryResult<T = BTPTransporterArtifact | BTPDeliveryFailureArtifact> {
134
223
  results: BTPQueryResultEntry<T>[];
@@ -155,8 +244,17 @@ export interface BTPDeliveryFailureArtifact {
155
244
  from: string;
156
245
  to: string;
157
246
  }
158
- export type BTPIdentityResDoc = Omit<IdentityPubKeyRecord, 'createdAt'>;
159
- export type BTPServerResDocs = BTPAuthResDoc | BTPQueryResult | BTPIdentityResDoc | string;
247
+ export type BTPIdentityResDoc = Omit<IdentityPubKeyRecord, 'createdAt'> & {
248
+ /** Since 1.2, in a 1.2.0 answer: the identity it answers for */
249
+ identity?: string;
250
+ /** Since 1.2, in a 1.2.0 answer to a lookup that asked: the identity's key chain, oldest first */
251
+ keyChain?: BTPKeyChainRecord[];
252
+ };
253
+ /** "Created, with this id": the answer to a command that makes something, such as `draft.create`. */
254
+ export interface BTPCreatedResDoc {
255
+ id: string;
256
+ }
257
+ export type BTPServerResDocs = BTPAuthResDoc | BTPQueryResult | BTPIdentityResDoc | BTPCreatedResDoc | string;
160
258
  export type BTPServerResponse<T = BTPServerResDocs> = {
161
259
  version: string;
162
260
  status: BTPStatus;
@@ -6,7 +6,16 @@
6
6
  */
7
7
  import { AbstractStorageStore } from '../storage/AbstractStorageStore.js';
8
8
  import { BTPIdentityRecord, IdentityPubKeyRecord } from '../storage/types.js';
9
+ import type { BTPKeyChainRecord } from '../trust/types.js';
9
10
  export declare abstract class AbstractIdentityStore<T extends BTPIdentityRecord> extends AbstractStorageStore<T> {
11
+ /**
12
+ * Since 1.2, optional: the identity's key chain, oldest first, which the
13
+ * server sends to a 1.2.0 lookup that asks for it. The provider writes it
14
+ * (signKeyRotation, signKeyExpiry); the server only reads it. None, or an
15
+ * empty chain, is an identity that never rotated.
16
+ * @param computedId - As for getPublicKeyRecord.
17
+ */
18
+ getKeyChain?(computedId: string): Promise<BTPKeyChainRecord[] | undefined>;
10
19
  /**
11
20
  * The public key record of an identity at a selector (its current one when not given).
12
21
  * @param computedId - The record id the server computes with `computeId(identity)`.
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { BTPIdentityRecord, StorageStoreOptions, IdentityPubKeyRecord } from '../storage/types.js';
8
8
  import { JsonStorageStore } from '../storage/JsonStorageStore.js';
9
+ import type { BTPKeyChainRecord } from '../trust/types.js';
9
10
  import { AbstractIdentityStore } from './AbstractIdentityStore.js';
10
11
  /**
11
12
  * JSON-based TrustStore for self-hosted environments.
@@ -26,4 +27,6 @@ export declare class JsonIdentityStore extends JsonStorageStore<BTPIdentityRecor
26
27
  * @returns The public key for the given identity and selector.
27
28
  */
28
29
  getPublicKeyRecord(computedId: string, selector?: string): Promise<IdentityPubKeyRecord | undefined>;
30
+ /** Since 1.2: the identity's key chain, as its record holds it. */
31
+ getKeyChain(computedId: string): Promise<BTPKeyChainRecord[] | undefined>;
29
32
  }
@@ -33,6 +33,9 @@ class JsonIdentityStore extends JsonStorageStore {
33
33
  const pointer = selector ?? record.currentSelector;
34
34
  return record.publicKeys.find((key) => key.selector === pointer);
35
35
  }
36
+ async getKeyChain(computedId) {
37
+ return (await super.getById(computedId))?.keyChain;
38
+ }
36
39
  }
37
40
  export {
38
41
  JsonIdentityStore
@@ -4,6 +4,7 @@
4
4
  * Licensed under the Apache License, Version 2.0
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
+ import type { BTPKeyChainRecord } from '../trust/types.js';
7
8
  export interface BTPStorageRecord {
8
9
  id: string;
9
10
  createdAt: string;
@@ -14,6 +15,7 @@ export interface BTPIdentityRecord extends BTPStorageRecord {
14
15
  identity: string;
15
16
  currentSelector: string;
16
17
  publicKeys: IdentityPubKeyRecord[];
18
+ keyChain?: BTPKeyChainRecord[];
17
19
  }
18
20
  export type IdentityPubKeyRecord = {
19
21
  selector: string;
@@ -0,0 +1,107 @@
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 { BTPSignature, PemKeys } from '../crypto/types.js';
8
+ import type { Signer } from '../crypto/signer-interface.js';
9
+ import type { z } from 'zod';
10
+ import type { BtpAgreementDocSchema } from '../server/schemas/btpsDocsSchema.js';
11
+ import type { BTPAgreementAnswers, BTPAgreementRef, BTPAgreementStatement, BTPStatementRecord, BTPStatementSignatureFacts } from './types.js';
12
+ type BTPAgreementDoc = z.infer<typeof BtpAgreementDocSchema>;
13
+ /** A key to sign with: a PEM pair, or a Signer for a key held elsewhere. */
14
+ type SigningKey = {
15
+ pemFiles: PemKeys;
16
+ } | {
17
+ signer: Signer;
18
+ };
19
+ /** The public key of `identity` at `selector`, or undefined: from DNS, a store, or an evidence bundle. */
20
+ export type BTPKeyOf = (identity: string, selector: string) => string | undefined;
21
+ /** Since 1.2: the SHA-256, in lowercase hex, of an agreement's RFC 8785 form without `originatorSignature`. */
22
+ export declare const agreementContentSha256: (agreement: object) => string;
23
+ /** Since 1.2: what names an agreement: its originator, its id and its content's SHA-256. */
24
+ export declare const agreementRef: (agreement: Pick<BTPAgreementDoc, "id">, originator: string) => BTPAgreementRef;
25
+ /**
26
+ * Since 1.2: the SHA-256, in lowercase hex, of a statement record's RFC 8785
27
+ * form, signature included: what the next statement names as `previous`.
28
+ */
29
+ export declare const statementRecordSha256: (record: BTPStatementRecord) => string;
30
+ /**
31
+ * Since 1.2: an agreement signed by its originator, over the RFC 8785 form of
32
+ * `{ originator, id, contentSha256 }`. Every signer's copy carries the same.
33
+ */
34
+ export declare const signAgreement: (content: Omit<BTPAgreementDoc, "originatorSignature">, by: {
35
+ originator: string;
36
+ selector: string;
37
+ } & SigningKey) => Promise<BTPAgreementDoc>;
38
+ /** Since 1.2: whether an agreement's `originatorSignature` is its originator's, over its own content. */
39
+ export declare const originatorSignatureValid: (agreement: BTPAgreementDoc, originator: string, keyOf: BTPKeyOf) => boolean;
40
+ /** Since 1.2: a statement signed with the signer's identity key, which may be one its provider holds. */
41
+ export declare const signStatement: (statement: BTPAgreementStatement, by: {
42
+ selector: string;
43
+ } & SigningKey) => Promise<BTPStatementRecord>;
44
+ /**
45
+ * Since 1.2: a statement signed with a device's key. Its record is complete
46
+ * once the originator adds the delegated artifact that delivered it
47
+ * (`deviceStatementRecord`).
48
+ */
49
+ export declare const signStatementOnDevice: (statement: BTPAgreementStatement, device: SigningKey) => Promise<{
50
+ statement: BTPAgreementStatement;
51
+ signature: BTPSignature;
52
+ }>;
53
+ /** Since 1.2: a device's statement with the delegated artifact that delivered it, as it arrived. */
54
+ export declare const deviceStatementRecord: (signed: {
55
+ statement: BTPAgreementStatement;
56
+ signature: BTPSignature;
57
+ }, delegatedArtifact: Extract<BTPStatementRecord, {
58
+ delegatedArtifact: object;
59
+ }>["delegatedArtifact"]) => BTPStatementRecord;
60
+ /**
61
+ * Since 1.2: what a statement record's signature shows, from the record alone
62
+ * and the keys `keyOf` gives. A device-signed record holds when the delegation
63
+ * is its delegator's over the artifact, a self-delegation (signed by the
64
+ * signer itself) carries an attestation, any attestation is its attestor's,
65
+ * the artifact came from the signer and is signed by the delegated key, and so
66
+ * is the statement. Every one of these is checked offline. Whether the
67
+ * delegator or the attestor is the signer's domain's operator needs DNS
68
+ * (`_btps.host` `op`): it is not checked here, and `delegatedBy` and
69
+ * `attestedBy` report who they are.
70
+ */
71
+ export declare const statementSignatureFacts: (record: BTPStatementRecord, keyOf: BTPKeyOf) => BTPStatementSignatureFacts;
72
+ /**
73
+ * Since 1.2: why it is not `from`'s turn to answer, from the answers already
74
+ * taken; or undefined. It needs only who sent the answer, so it reads the
75
+ * envelope and never the statement: a listed signer who has not answered, and
76
+ * in a sequential agreement the next one, with nothing after a decline.
77
+ */
78
+ export declare const agreementTurnProblem: (from: string, held: BTPAgreementAnswers) => string | undefined;
79
+ /**
80
+ * Since 1.2: why an answer does not follow its agreement's signers and order,
81
+ * from its sender, the `previous` its statement names, and the answers already
82
+ * taken; or undefined: its turn (`agreementTurnProblem`), and `previous`, the
83
+ * SHA-256 of the answer before it in a sequential agreement and absent in an
84
+ * `any` one. `agreementStatementProblem` runs this on an opened statement.
85
+ */
86
+ export declare const agreementOrderProblem: (answer: {
87
+ from: string;
88
+ previous?: string;
89
+ }, held: BTPAgreementAnswers) => string | undefined;
90
+ /**
91
+ * Since 1.2: why an opened answer does not answer its agreement, or undefined:
92
+ * the originator's platform's check, never the server's. `envelope` is the
93
+ * answer's own `from` and `to`, `agreement` the receiver's copy, and `earlier`
94
+ * the statement records it has already taken, in order. The statement names
95
+ * this agreement and its terms exactly, is its sender's own, is signed by the
96
+ * deadline, and follows the signers' order. Signatures are not part of this:
97
+ * `statementSignatureFacts` checks them.
98
+ */
99
+ export declare const agreementStatementProblem: (envelope: {
100
+ from: string;
101
+ to: string;
102
+ }, event: {
103
+ eventType: string;
104
+ agreement: BTPAgreementRef;
105
+ statement?: BTPStatementRecord;
106
+ }, agreement: BTPAgreementDoc, earlier: readonly BTPStatementRecord[]) => string | undefined;
107
+ export {};
@@ -0,0 +1,116 @@
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 crypto from "crypto";
9
+ import { signBtpPayload, signBtpPayloadWithSigner, verifySignature } from "../crypto/index.js";
10
+ import { canonicalizeValue } from "../crypto/jcs.js";
11
+ import { sameIdentity } from "../server/schemas/helpers.js";
12
+ const sha256Of = (value) => crypto.createHash("sha256").update(canonicalizeValue(value), "utf8").digest("hex"), sign = (payload, key) => "signer" in key ? signBtpPayloadWithSigner(payload, key.signer) : Promise.resolve(signBtpPayload(payload, key.pemFiles)), isValid = (payload, signature, key) => key !== void 0 && verifySignature(payload, signature, key).isValid, contentOf = (agreement) => Object.fromEntries(Object.entries(agreement).filter(([key]) => key !== "originatorSignature")), agreementContentSha256 = (agreement) => sha256Of(contentOf(agreement)), agreementRef = (agreement, originator) => ({
13
+ originator,
14
+ id: agreement.id,
15
+ contentSha256: agreementContentSha256(agreement)
16
+ }), statementRecordSha256 = (record) => sha256Of(record), signAgreement = async (content, by) => ({
17
+ ...content,
18
+ originatorSignature: {
19
+ selector: by.selector,
20
+ signature: await sign(agreementRef(content, by.originator), by)
21
+ }
22
+ }), originatorSignatureValid = (agreement, originator, keyOf) => {
23
+ const { selector, signature } = agreement.originatorSignature;
24
+ return isValid(agreementRef(agreement, originator), signature, keyOf(originator, selector));
25
+ }, signStatement = async (statement, by) => ({
26
+ statement,
27
+ selector: by.selector,
28
+ signature: await sign(statement, by)
29
+ }), signStatementOnDevice = async (statement, device) => ({
30
+ statement,
31
+ signature: await sign(statement, device)
32
+ }), deviceStatementRecord = (signed, delegatedArtifact) => ({ ...signed, delegatedArtifact }), statementSignatureFacts = (record, keyOf) => {
33
+ const { statement, signature } = record;
34
+ if (!record.delegatedArtifact)
35
+ return {
36
+ signatureValid: isValid(statement, signature, keyOf(statement.signer, record.selector)),
37
+ keyKind: "identity"
38
+ };
39
+ const { delegation, ...artifact } = record.delegatedArtifact, { signature: delegationSignature, attestation, ...unsignedDelegation } = delegation, { signature: artifactSignature, ...unsignedArtifact } = artifact, selfDelegated = sameIdentity(delegation.signedBy, artifact.from);
40
+ return {
41
+ signatureValid: sameIdentity(artifact.from, statement.signer) && (!selfDelegated || attestation !== void 0) && isValid(
42
+ { ...artifact, delegation: unsignedDelegation },
43
+ delegationSignature,
44
+ keyOf(delegation.signedBy, delegation.selector)
45
+ ) && attestationHolds(delegation, keyOf) && isValid(unsignedArtifact, artifactSignature, delegation.agentPubKey) && isValid(statement, signature, delegation.agentPubKey),
46
+ keyKind: "device",
47
+ delegatedBy: delegation.signedBy,
48
+ ...attestation && { attestedBy: attestation.signedBy }
49
+ };
50
+ }, attestationHolds = ({ attestation, ...delegation }, keyOf) => {
51
+ if (!attestation) return !0;
52
+ const { signature, ...unsigned } = attestation;
53
+ return isValid(
54
+ { ...delegation, attestation: unsigned },
55
+ signature,
56
+ keyOf(attestation.signedBy, attestation.selector)
57
+ );
58
+ }, agreementTurnProblem = (from, held) => {
59
+ if (!held.signers.some((signer) => sameIdentity(signer, from)))
60
+ return "only a listed signer answers";
61
+ if (held.answered.some(({ signer }) => sameIdentity(signer, from)))
62
+ return "an answer is final: a signer answers once";
63
+ if (held.signingOrder === "any") return;
64
+ if (held.answered.some(({ decision }) => decision === "declined"))
65
+ return "a declined ends a sequential agreement";
66
+ const next = held.signers[held.answered.length];
67
+ if (next === void 0 || !sameIdentity(next, from))
68
+ return "in a sequential agreement the signers answer in list order";
69
+ }, agreementOrderProblem = (answer, held) => {
70
+ const { from, previous } = answer, turn = agreementTurnProblem(from, held);
71
+ if (turn) return turn;
72
+ if (held.signingOrder === "any")
73
+ return previous === void 0 ? void 0 : "previous is only in a sequential agreement";
74
+ const last = held.answered[held.answered.length - 1];
75
+ if (previous !== last?.sha256)
76
+ return last ? "previous is the SHA-256 of the statement record before it" : "the first statement names no previous";
77
+ }, sameRef = (a, b) => sameIdentity(a.originator, b.originator) && a.id === b.id && a.contentSha256 === b.contentSha256, agreementStatementProblem = (envelope, event, agreement, earlier) => {
78
+ const record = event.statement;
79
+ if (record === void 0) return "only an answer carries a statement";
80
+ const { statement } = record;
81
+ if (statement.decision !== event.eventType)
82
+ return "an answer's eventType is its statement's decision";
83
+ if (!sameRef(event.agreement, statement.agreement))
84
+ return "the event's agreement is its statement's";
85
+ if (!sameRef(statement.agreement, agreementRef(agreement, envelope.to)))
86
+ return "a statement names its own agreement: its originator, id and contentSha256";
87
+ if (!sameIdentity(envelope.from, statement.signer))
88
+ return "a statement is sent by its own signer";
89
+ const { by, terms, signers, signingOrder } = agreement.acceptance;
90
+ return statement.terms.length !== terms.length || statement.terms.some((t, i) => t !== terms[i]) ? "a statement repeats the agreement's terms exactly" : by !== void 0 && Date.parse(statement.signedAt) > Date.parse(by) ? "signedAt is no later than acceptance.by" : agreementOrderProblem(
91
+ { from: statement.signer, previous: statement.previous },
92
+ {
93
+ signers: signers.map(({ address }) => address),
94
+ signingOrder,
95
+ answered: earlier.map((before) => ({
96
+ signer: before.statement.signer,
97
+ decision: before.statement.decision,
98
+ sha256: statementRecordSha256(before)
99
+ }))
100
+ }
101
+ );
102
+ };
103
+ export {
104
+ agreementContentSha256,
105
+ agreementOrderProblem,
106
+ agreementRef,
107
+ agreementStatementProblem,
108
+ agreementTurnProblem,
109
+ deviceStatementRecord,
110
+ originatorSignatureValid,
111
+ signAgreement,
112
+ signStatement,
113
+ signStatementOnDevice,
114
+ statementRecordSha256,
115
+ statementSignatureFacts
116
+ };
@@ -0,0 +1,220 @@
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 { z } from 'zod';
8
+ import type { BTPSignature } from '../crypto/types.js';
9
+ import { BtpEvidenceBundleSchema } from '../server/schemas/btpsDocsSchema.js';
10
+ import type { BTPServerResponse } from '../server/types.js';
11
+ import { type BTPKeyChainCheck } from '../delegation/verifyTransporterSignature.js';
12
+ import { type BTPKeyHolder } from './keyRotation.js';
13
+ import { type BTPKeyOf } from './agreements.js';
14
+ import { type BTPTimestampFacts } from './timestamps.js';
15
+ import type { BTPKeyChainFacts, BTPKeyChainRecord, BTPKeyExpiryReason, BTPStatementRecord, BTPStatementSignatureFacts } from './types.js';
16
+ /**
17
+ * Since 1.2: an agreement's evidence bundle (format `btps-evidence/1`). A
18
+ * record's delegated artifact is a whole transporter artifact, though the
19
+ * schema checks only what its signatures need.
20
+ */
21
+ export type BTPEvidenceBundle = Omit<z.infer<typeof BtpEvidenceBundleSchema>, 'statements'> & {
22
+ statements: BTPStatementRecord[];
23
+ };
24
+ /**
25
+ * Since 1.2: a key a signature was checked with: whose, under which selector,
26
+ * and its fingerprint. Taken from the bundle, so it says what the bundle
27
+ * holds, not that the key was its identity's: no fingerprint when the bundle
28
+ * has no usable key for it. A device key has no selector.
29
+ */
30
+ export type BTPEvidenceKey = {
31
+ identity: string;
32
+ selector?: string;
33
+ fingerprint?: string;
34
+ };
35
+ /**
36
+ * Since 1.2: a signing identity's key chain, as a bundle carries it, with the
37
+ * operator's signed lookup answer that served it, when the builder kept it.
38
+ */
39
+ export type BTPEvidenceKeyChain = {
40
+ identity: string;
41
+ records: BTPKeyChainRecord[];
42
+ operatorAnswer?: BTPServerResponse;
43
+ };
44
+ /** Since 1.2: when the bundle's builder received a statement, signed by it at the time. */
45
+ export type BTPEvidenceArrival = {
46
+ statementSha256: string;
47
+ arrivedAt: string;
48
+ receivedBy: string;
49
+ selector: string;
50
+ signature: BTPSignature;
51
+ };
52
+ /**
53
+ * Since 1.2: the operator's answer a bundle keeps with a chain. Its key, like
54
+ * every key in a bundle, is the bundle's own: the answer confirms a lost key's
55
+ * rotation only when that key is one the reader trusts.
56
+ */
57
+ export type BTPEvidenceOperatorAnswerFacts = {
58
+ /** Who signed it */
59
+ signedBy: string;
60
+ /** Its signature holds, by the key the bundle holds for `signedBy` */
61
+ signatureValid: boolean;
62
+ /** It names this chain's identity and carries this chain, record for record */
63
+ answersThisChain: boolean;
64
+ /**
65
+ * Its key is the one the reader named as the operator of the chain
66
+ * identity's domain (`operators`), or, online, `signedBy` is the operator
67
+ * DNS names there (`op=`) and its key is confirmed as `signedBy`'s
68
+ */
69
+ operatorKeyAnchored: boolean;
70
+ };
71
+ /** Since 1.2: a signature's key, against its identity's key chain. Facts, never a verdict. */
72
+ export type BTPEvidenceKeyChainFacts = {
73
+ /** Every record is well-formed and signed as its kind requires, and the chain rules hold */
74
+ chainValid: boolean;
75
+ /** The first rule broken, when not valid */
76
+ problem?: string;
77
+ /** The key that signed is a key of the chain */
78
+ keyInChain: boolean;
79
+ /**
80
+ * A lost key's rotation that neither an online anchor nor an operator's
81
+ * answer, by an operator key the reader trusts, confirms
82
+ */
83
+ authorityUnverified: boolean;
84
+ /** The operator's answer the bundle keeps with the chain, when it keeps one */
85
+ operatorAnswer?: BTPEvidenceOperatorAnswerFacts;
86
+ /** The bundle's chain gives a key two successors */
87
+ forked: boolean;
88
+ /** The fingerprint of the chain's last key */
89
+ reachesKey?: string;
90
+ /** What confirms the chain, and up to which key: a kept fingerprint, or online */
91
+ anchored: BTPKeyChainFacts['anchored'];
92
+ /** When the key that signed was rotated away from, if it was */
93
+ rotatedAt?: string;
94
+ /** When the key that signed was expired, from when, and why */
95
+ expiredImmediately?: {
96
+ at: string;
97
+ compromisedSince: string;
98
+ reason: BTPKeyExpiryReason;
99
+ };
100
+ /** The time the signer claims is in the key's window, before any compromisedSince */
101
+ signedInWindow: boolean;
102
+ /** The same, by a trusted timestamp's time; absent without one */
103
+ signedInWindowIndependently?: boolean;
104
+ /**
105
+ * The key's owner declared it expired from before a statement it had
106
+ * already received (by a signed arrival or a trusted timestamp): the
107
+ * owner moved the line back past it. Absent without such a time.
108
+ */
109
+ disownedAfterTheFact?: boolean;
110
+ };
111
+ /** Since 1.2: what an evidence bundle shows. BTPS reports these and decides nothing. */
112
+ export type BTPEvidenceFacts = {
113
+ /** The SHA-256 of the agreement's content, as the bundle holds it */
114
+ contentSha256: string;
115
+ /** The originator's signature is over this content */
116
+ originatorSignatureValid: boolean;
117
+ /** The key the originator's signature was checked with */
118
+ originatorKey: BTPEvidenceKey;
119
+ /** Since 1.2: the originator's key against its key chain, when the bundle carries one */
120
+ originatorKeyChain?: BTPEvidenceKeyChainFacts;
121
+ /**
122
+ * False unless checked `online`: then true when every key a signature was
123
+ * checked with is its identity's, by its chain anchored online or by DNS.
124
+ */
125
+ keysConfirmedOnline: boolean;
126
+ /** Each term is the SHA-256 of one of its attachments, as attached */
127
+ termsAttached: boolean;
128
+ /** Each statement, in the bundle's order */
129
+ statements: (BTPStatementSignatureFacts & {
130
+ signer: string;
131
+ decision: 'accepted' | 'declined';
132
+ /** The key its signature was checked with: the signer's identity key, or its device's key */
133
+ key: BTPEvidenceKey;
134
+ /** For a device: the key its delegation was checked with, the delegator's */
135
+ delegationKey?: BTPEvidenceKey;
136
+ /** It names this agreement: its originator, id and content */
137
+ agreementMatches: boolean;
138
+ /** It repeats the agreement's terms exactly */
139
+ termsMatch: boolean;
140
+ /** It was signed no later than `acceptance.by` */
141
+ withinDeadline: boolean;
142
+ /** It follows the signers and order, after the statements before it */
143
+ inOrder: boolean;
144
+ /** Its RFC 3161 timestamp, when the bundle has one for it */
145
+ timestamp?: BTPTimestampFacts;
146
+ /** Since 1.2: when the bundle's builder received it, and whether that is signed by it */
147
+ arrival?: {
148
+ at: string;
149
+ receivedBy: string;
150
+ signatureValid: boolean;
151
+ };
152
+ /** Since 1.2: its signing key (a device's: its delegator's) against its key chain */
153
+ keyChain?: BTPEvidenceKeyChainFacts;
154
+ })[];
155
+ /**
156
+ * Every fact above holds, and every signer accepted, once. A timestamp is
157
+ * optional and never part of it. Checked against the bundle's own keys: it
158
+ * says the bundle is consistent, not that each key was its identity's.
159
+ */
160
+ complete: boolean;
161
+ };
162
+ /**
163
+ * Since 1.2: that the bundle's builder received a statement, at `arrivedAt`,
164
+ * signed then by `receivedBy` (the party that received it) at `selector`. A
165
+ * platform signs each when the statement arrives and keeps it for the
166
+ * bundle: it is the receiver's record, independent of the signer.
167
+ */
168
+ export declare const signArrival: (arrival: Omit<BTPEvidenceArrival, "signature">, holder: BTPKeyHolder) => Promise<BTPEvidenceArrival>;
169
+ /**
170
+ * Since 1.2: the facts of an agreement's evidence bundle, checked offline from
171
+ * the bundle alone. A bundle that is not well formed is refused
172
+ * (`BTP_ERROR_VALIDATION`). Whether a key really was its identity's at the
173
+ * time, and whether a device's delegator is its domain's operator, are facts
174
+ * a reader may confirm online; the bundle embeds the keys so it checks without.
175
+ * A statement's RFC 3161 timestamp, when there is one, is reported with it;
176
+ * with `trustedTimestampRoots` (PEM), whether its authority is trusted too.
177
+ *
178
+ * Since 1.2, each signing key is reported against its identity's key chain
179
+ * when the bundle carries one (`keyChains`), and each statement's signed
180
+ * arrival (`arrivals`) with it. `anchors` are signing-key fingerprints the
181
+ * reader kept. `operators` are the fingerprints the reader kept of domains'
182
+ * operators, by domain: an operator's answer in the bundle confirms a lost
183
+ * key's rotation only by the one named for the chain identity's domain, or
184
+ * online, by the operator DNS names there. `online` confirms each key now as its identity's (`onlineKeyChain`): a key
185
+ * of its identity's chain, which must hold online as a server requires, or its
186
+ * DNS key when there is no chain; only then is `keysConfirmedOnline` true. A
187
+ * key since rotated away or expired is still its identity's: when it was
188
+ * valid is in the key chain facts.
189
+ */
190
+ export declare const verifyEvidenceBundle: (bundle: unknown, options?: {
191
+ trustedTimestampRoots?: string[];
192
+ anchors?: string[];
193
+ operators?: Record<string, string>;
194
+ online?: BTPKeyChainCheck;
195
+ }) => Promise<BTPEvidenceFacts>;
196
+ /**
197
+ * Since 1.2: an agreement's evidence bundle, from the opened agreement, its
198
+ * statement records in the order they were taken, and the keys `keyOf` gives:
199
+ * the originator's, each signer's, and each device's delegator and attestor.
200
+ * A key it cannot find is refused (`BTP_ERROR_RESOLVE_PUBKEY`): a bundle
201
+ * without it would not check offline.
202
+ *
203
+ * Since 1.2, optional: `keyChains`, each signing identity's key chain (from
204
+ * `BtpsClient.lookupKeyChain`), with the operator's answer that served it (its
205
+ * `answer`, as `operatorAnswer`); a
206
+ * key `keyOf` no longer finds (its DNS record retired) is taken from its
207
+ * identity's chain. And `arrivals`, signed with `signArrival` as each
208
+ * statement arrived. Their signers' keys join `keys`.
209
+ */
210
+ export declare const buildEvidenceBundle: (parts: Pick<BTPEvidenceBundle, "originator" | "agreement"> & {
211
+ statements: BTPStatementRecord[];
212
+ keyChains?: BTPEvidenceKeyChain[];
213
+ arrivals?: BTPEvidenceArrival[];
214
+ }, keyOf: BTPKeyOf) => BTPEvidenceBundle;
215
+ /**
216
+ * Since 1.2: an evidence bundle's facts as plain text, one line a fact, as the
217
+ * `btps-verify-evidence` command prints them. Facts only: it says what holds
218
+ * and what does not, never whether to rely on it.
219
+ */
220
+ export declare const describeEvidenceFacts: (facts: BTPEvidenceFacts) => string;