@btps/sdk 1.1.3 → 1.2.0-rc.2

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 +461 -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 +99 -12
  52. package/dist/core/server/schemas/bounded.js +2 -2
  53. package/dist/core/server/schemas/btpsDocsSchema.d.ts +36009 -1083
  54. package/dist/core/server/schemas/btpsDocsSchema.js +305 -42
  55. package/dist/core/server/schemas/helpers.d.ts +10090 -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 +312 -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 +79 -5
  89. package/dist/server/btpsServer.js +297 -145
  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 +103 -9
  111. package/package.json +12 -3
@@ -0,0 +1,267 @@
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 {
10
+ MIN_RSA_KEY_BITS,
11
+ getFingerprintFromPem,
12
+ signBtpPayload,
13
+ signBtpPayloadWithSigner,
14
+ verifySignature
15
+ } from "../crypto/index.js";
16
+ import { canonicalizeValue } from "../crypto/jcs.js";
17
+ import { BTPErrorException } from "../error/index.js";
18
+ import {
19
+ BTP_ERROR_KEY_RETIRED,
20
+ BTP_ERROR_KEY_REVOKED,
21
+ BTP_ERROR_VALIDATION
22
+ } from "../error/constant.js";
23
+ import { BtpKeyChainSchema } from "../server/schemas/keyChainSchema.js";
24
+ import { sameIdentity } from "../server/schemas/helpers.js";
25
+ import { base64ToPem, pemToBase64 } from "../utils/index.js";
26
+ const publicKeyOf = async (holder) => "signer" in holder ? (await holder.signer.getPublicKey()).publicKey : holder.pemFiles.publicKey, signedBy = async (by, payload, holder) => ({
27
+ by,
28
+ ..."signer" in holder ? await signBtpPayloadWithSigner(payload, holder.signer) : signBtpPayload(payload, holder.pemFiles)
29
+ }), signedObjectOf = (record) => "rotation" in record ? record.rotation : record.expiry, keyChainRecordHash = (record) => crypto.createHash("sha256").update(canonicalizeValue(signedObjectOf(record)), "utf8").digest("hex"), signKeyRotation = async (rotation, keys) => {
30
+ if (!keys.from && rotation.expiry !== "immediate")
31
+ throw new BTPErrorException(BTP_ERROR_VALIDATION, {
32
+ cause: "only a rotation with immediate expiry goes without the old key's signature"
33
+ });
34
+ const fromPem = keys.from ? await publicKeyOf(keys.from) : rotation.from.publicKey;
35
+ if (!fromPem)
36
+ throw new BTPErrorException(BTP_ERROR_VALIDATION, {
37
+ cause: "a rotation without the old key names its public key"
38
+ });
39
+ const keyOf = (selector, pem) => ({
40
+ selector,
41
+ fingerprint: getFingerprintFromPem(pem),
42
+ publicKey: pemToBase64(pem)
43
+ }), signed = {
44
+ type: "btps.keyRotation.v1",
45
+ identity: rotation.identity,
46
+ from: keyOf(rotation.from.selector, fromPem),
47
+ to: keyOf(rotation.to.selector, await publicKeyOf(keys.to)),
48
+ at: rotation.at,
49
+ prev: rotation.prev,
50
+ ...rotation.expiry === "immediate" ? {
51
+ expiry: "immediate",
52
+ compromisedSince: rotation.compromisedSince,
53
+ reason: rotation.reason
54
+ } : { expiry: "planned" }
55
+ };
56
+ return {
57
+ rotation: signed,
58
+ signatures: [
59
+ ...keys.from ? [await signedBy("from", signed, keys.from)] : [],
60
+ await signedBy("to", signed, keys.to)
61
+ ]
62
+ };
63
+ }, signKeyExpiry = async (expiry, current) => {
64
+ const signed = { type: "btps.keyExpiry.v1", ...expiry };
65
+ return { expiry: signed, signatures: [await signedBy("current", signed, current)] };
66
+ }, fingerprintOfKey = (publicKey) => {
67
+ try {
68
+ const key = crypto.createPublicKey({
69
+ key: Buffer.from(publicKey, "base64"),
70
+ format: "der",
71
+ type: "spki"
72
+ }), der = key.export({ format: "der", type: "spki" });
73
+ return der.toString("base64") !== publicKey || key.asymmetricKeyType !== "rsa" || (key.asymmetricKeyDetails?.modulusLength ?? 0) < MIN_RSA_KEY_BITS ? void 0 : crypto.createHash("sha256").update(der).digest("base64");
74
+ } catch {
75
+ return;
76
+ }
77
+ }, verifies = (payload, signature, publicKeyPem) => !!signature && verifySignature(payload, signature, publicKeyPem).isValid, recordProblem = (record, identity) => {
78
+ const signed = signedObjectOf(record);
79
+ if (!sameIdentity(signed.identity, identity))
80
+ return `it is ${signed.identity}'s, not ${identity}'s`;
81
+ const by = new Map(record.signatures.map((signature) => [signature.by, signature]));
82
+ if (by.size !== record.signatures.length) return "one key signs it twice";
83
+ if ("expiry" in record)
84
+ return by.has("current") ? Date.parse(record.expiry.compromisedSince) > Date.parse(record.expiry.at) ? "its compromisedSince is after its at" : void 0 : "an expiry is signed by the current key only";
85
+ const { rotation } = record;
86
+ for (const [name, key] of [
87
+ ["from", rotation.from],
88
+ ["to", rotation.to]
89
+ ]) {
90
+ const computed = fingerprintOfKey(key.publicKey);
91
+ if (!computed)
92
+ return `its ${name} key is not the DER SPKI of an RSA key of at least ${MIN_RSA_KEY_BITS} bits`;
93
+ if (computed !== key.fingerprint) return `its ${name} fingerprint is not its key's`;
94
+ }
95
+ if (rotation.from.fingerprint === rotation.to.fingerprint) return "it rotates a key to itself";
96
+ if (by.has("current")) return "a rotation is signed by its from and to keys only";
97
+ if (!verifies(rotation, by.get("to"), base64ToPem(rotation.to.publicKey)))
98
+ return "the new key does not sign it";
99
+ if ((by.has("from") || rotation.expiry === "planned") && !verifies(rotation, by.get("from"), base64ToPem(rotation.from.publicKey)))
100
+ return "the old key does not sign it";
101
+ if (rotation.expiry === "immediate" && Date.parse(rotation.compromisedSince) > Date.parse(rotation.at))
102
+ return "its compromisedSince is after its at";
103
+ }, keyFrom = (key) => ({
104
+ selector: key.selector,
105
+ fingerprint: key.fingerprint,
106
+ publicKey: base64ToPem(key.publicKey)
107
+ }), walk = (nodes) => {
108
+ const keys = [], selectors = new Map(), namedUnder = new Map();
109
+ let lastAt = -1 / 0, lost = !1;
110
+ const names = (selector, fingerprint) => {
111
+ const named = selectors.get(selector);
112
+ return selectors.set(selector, fingerprint), namedUnder.set(fingerprint, (namedUnder.get(fingerprint) ?? new Set()).add(selector)), named === void 0 || named === fingerprint;
113
+ };
114
+ for (const { record, index } of nodes) {
115
+ const at = Date.parse(signedObjectOf(record).at);
116
+ if (!(at > lastAt)) return `record ${index}: its at is not later than the previous record's`;
117
+ lastAt = at;
118
+ const current = keys.at(-1);
119
+ if ("rotation" in record) {
120
+ const { rotation } = record;
121
+ if (!current) keys.push(keyFrom(rotation.from));
122
+ else if (rotation.from.fingerprint !== current.fingerprint)
123
+ return `record ${index}: it rotates from a key that is not the current one`;
124
+ if (keys.some((key) => key.fingerprint === rotation.to.fingerprint))
125
+ return `record ${index}: its new key was already a key of the chain`;
126
+ if (!names(rotation.from.selector, rotation.from.fingerprint))
127
+ return `record ${index}: selector ${rotation.from.selector} names two keys`;
128
+ if (!names(rotation.to.selector, rotation.to.fingerprint))
129
+ return `record ${index}: selector ${rotation.to.selector} names two keys`;
130
+ const left = keys.at(-1);
131
+ left.validUntil = rotation.at, left.rotatedAway = rotation.expiry, rotation.expiry === "immediate" && Object.assign(left, {
132
+ compromisedSince: rotation.compromisedSince,
133
+ reason: rotation.reason,
134
+ expiredAt: rotation.at
135
+ }), lost ||= !record.signatures.some((signature) => signature.by === "from"), keys.push({ ...keyFrom(rotation.to), validFrom: rotation.at });
136
+ } else {
137
+ const { expiry } = record, signature = record.signatures.find((s) => s.by === "current");
138
+ if (!current || !verifies(expiry, signature, current.publicKey))
139
+ return `record ${index}: the current key does not sign it`;
140
+ const target = keys.find((key) => key.fingerprint === expiry.key.fingerprint);
141
+ if (!target || target === current)
142
+ return `record ${index}: it expires a key that is not a past key of the chain`;
143
+ if (!namedUnder.get(expiry.key.fingerprint)?.has(expiry.key.selector))
144
+ return `record ${index}: the chain never names that key under selector ${expiry.key.selector}`;
145
+ if (target.compromisedSince !== void 0)
146
+ return `record ${index}: the key is already expired`;
147
+ Object.assign(target, {
148
+ compromisedSince: expiry.compromisedSince,
149
+ reason: expiry.reason,
150
+ expiredAt: expiry.at
151
+ });
152
+ }
153
+ }
154
+ return { nodes, keys, lost };
155
+ }, invalid = (problem) => ({
156
+ chainValid: !1,
157
+ problem,
158
+ authorityUnverified: !1,
159
+ forked: !1,
160
+ keys: [],
161
+ anchored: !1
162
+ }), checkKeyChain = (records, identity) => {
163
+ const parsed = BtpKeyChainSchema.safeParse(records);
164
+ if (!parsed.success) {
165
+ const [issue] = parsed.error.issues;
166
+ return { problem: `not a key chain: ${issue?.path.join(".")} ${issue?.message}`.trim() };
167
+ }
168
+ const checked = parsed.data;
169
+ if (checked.length === 0) return { records: checked, paths: [] };
170
+ const nodes = checked.map((record, index) => ({
171
+ record,
172
+ index,
173
+ hash: keyChainRecordHash(record)
174
+ })), byHash = new Map();
175
+ for (const node of nodes) {
176
+ const problem = recordProblem(node.record, identity);
177
+ if (problem) return { problem: `record ${node.index}: ${problem}` };
178
+ if (byHash.has(node.hash)) return { problem: `record ${node.index}: it appears twice` };
179
+ byHash.set(node.hash, node);
180
+ }
181
+ const roots = nodes.filter((node) => signedObjectOf(node.record).prev === null);
182
+ if (roots.length !== 1) return { problem: "the chain does not have exactly one first record" };
183
+ const [root] = roots, children = new Map();
184
+ for (const node of nodes) {
185
+ const { prev } = signedObjectOf(node.record);
186
+ if (prev !== null) {
187
+ if (!byHash.has(prev))
188
+ return { problem: `record ${node.index}: its prev names no record of the chain` };
189
+ children.set(prev, [...children.get(prev) ?? [], node]);
190
+ }
191
+ }
192
+ const lines = [], extend = (line) => {
193
+ const next = children.get(line.at(-1).hash) ?? [];
194
+ next.length === 0 && lines.push(line);
195
+ for (const node of next) extend([...line, node]);
196
+ };
197
+ if (extend([root]), new Set(lines.flat()).size !== nodes.length)
198
+ return { problem: "a record is not reached from the first record" };
199
+ const paths = [];
200
+ for (const line of lines) {
201
+ const path = walk(line);
202
+ if (typeof path == "string") return { problem: path };
203
+ paths.push(path);
204
+ }
205
+ return { records: checked, paths };
206
+ }, verifyKeyChain = (records, options) => keyChainFactsOf(checkKeyChain(records, options.identity), options), keyChainFactsOf = (checked, options) => {
207
+ if (checked.problem !== void 0) return invalid(checked.problem);
208
+ const { paths } = checked;
209
+ if (paths.length === 0)
210
+ return {
211
+ chainValid: !0,
212
+ authorityUnverified: !1,
213
+ forked: !1,
214
+ keys: [],
215
+ anchored: !1
216
+ };
217
+ const forked = paths.length > 1, tipOf = (path) => path.keys.at(-1).fingerprint, online = options.online, onlineAnchors = (path) => !!online?.fromOperator && (online.dns.kind === "hostOnly" || online.dns.fingerprints.includes(tipOf(path))), anchors = new Set(options.anchors ?? []), keptOn = (path) => path.keys.filter(
218
+ (key) => anchors.has(key.fingerprint) && paths.filter((other) => other.keys.some((k) => k.fingerprint === key.fingerprint)).length === 1
219
+ ), candidates = forked ? paths.filter((path) => onlineAnchors(path) || keptOn(path).length > 0) : paths, chosen = candidates.length === 1 ? candidates[0] : void 0;
220
+ let anchored = !1;
221
+ if (chosen && onlineAnchors(chosen)) anchored = { by: "online", upTo: tipOf(chosen) };
222
+ else if (chosen) {
223
+ const kept = chosen.keys.filter((key) => anchors.has(key.fingerprint)).at(-1);
224
+ kept && (anchored = { by: "kept-fingerprint", upTo: kept.fingerprint });
225
+ }
226
+ const branches = forked ? paths.map((path) => {
227
+ const split = chosen ? path.nodes.findIndex((node, i) => chosen.nodes[i] !== node) : -1;
228
+ if (!chosen || split < 1) return { tip: tipOf(path), void: !1 };
229
+ const rotations = path.nodes.slice(0, split).filter((n) => "rotation" in n.record).length, since = chosen.keys[rotations]?.compromisedSince, at = signedObjectOf(path.nodes[split].record).at;
230
+ return {
231
+ tip: tipOf(path),
232
+ void: since !== void 0 && Date.parse(at) >= Date.parse(since)
233
+ };
234
+ }) : void 0;
235
+ return {
236
+ chainValid: !0,
237
+ authorityUnverified: !!chosen?.lost && (anchored === !1 || anchored.by !== "online"),
238
+ forked,
239
+ keys: chosen?.keys ?? [],
240
+ ...branches && { branches },
241
+ anchored
242
+ };
243
+ }, keyChainProblem = (records, options) => keyChainProblemOf(checkKeyChain(records, options.identity), options), keyChainProblemOf = (checked, options) => {
244
+ const { fromOperator, dns } = options, facts = keyChainFactsOf(checked, { online: { fromOperator, dns } });
245
+ if (checked.problem !== void 0 || !facts.chainValid) return facts.problem;
246
+ const latest = (options.now ?? Date.now()) + (options.maxSkewSeconds ?? 300) * 1e3, future = checked.records.findIndex(
247
+ (record) => Date.parse(signedObjectOf(record).at) > latest
248
+ );
249
+ if (future !== -1) return `record ${future}: it is dated in the future`;
250
+ if (facts.forked) return "the chain forks: a key has two successors";
251
+ if (facts.keys.length > 0 && !facts.anchored)
252
+ return fromOperator ? "the chain's current key is not the key DNS publishes for the identity" : "the chain did not come in the operator's signed answer";
253
+ }, keyAt = (facts, ref) => facts.keys.find(
254
+ (key) => ref.fingerprint !== void 0 ? key.fingerprint === ref.fingerprint : key.selector === ref.selector
255
+ ), keyChainSignerProblem = (key, options) => key.compromisedSince !== void 0 ? BTP_ERROR_KEY_REVOKED : key.validUntil === void 0 ? void 0 : (options.now ?? Date.now()) - Date.parse(key.validUntil) > options.retiredKeyGraceSeconds * 1e3 ? BTP_ERROR_KEY_RETIRED : void 0;
256
+ export {
257
+ checkKeyChain,
258
+ keyAt,
259
+ keyChainFactsOf,
260
+ keyChainProblem,
261
+ keyChainProblemOf,
262
+ keyChainRecordHash,
263
+ keyChainSignerProblem,
264
+ signKeyExpiry,
265
+ signKeyRotation,
266
+ verifyKeyChain
267
+ };
@@ -0,0 +1,114 @@
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 { BTPError } from '../error/types.js';
8
+ import type { BTPDetailPermission, BTPPermissionName, BTPTrustPermissions } from '../server/types.js';
9
+ import type { BTPTrustRecordPermissions, BTPTrustStatus } from './types.js';
10
+ type GrantRecord = {
11
+ status: BTPTrustStatus;
12
+ permissions?: BTPTrustRecordPermissions;
13
+ };
14
+ /**
15
+ * Why an answer's `granted` cannot be taken against the requester's trust
16
+ * record, and the error it is refused with; undefined when it can, or when it
17
+ * grants nothing by name (a rejection, or a 1.1 answer).
18
+ */
19
+ export declare const trustGrantRefusal: (response: {
20
+ granted?: readonly BTPPermissionName[];
21
+ }, record: GrantRecord) => {
22
+ error: BTPError;
23
+ problem: string;
24
+ } | undefined;
25
+ /** Since 1.2: why an answer's `granted` does not meet the requester's trust record, or undefined. */
26
+ export declare const trustGrantProblem: (response: {
27
+ granted?: readonly BTPPermissionName[];
28
+ }, record: GrantRecord) => string | undefined;
29
+ /**
30
+ * Why a send cannot be taken under the receiver's trust record, and the error
31
+ * it is refused with; undefined when it can. Under a trust with permissions, a
32
+ * `BTPS_DOC` names its `documentType`, `send:<documentType>` is granted, and a
33
+ * readable document is that type. A trust without permissions (a 1.1 trust)
34
+ * allows any type, and events follow the document they are about.
35
+ */
36
+ export declare const documentTypeRefusal: (artifact: {
37
+ type: string;
38
+ documentType?: string;
39
+ encryption?: unknown;
40
+ document?: unknown;
41
+ }, record: {
42
+ permissions?: BTPTrustRecordPermissions;
43
+ }) => {
44
+ error: BTPError;
45
+ problem: string;
46
+ } | undefined;
47
+ /** Since 1.2: why a send does not meet the receiver's trust record, or undefined. */
48
+ export declare const documentTypeProblem: (artifact: Parameters<typeof documentTypeRefusal>[0], record: Parameters<typeof documentTypeRefusal>[1]) => string | undefined;
49
+ /** Since 1.2: a details refresh artifact as these checks read it: its envelope, and its document once opened. */
50
+ export type BTPDetailsEnvelope = {
51
+ type: string;
52
+ id?: string;
53
+ from: string;
54
+ to: string;
55
+ details?: readonly string[];
56
+ relatesTo?: string;
57
+ document?: unknown;
58
+ };
59
+ /**
60
+ * A details refresh against the receiver's record of the trust, from the
61
+ * envelope alone: a notice and a response name only details the receiver holds
62
+ * of the sender (`detailsHeld`), a request only details the answerer shares
63
+ * (`detailsShared`). A trust without permissions holds no details by name.
64
+ */
65
+ export declare const detailsNamesRefusal: (artifact: BTPDetailsEnvelope, record: {
66
+ permissions?: BTPTrustRecordPermissions;
67
+ }) => {
68
+ error: BTPError;
69
+ problem: string;
70
+ } | undefined;
71
+ /**
72
+ * A details response against the request it names (`relatesTo`), as the
73
+ * receiver sent it: that request, from the receiver to this sender, and only
74
+ * the names it asked for. `sentRequest` is undefined when the receiver sent none.
75
+ */
76
+ export declare const detailsRequestRefusal: (response: BTPDetailsEnvelope, sentRequest?: BTPDetailsEnvelope) => {
77
+ error: BTPError;
78
+ problem: string;
79
+ } | undefined;
80
+ /**
81
+ * Since 1.2: why a details refresh artifact cannot be taken, or undefined: its
82
+ * names against the receiver's record, a response against the request it
83
+ * names, and, once a response is opened, its values against its names.
84
+ */
85
+ export declare const detailsProblem: (artifact: BTPDetailsEnvelope, record: {
86
+ permissions?: BTPTrustRecordPermissions;
87
+ }, sentRequest?: BTPDetailsEnvelope) => string | undefined;
88
+ /**
89
+ * Since 1.2: the permissions the requester saves on its own record when it
90
+ * sends a request with permissions, or undefined for a request without them (a
91
+ * 1.1 trust). A change keeps the trust's current permissions and adds the
92
+ * change as pending, so the trust runs on its old grant until it is answered.
93
+ */
94
+ export declare const trustPermissionsFromRequest: (request: {
95
+ permissions?: BTPTrustPermissions;
96
+ change?: true;
97
+ issuedAt: string;
98
+ }, current?: BTPTrustRecordPermissions) => BTPTrustRecordPermissions | undefined;
99
+ /**
100
+ * Since 1.2: the permissions each side saves when a request is accepted: the
101
+ * requester's record and the responder's. Each holds the other's details by
102
+ * name: the requester the details granted to it, the responder the details the
103
+ * request gave. Undefined when the answer grants nothing by name.
104
+ */
105
+ export declare const trustPermissionsFromResponse: (response: {
106
+ granted?: readonly BTPPermissionName[];
107
+ }, request: {
108
+ permissions?: BTPTrustPermissions;
109
+ given?: readonly BTPDetailPermission[];
110
+ }) => {
111
+ requester: BTPTrustRecordPermissions;
112
+ responder: BTPTrustRecordPermissions;
113
+ } | undefined;
114
+ export {};
@@ -0,0 +1,115 @@
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 {
9
+ BTP_ERROR_DETAILS_NOT_HELD,
10
+ BTP_ERROR_DOCUMENT_TYPE_MISMATCH,
11
+ BTP_ERROR_PERMISSION,
12
+ BTP_ERROR_PERMISSION_REQUIRED
13
+ } from "../error/constant.js";
14
+ import { DETAILS_ARTIFACT_TYPES } from "../server/constants/permissions.js";
15
+ import { detailsValuesProblem } from "../server/schemas/trustValues.js";
16
+ const detailsOf = (names) => names.filter((name) => name.startsWith("detail:")), trustGrantRefusal = (response, record) => {
17
+ const { granted } = response;
18
+ if (!granted) return;
19
+ const { permissions } = record;
20
+ if (!permissions)
21
+ return {
22
+ error: BTP_ERROR_PERMISSION_REQUIRED,
23
+ problem: "the request has no permissions on record, so required ones cannot be checked"
24
+ };
25
+ const asked = record.status === "accepted" ? permissions.pendingChange?.requested : permissions.requested;
26
+ if (!asked)
27
+ return {
28
+ error: BTP_ERROR_PERMISSION,
29
+ problem: "an accepted trust takes an answer only while a change is pending"
30
+ };
31
+ const missing = asked.find(({ name, required }) => required && !granted.includes(name));
32
+ if (missing)
33
+ return { error: BTP_ERROR_PERMISSION_REQUIRED, problem: `${missing.name} is required` };
34
+ const extra = granted.find((name) => !asked.some((permission) => permission.name === name));
35
+ if (extra) return { error: BTP_ERROR_PERMISSION, problem: `${extra} was not asked for` };
36
+ }, trustGrantProblem = (response, record) => trustGrantRefusal(response, record)?.problem, documentTypeRefusal = (artifact, record) => {
37
+ const { permissions } = record;
38
+ if (artifact.type !== "BTPS_DOC" || !permissions) return;
39
+ const { documentType } = artifact;
40
+ if (documentType === void 0)
41
+ return {
42
+ error: BTP_ERROR_PERMISSION,
43
+ problem: "a send under a trust with permissions names its documentType"
44
+ };
45
+ if (!permissions.granted.includes(`send:${documentType}`))
46
+ return { error: BTP_ERROR_PERMISSION, problem: `send:${documentType} is not granted` };
47
+ const readable = !artifact.encryption && typeof artifact.document == "object" && artifact.document !== null, type = readable ? artifact.document.type : void 0;
48
+ if (readable && type !== documentType)
49
+ return {
50
+ error: BTP_ERROR_DOCUMENT_TYPE_MISMATCH,
51
+ problem: `the document is a ${String(type)}, not the ${documentType} its envelope names`
52
+ };
53
+ }, documentTypeProblem = (artifact, record) => documentTypeRefusal(artifact, record)?.problem, sameAddress = (a, b) => a.toLowerCase() === b.toLowerCase(), detailsNamesRefusal = (artifact, record) => {
54
+ if (!DETAILS_ARTIFACT_TYPES.includes(artifact.type)) return;
55
+ const { permissions } = record;
56
+ if (!permissions)
57
+ return {
58
+ error: BTP_ERROR_DETAILS_NOT_HELD,
59
+ problem: "a trust without permissions holds no details by name"
60
+ };
61
+ const asking = artifact.type === "DETAILS_REQ", holds = asking ? permissions.detailsShared : permissions.detailsHeld, missing = (artifact.details ?? []).find((name) => !holds.includes(name));
62
+ if (missing)
63
+ return {
64
+ error: BTP_ERROR_DETAILS_NOT_HELD,
65
+ problem: asking ? `${missing} is not a detail the answerer shares by this trust` : `${missing} is not a detail the receiver holds by this trust`
66
+ };
67
+ }, detailsRequestRefusal = (response, sentRequest) => {
68
+ if (response.type !== "DETAILS_RES") return;
69
+ const refuse = (problem) => ({ error: BTP_ERROR_PERMISSION, problem });
70
+ if (!sentRequest) return refuse("a details response answers a request its receiver sent");
71
+ if (sentRequest.type !== "DETAILS_REQ" || sentRequest.id !== response.relatesTo)
72
+ return refuse("a details response answers the request it names");
73
+ if (!sameAddress(sentRequest.from, response.to) || !sameAddress(sentRequest.to, response.from))
74
+ return refuse("a details response answers a request its receiver sent to its sender");
75
+ const asked = sentRequest.details ?? [], extra = (response.details ?? []).find((name) => !asked.includes(name));
76
+ return extra ? refuse(`${extra} was not asked for`) : void 0;
77
+ }, detailsProblem = (artifact, record, sentRequest) => {
78
+ const refusal = detailsNamesRefusal(artifact, record) ?? detailsRequestRefusal(artifact, sentRequest);
79
+ if (refusal) return refusal.problem;
80
+ const opened = typeof artifact.document == "object" && artifact.document !== null;
81
+ return artifact.type === "DETAILS_RES" && opened ? detailsValuesProblem(artifact) : void 0;
82
+ }, trustPermissionsFromRequest = (request, current) => {
83
+ const { permissions } = request;
84
+ if (permissions)
85
+ return request.change && current ? { ...current, pendingChange: { requested: permissions, requestedAt: request.issuedAt } } : { requested: permissions, granted: [], detailsHeld: [], detailsShared: [] };
86
+ }, trustPermissionsFromResponse = (response, request) => {
87
+ const { granted } = response;
88
+ if (!granted || !request.permissions) return;
89
+ const requested = request.permissions, grantedDetails = detailsOf(granted), given = [...request.given ?? []];
90
+ return {
91
+ requester: {
92
+ requested,
93
+ granted: [...granted],
94
+ detailsHeld: grantedDetails,
95
+ detailsShared: given
96
+ },
97
+ responder: {
98
+ requested,
99
+ granted: [...granted],
100
+ detailsHeld: given,
101
+ detailsShared: grantedDetails
102
+ }
103
+ };
104
+ };
105
+ export {
106
+ detailsNamesRefusal,
107
+ detailsProblem,
108
+ detailsRequestRefusal,
109
+ documentTypeProblem,
110
+ documentTypeRefusal,
111
+ trustGrantProblem,
112
+ trustGrantRefusal,
113
+ trustPermissionsFromRequest,
114
+ trustPermissionsFromResponse
115
+ };
@@ -0,0 +1,42 @@
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 { ConnectionOptions } from 'tls';
8
+ import { BTPErrorException } from '../error/index.js';
9
+ import type { BTPShaped } from '../server/types.js';
10
+ type Payload = {
11
+ type?: string;
12
+ document?: unknown;
13
+ [key: string]: unknown;
14
+ };
15
+ /**
16
+ * Since 1.2: a trust request as a 1.1 receiver allows, and what it left out:
17
+ * the permissions on its envelope and the values in its document that stamp
18
+ * it 1.2.0. 1.1's own fields (name, email, phone, ...) stay.
19
+ */
20
+ export declare const shapeTrustRequestFor11: <T extends Payload>(payload: T) => {
21
+ payload: T;
22
+ shaped: BTPShaped;
23
+ };
24
+ /**
25
+ * Since 1.2: a payload composed for its receiver. Only a `TRUST_REQ` carrying
26
+ * permissions is asked about, so any other send costs no round trip. To a
27
+ * receiver whose server speaks 1.1 it goes as 1.1 allows, reported in
28
+ * `shaped`, or, with `versionFallback: false`, is refused with that version.
29
+ * When the receiver's server cannot be asked, that error is returned and
30
+ * nothing is sent: a version is never guessed.
31
+ */
32
+ export declare const composeTrustRequestFor: <T extends Payload>(to: string, payload: T, options?: {
33
+ versionFallback?: boolean;
34
+ btpMtsOptions?: Omit<ConnectionOptions, "port" | "host">;
35
+ }) => Promise<{
36
+ payload: T;
37
+ shaped?: BTPShaped;
38
+ error?: undefined;
39
+ } | {
40
+ error: BTPErrorException;
41
+ }>;
42
+ export {};
@@ -0,0 +1,47 @@
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_VERSION_UNSUPPORTED } from "../error/constant.js";
9
+ import { BTPErrorException } from "../error/index.js";
10
+ import { artifactVersion, isVersionBelow } from "../server/constants/index.js";
11
+ const ENVELOPE_FIELDS = ["permissions", "given", "entityType", "change"], DOCUMENT_FIELDS = ["own", "verification"], shapeTrustRequestFor11 = (payload) => {
12
+ const leftOut = [], shapedPayload = { ...payload };
13
+ for (const field of ENVELOPE_FIELDS)
14
+ shapedPayload[field] !== void 0 && (delete shapedPayload[field], leftOut.push(field));
15
+ if (typeof payload.document == "object" && payload.document !== null) {
16
+ const document = { ...payload.document };
17
+ for (const field of DOCUMENT_FIELDS)
18
+ document[field] !== void 0 && (delete document[field], leftOut.push(field));
19
+ shapedPayload.document = document;
20
+ }
21
+ const sentAs = artifactVersion(shapedPayload);
22
+ return shapedPayload.version !== void 0 && (shapedPayload.version = sentAs), { payload: shapedPayload, shaped: { sentAs, leftOut } };
23
+ }, receiverVersion = async (to, btpMtsOptions) => {
24
+ const { BtpsClient } = await import("../../client/btpsClient.js"), client = new BtpsClient({ to, btpMtsOptions, maxRetries: 0 });
25
+ try {
26
+ return await client.getServerVersion();
27
+ } finally {
28
+ client.destroy();
29
+ }
30
+ }, composeTrustRequestFor = async (to, payload, options = {}) => {
31
+ if (payload.type !== "TRUST_REQ" || payload.permissions === void 0) return { payload };
32
+ const { version, error } = await receiverVersion(to, options.btpMtsOptions);
33
+ return error ? { error } : typeof version != "string" || version === "" ? {
34
+ error: new BTPErrorException(BTP_ERROR_VERSION_UNSUPPORTED, {
35
+ cause: `${to}'s server did not say which version it speaks, so the trust request is not sent`
36
+ })
37
+ } : isVersionBelow(version, "1.2.0") ? options.versionFallback === !1 ? {
38
+ error: new BTPErrorException(BTP_ERROR_VERSION_UNSUPPORTED, {
39
+ cause: `${to}'s server speaks ${version}, which takes no trust permissions, and versionFallback is false`,
40
+ meta: { receiverVersion: version }
41
+ })
42
+ } : shapeTrustRequestFor11(payload) : { payload };
43
+ };
44
+ export {
45
+ composeTrustRequestFor,
46
+ shapeTrustRequestFor11
47
+ };
@@ -13,7 +13,8 @@ export declare abstract class AbstractTrustStore<T extends BTPTrustRecord> exten
13
13
  * either direction, as the platform recorded it. Every `BTPS_EVENT` names
14
14
  * the artifact that delivered its invoice (`relatesTo`) and is refused
15
15
  * unless this answers true, so a sender cannot send events about invoices
16
- * that were never exchanged.
16
+ * that were never exchanged. Since 1.2, a `DETAILS_RES` is refused the same
17
+ * way unless the request it names (`relatesTo`) is known.
17
18
  */
18
19
  abstract isKnownArtifact(query: {
19
20
  artifactId: string;
@@ -25,8 +25,9 @@ declare class JsonTrustStore extends JsonStorageStore<BTPTrustRecord> implements
25
25
  getAll(receiverId?: string): Promise<BTPTrustRecord[]>;
26
26
  /**
27
27
  * This store keeps trust records only, not artifacts, so it knows of none
28
- * and a server using it as is accepts no `BTPS_EVENT`. To accept events,
29
- * extend it and answer from wherever the platform keeps delivered artifacts.
28
+ * and a server using it as is accepts no `BTPS_EVENT`, and since 1.2 no
29
+ * `DETAILS_RES`. To accept them, extend it and answer from wherever the
30
+ * platform keeps delivered artifacts.
30
31
  */
31
32
  isKnownArtifact(): Promise<boolean>;
32
33
  }
@@ -0,0 +1,49 @@
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 { BTPStatementRecord } from './types.js';
8
+ /** Since 1.2: what a timestamp token shows about the statement it is for. */
9
+ export type BTPTimestampFacts = {
10
+ /** The token's message imprint is the SHA-256 of this statement record */
11
+ imprintMatches: boolean;
12
+ /** The token is signed by the certificate it carries */
13
+ signatureValid: boolean;
14
+ /** The time the authority put on it, when the token could be read */
15
+ time?: string;
16
+ /** Who signed it: its certificate's subject */
17
+ authority?: string;
18
+ /**
19
+ * The signer's certificate is a timestamp authority's (RFC 3161 §2.3): its
20
+ * only extended key usage is id-kp-timeStamping, marked critical
21
+ */
22
+ timestampingKeyUsage?: boolean;
23
+ /** With trusted roots given: a timestamp authority's certificate that chains to one of them */
24
+ trusted?: boolean;
25
+ };
26
+ /**
27
+ * Since 1.2: an RFC 3161 TimeStampReq, DER encoded, for the SHA-256 of a
28
+ * statement record, asking for the authority's certificate in the reply. A
29
+ * platform sends it to the authority of its choice
30
+ * (`Content-Type: application/timestamp-query`).
31
+ */
32
+ export declare const timestampRequest: (record: BTPStatementRecord, options?: {
33
+ nonce?: number;
34
+ }) => Promise<Uint8Array>;
35
+ /**
36
+ * Since 1.2: the token in an authority's RFC 3161 TimeStampResp, base64, as
37
+ * an evidence bundle holds it. A reply that grants none is refused
38
+ * (`BTP_ERROR_VALIDATION`).
39
+ */
40
+ export declare const timestampTokenOf: (response: Uint8Array) => Promise<string>;
41
+ /**
42
+ * Since 1.2: the facts of a timestamp token, base64, for the statement record
43
+ * whose SHA-256 is `statementSha256`. With `trustedRoots` (PEM certificates),
44
+ * it also says whether the authority's certificate chains to one of them;
45
+ * without, `trusted` is left out. It refuses nothing.
46
+ */
47
+ export declare const timestampFacts: (token: string, statementSha256: string, options?: {
48
+ trustedRoots?: string[];
49
+ }) => Promise<BTPTimestampFacts>;