@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.
- package/CHANGELOG.md +475 -0
- package/bin/verify-evidence-bundle.mjs +96 -0
- package/dist/client/btpsAgent.d.ts +10 -1
- package/dist/client/btpsAgent.js +117 -19
- package/dist/client/btpsClient.d.ts +53 -7
- package/dist/client/btpsClient.js +266 -137
- package/dist/client/btpsTransporter.js +2 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +3 -1
- package/dist/client/libs/schema.js +92 -15
- package/dist/client/libs/timeouts.d.ts +6 -0
- package/dist/client/libs/timeouts.js +2 -1
- package/dist/client/types/index.d.ts +60 -2
- package/dist/core/authentication/BtpsAuthentication.d.ts +43 -1
- package/dist/core/authentication/BtpsAuthentication.js +152 -36
- package/dist/core/authentication/refreshSuccessor.js +47 -0
- package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +17 -1
- package/dist/core/authentication/storage/InMemoryTokenStore.js +16 -4
- package/dist/core/authentication/types.d.ts +82 -0
- package/dist/core/crypto/contentKey.d.ts +34 -0
- package/dist/core/crypto/contentKey.js +64 -0
- package/dist/core/crypto/decryptVerify.d.ts +7 -1
- package/dist/core/crypto/decryptVerify.js +23 -5
- package/dist/core/crypto/decrypter-interface.d.ts +6 -0
- package/dist/core/crypto/index.d.ts +28 -3
- package/dist/core/crypto/index.js +34 -20
- package/dist/core/crypto/keyResolver.d.ts +48 -0
- package/dist/core/crypto/keyResolver.js +46 -0
- package/dist/core/crypto/pem-decrypter.d.ts +2 -0
- package/dist/core/crypto/pem-decrypter.js +13 -8
- package/dist/core/crypto/signEncrypt.d.ts +4 -1
- package/dist/core/crypto/signEncrypt.js +20 -5
- package/dist/core/crypto/types.d.ts +8 -1
- package/dist/core/delegation/BtpsDelegator.d.ts +4 -0
- package/dist/core/delegation/BtpsDelegator.js +3 -2
- package/dist/core/delegation/verifyTransporterSignature.d.ts +104 -0
- package/dist/core/delegation/verifyTransporterSignature.js +224 -0
- package/dist/core/error/constant.d.ts +41 -0
- package/dist/core/error/constant.js +60 -0
- package/dist/core/server/constants/btps-protocol.d.ts +21 -5
- package/dist/core/server/constants/btps-protocol.js +46 -8
- package/dist/core/server/constants/index.d.ts +7 -3
- package/dist/core/server/constants/index.js +19 -4
- package/dist/core/server/constants/limits.d.ts +41 -1
- package/dist/core/server/constants/limits.js +45 -2
- package/dist/core/server/constants/permissions.d.ts +38 -0
- package/dist/core/server/constants/permissions.js +38 -0
- package/dist/core/server/schemas/artifacts/agentSchema.js +2 -1
- package/dist/core/server/schemas/artifacts/artifacts.js +7 -1
- package/dist/core/server/schemas/artifacts/controlSchema.js +1 -1
- package/dist/core/server/schemas/artifacts/identityLookupSchema.js +10 -1
- package/dist/core/server/schemas/artifacts/transporterSchema.js +92 -12
- package/dist/core/server/schemas/bounded.js +41 -0
- package/dist/core/server/schemas/btpsDocsSchema.d.ts +34522 -1421
- package/dist/core/server/schemas/btpsDocsSchema.js +355 -68
- package/dist/core/server/schemas/helpers.d.ts +9580 -0
- package/dist/core/server/schemas/helpers.js +76 -12
- package/dist/core/server/schemas/keyChainSchema.js +53 -0
- package/dist/core/server/schemas/responseSchema.js +88 -12
- package/dist/core/server/schemas/schema.js +6 -2
- package/dist/core/server/schemas/trustValues.d.ts +105 -0
- package/dist/core/server/schemas/trustValues.js +117 -0
- package/dist/core/server/types.d.ts +104 -6
- package/dist/core/storage/AbstractIdentityStore.d.ts +9 -0
- package/dist/core/storage/JsonIdentityStore.d.ts +3 -0
- package/dist/core/storage/JsonIdentityStore.js +3 -0
- package/dist/core/storage/types.d.ts +2 -0
- package/dist/core/trust/agreements.d.ts +107 -0
- package/dist/core/trust/agreements.js +116 -0
- package/dist/core/trust/evidence.d.ts +220 -0
- package/dist/core/trust/evidence.js +334 -0
- package/dist/core/trust/index.d.ts +10 -0
- package/dist/core/trust/index.js +14 -1
- package/dist/core/trust/keyRotation.d.ts +148 -0
- package/dist/core/trust/keyRotation.js +267 -0
- package/dist/core/trust/permissions.d.ts +114 -0
- package/dist/core/trust/permissions.js +115 -0
- package/dist/core/trust/shaping.d.ts +42 -0
- package/dist/core/trust/shaping.js +47 -0
- package/dist/core/trust/storage/AbstractTrustStore.d.ts +2 -1
- package/dist/core/trust/storage/JsonTrustStore.d.ts +3 -2
- package/dist/core/trust/timestamps.d.ts +49 -0
- package/dist/core/trust/timestamps.js +78 -0
- package/dist/core/trust/trustUtils.d.ts +13 -2
- package/dist/core/trust/trustUtils.js +28 -3
- package/dist/core/trust/types.d.ts +302 -2
- package/dist/core/trust/verification.d.ts +52 -0
- package/dist/core/trust/verification.js +55 -0
- package/dist/server/btpsServer.d.ts +72 -6
- package/dist/server/btpsServer.js +280 -157
- package/dist/server/index.d.ts +3 -0
- package/dist/server/index.js +17 -1
- package/dist/server/libs/agreementOrderCheck.d.ts +29 -0
- package/dist/server/libs/agreementOrderCheck.js +29 -0
- package/dist/server/libs/artifactTimeWindow.d.ts +2 -2
- package/dist/server/libs/artifactTimeWindow.js +2 -1
- package/dist/server/libs/detailsRequestLimit.d.ts +27 -0
- package/dist/server/libs/detailsRequestLimit.js +28 -0
- package/dist/server/libs/detailsResponseCheck.d.ts +27 -0
- package/dist/server/libs/detailsResponseCheck.js +27 -0
- package/dist/server/libs/eventChainCheck.d.ts +31 -0
- package/dist/server/libs/eventChainCheck.js +39 -0
- package/dist/server/libs/inFlightLimit.d.ts +10 -0
- package/dist/server/libs/inFlightLimit.js +7 -1
- package/dist/server/libs/index.d.ts +5 -0
- package/dist/server/libs/index.js +10 -0
- package/dist/server/libs/keyChains.d.ts +14 -0
- package/dist/server/libs/keyChains.js +17 -0
- package/dist/server/libs/wrapForAgent.d.ts +20 -0
- package/dist/server/libs/wrapForAgent.js +36 -0
- package/dist/server/types.d.ts +95 -9
- package/package.json +12 -3
|
@@ -0,0 +1,78 @@
|
|
|
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 { BTPErrorException } from "../error/index.js";
|
|
10
|
+
import { BTP_ERROR_VALIDATION } from "../error/constant.js";
|
|
11
|
+
import { statementRecordSha256 } from "./agreements.js";
|
|
12
|
+
const SHA256 = "2.16.840.1.101.3.4.2.1", TST_INFO = "1.2.840.113549.1.9.16.1.4", MESSAGE_DIGEST = "1.2.840.113549.1.9.4", CONTENT_TYPE = "1.2.840.113549.1.9.3", EXT_KEY_USAGE = "2.5.29.37", TIME_STAMPING = "1.3.6.1.5.5.7.3.8", HASHES = {
|
|
13
|
+
[SHA256]: "sha256",
|
|
14
|
+
"2.16.840.1.101.3.4.2.2": "sha384",
|
|
15
|
+
"2.16.840.1.101.3.4.2.3": "sha512"
|
|
16
|
+
}, libraries = async () => ({ asn1js: await import("asn1js"), pkijs: await import("pkijs") }), hexOf = (bytes) => Buffer.from(new Uint8Array(bytes)).toString("hex"), derOfPem = (pem) => Buffer.from(pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, ""), "base64"), timestampRequest = async (record, options = {}) => {
|
|
17
|
+
const { asn1js, pkijs } = await libraries(), request = new pkijs.TimeStampReq({
|
|
18
|
+
version: 1,
|
|
19
|
+
messageImprint: new pkijs.MessageImprint({
|
|
20
|
+
hashAlgorithm: new pkijs.AlgorithmIdentifier({ algorithmId: SHA256 }),
|
|
21
|
+
hashedMessage: new asn1js.OctetString({
|
|
22
|
+
valueHex: Buffer.from(statementRecordSha256(record), "hex")
|
|
23
|
+
})
|
|
24
|
+
}),
|
|
25
|
+
certReq: !0,
|
|
26
|
+
...options.nonce !== void 0 && { nonce: new asn1js.Integer({ value: options.nonce }) }
|
|
27
|
+
});
|
|
28
|
+
return new Uint8Array(request.toSchema().toBER());
|
|
29
|
+
}, timestampTokenOf = async (response) => {
|
|
30
|
+
const { pkijs } = await libraries(), reply = pkijs.TimeStampResp.fromBER(response);
|
|
31
|
+
if (reply.status.status > 1 || !reply.timeStampToken)
|
|
32
|
+
throw new BTPErrorException(BTP_ERROR_VALIDATION, {
|
|
33
|
+
cause: `the timestamp authority granted no token (status ${reply.status.status})`
|
|
34
|
+
});
|
|
35
|
+
return Buffer.from(reply.timeStampToken.toSchema().toBER()).toString("base64");
|
|
36
|
+
}, timestampFacts = async (token, statementSha256, options = {}) => {
|
|
37
|
+
const { asn1js, pkijs } = await libraries(), unread = { imprintMatches: !1, signatureValid: !1 };
|
|
38
|
+
try {
|
|
39
|
+
const contentInfo = pkijs.ContentInfo.fromBER(Buffer.from(token, "base64")), signedData = new pkijs.SignedData({ schema: contentInfo.content }), { eContentType, eContent } = signedData.encapContentInfo;
|
|
40
|
+
if (eContentType !== TST_INFO || !eContent) return unread;
|
|
41
|
+
const content = Buffer.from(eContent.getValue()), tstInfo = pkijs.TSTInfo.fromBER(content), { hashAlgorithm, hashedMessage } = tstInfo.messageImprint, imprintMatches = hashAlgorithm.algorithmId === SHA256 && hexOf(hashedMessage.valueBlock.valueHexView) === statementSha256, [signerInfo] = signedData.signerInfos, certificates = (signedData.certificates ?? []).filter(
|
|
42
|
+
(cert) => cert instanceof pkijs.Certificate
|
|
43
|
+
), sid = signerInfo?.sid, signer = sid instanceof pkijs.IssuerAndSerialNumber ? certificates.find(
|
|
44
|
+
(cert) => cert.issuer.isEqual(sid.issuer) && cert.serialNumber.isEqual(sid.serialNumber)
|
|
45
|
+
) : void 0, authority = signer?.subject.typesAndValues.map(({ type, value }) => `${type === "2.5.4.3" ? "CN" : type}=${value.valueBlock.value}`).join(", "), usages = signer?.extensions?.filter(({ extnID }) => extnID === EXT_KEY_USAGE) ?? [], [usage] = usages, timestampingKeyUsage = usages.length === 1 && usage?.critical === !0 && usage.parsedValue instanceof pkijs.ExtKeyUsage && usage.parsedValue.keyPurposes.length === 1 && usage.parsedValue.keyPurposes[0] === TIME_STAMPING, hash = signerInfo && HASHES[signerInfo.digestAlgorithm.algorithmId], attributes = signerInfo?.signedAttrs, attribute = (type) => attributes?.attributes.find((attr) => attr.type === type)?.values[0], digest = attribute(MESSAGE_DIGEST), contentType = attribute(CONTENT_TYPE), contentTypeMatches = contentType instanceof asn1js.ObjectIdentifier && contentType.getValue() === TST_INFO;
|
|
46
|
+
let signatureValid = !1;
|
|
47
|
+
if (signer && hash && attributes?.encodedValue && digest instanceof Object && contentTypeMatches) {
|
|
48
|
+
const digestMatches = hexOf(digest.valueBlock.valueHexView) === crypto.createHash(hash).update(content).digest("hex"), signed = Buffer.from(attributes.encodedValue);
|
|
49
|
+
signed[0] = 49;
|
|
50
|
+
const key = crypto.createPublicKey({
|
|
51
|
+
key: Buffer.from(signer.subjectPublicKeyInfo.toSchema().toBER()),
|
|
52
|
+
format: "der",
|
|
53
|
+
type: "spki"
|
|
54
|
+
});
|
|
55
|
+
signatureValid = digestMatches && crypto.verify(hash, signed, key, Buffer.from(signerInfo.signature.valueBlock.valueHexView));
|
|
56
|
+
}
|
|
57
|
+
const roots = options.trustedRoots?.map((pem) => pkijs.Certificate.fromBER(derOfPem(pem))), signerDer = signer && hexOf(signer.toSchema().toBER()), trusted = roots === void 0 ? void 0 : signatureValid && timestampingKeyUsage && signer !== void 0 && (roots.some((root) => hexOf(root.toSchema().toBER()) === signerDer) || (await new pkijs.CertificateChainValidationEngine({
|
|
58
|
+
certs: [...certificates.filter((cert) => cert !== signer), signer],
|
|
59
|
+
trustedCerts: roots,
|
|
60
|
+
checkDate: tstInfo.genTime
|
|
61
|
+
}).verify().catch(() => ({ result: !1 }))).result);
|
|
62
|
+
return {
|
|
63
|
+
imprintMatches,
|
|
64
|
+
signatureValid,
|
|
65
|
+
time: tstInfo.genTime.toISOString(),
|
|
66
|
+
...authority && { authority },
|
|
67
|
+
...signer && { timestampingKeyUsage },
|
|
68
|
+
...trusted !== void 0 && { trusted }
|
|
69
|
+
};
|
|
70
|
+
} catch {
|
|
71
|
+
return unread;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
export {
|
|
75
|
+
timestampFacts,
|
|
76
|
+
timestampRequest,
|
|
77
|
+
timestampTokenOf
|
|
78
|
+
};
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { BTPErrorException } from '../error/index.js';
|
|
8
8
|
import { BTPTrustRecord } from './types.js';
|
|
9
9
|
import { AbstractTrustStore } from './storage/AbstractTrustStore.js';
|
|
10
|
+
import type { BTPPermissionName } from '../server/types.js';
|
|
10
11
|
/**
|
|
11
12
|
* Checks if a trust record is active.
|
|
12
13
|
* Used in for artifact type other than TRUST_RES and TRUST_REQ
|
|
@@ -20,10 +21,16 @@ export declare const isTrustActive: (trust?: BTPTrustRecord) => boolean;
|
|
|
20
21
|
* Used in for artifact type TRUST_REQ
|
|
21
22
|
* only allow message to be sent if trust record is not active
|
|
22
23
|
* considers blocked and retryAfterDate as one can send new trust request after the retryAfterDate
|
|
24
|
+
* Since 1.2, a change (`change: true`) is the one request an active trust takes,
|
|
25
|
+
* one at a time: never while the receiver's record has a change pending, and
|
|
26
|
+
* never without an active trust.
|
|
23
27
|
* @param trust - The trust record to check
|
|
28
|
+
* @param request - The request's envelope
|
|
24
29
|
* @returns Object indicating validity and optional BTPS error
|
|
25
30
|
*/
|
|
26
|
-
export declare const validateTrustRequest: (trust?: BTPTrustRecord
|
|
31
|
+
export declare const validateTrustRequest: (trust?: BTPTrustRecord, request?: {
|
|
32
|
+
change?: true;
|
|
33
|
+
}) => {
|
|
27
34
|
isValid: boolean;
|
|
28
35
|
error?: BTPErrorException;
|
|
29
36
|
};
|
|
@@ -60,11 +67,15 @@ export declare function computeAgentTrustId(agentId: string, identity: string):
|
|
|
60
67
|
* @param senderId - The identity sending the trust response (e.g., userB$domain)
|
|
61
68
|
* @param receiverId - The identity receiving the trust response (e.g., userA$domain)
|
|
62
69
|
* @param trustStore - The TrustStore instance
|
|
70
|
+
* @param response - Since 1.2: the answer's envelope, whose `granted` is checked against the
|
|
71
|
+
* requester's record: every required name granted, and none it did not ask for
|
|
63
72
|
* @returns Object indicating validity and optional BTPS error
|
|
64
73
|
*/
|
|
65
74
|
export declare function validateTrustResponse(senderId: string, // The responder
|
|
66
75
|
receiverId: string, // The original requester
|
|
67
|
-
trustStore: AbstractTrustStore<BTPTrustRecord
|
|
76
|
+
trustStore: AbstractTrustStore<BTPTrustRecord>, response?: {
|
|
77
|
+
granted?: readonly BTPPermissionName[];
|
|
78
|
+
}): Promise<{
|
|
68
79
|
isValid: boolean;
|
|
69
80
|
error?: BTPErrorException;
|
|
70
81
|
}>;
|
|
@@ -13,7 +13,21 @@ import {
|
|
|
13
13
|
BTPErrorException
|
|
14
14
|
} from "../error/index.js";
|
|
15
15
|
import isEmpty from "lodash/isEmpty.js";
|
|
16
|
-
|
|
16
|
+
import { trustGrantRefusal } from "./permissions.js";
|
|
17
|
+
const isTrustActive = (trust) => !(isEmpty(trust) || trust.status !== "accepted" || trust.expiresAt && new Date(trust.expiresAt).getTime() < Date.now()), validateTrustRequest = (trust, request) => {
|
|
18
|
+
const isActive = isTrustActive(trust);
|
|
19
|
+
return isActive && request?.change ? trust?.permissions?.pendingChange ? {
|
|
20
|
+
isValid: !1,
|
|
21
|
+
error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED, {
|
|
22
|
+
cause: "a change is already pending on this trust"
|
|
23
|
+
})
|
|
24
|
+
} : { isValid: !0, error: void 0 } : isActive ? { isValid: !1, error: new BTPErrorException(BTP_ERROR_TRUST_ALREADY_ACTIVE) } : request?.change ? {
|
|
25
|
+
isValid: !1,
|
|
26
|
+
error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED, {
|
|
27
|
+
cause: "a change is only to an active trust"
|
|
28
|
+
})
|
|
29
|
+
} : trust?.status === "blocked" ? { isValid: !1, error: new BTPErrorException(BTP_ERROR_TRUST_BLOCKED) } : trust?.retryAfterDate && new Date(trust.retryAfterDate).getTime() > Date.now() ? { isValid: !1, error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED) } : { isValid: !0, error: void 0 };
|
|
30
|
+
};
|
|
17
31
|
function computeTrustId(senderId, receiverId) {
|
|
18
32
|
const input = `${senderId}:${receiverId}`.toLowerCase();
|
|
19
33
|
return createHash("sha256").update(input).digest("hex");
|
|
@@ -21,12 +35,23 @@ function computeTrustId(senderId, receiverId) {
|
|
|
21
35
|
function computeAgentTrustId(agentId, identity) {
|
|
22
36
|
return computeTrustId(`agent:${agentId}`, identity);
|
|
23
37
|
}
|
|
24
|
-
async function validateTrustResponse(senderId, receiverId, trustStore) {
|
|
38
|
+
async function validateTrustResponse(senderId, receiverId, trustStore, response = {}) {
|
|
25
39
|
const flippedId = computeTrustId(receiverId, senderId), trustRecord = await trustStore.getById(flippedId), buildError = (cause) => ({
|
|
26
40
|
isValid: !1,
|
|
27
41
|
error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED, { cause })
|
|
28
42
|
});
|
|
29
|
-
|
|
43
|
+
if (!trustRecord)
|
|
44
|
+
return buildError(`No pending trust request found from ${receiverId} to ${senderId}`);
|
|
45
|
+
const changePending = trustRecord.status === "accepted" && trustRecord.permissions?.pendingChange;
|
|
46
|
+
if (trustRecord.status !== "pending" && !changePending)
|
|
47
|
+
return buildError(`Trust request from ${receiverId} to ${senderId} is not pending`);
|
|
48
|
+
if (trustRecord.receiverId !== senderId)
|
|
49
|
+
return buildError(`Only ${trustRecord.receiverId} can respond to this trust request`);
|
|
50
|
+
const refusal = trustGrantRefusal(response, trustRecord);
|
|
51
|
+
return refusal ? {
|
|
52
|
+
isValid: !1,
|
|
53
|
+
error: new BTPErrorException(refusal.error, { cause: refusal.problem })
|
|
54
|
+
} : { isValid: !0 };
|
|
30
55
|
}
|
|
31
56
|
function canRetryTrust(trust) {
|
|
32
57
|
return isEmpty(trust) ? !0 : trust.status === "accepted" || trust.status === "blocked" ? !1 : trust.retryAfterDate ? new Date(trust.retryAfterDate).getTime() <= Date.now() : !0;
|
|
@@ -5,9 +5,24 @@
|
|
|
5
5
|
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
6
|
*/
|
|
7
7
|
import { BTPStorageRecord } from '../storage/types.js';
|
|
8
|
+
import type { BTPSignature } from '../crypto/types.js';
|
|
9
|
+
import type { BTPDelegation, BTPDetailPermission, BTPPermissionName, BTPServerResponse, BTPTransporterArtifact, BTPTrustPermissions } from '../server/types.js';
|
|
8
10
|
export type BTPTrustStatus = 'accepted' | 'rejected' | 'revoked' | 'pending' | 'blocked';
|
|
9
11
|
export type BTPTrustDecisionType = Exclude<BTPTrustStatus, 'pending'>;
|
|
10
12
|
export type BTPEncryptionType = 'unencrypted' | 'encrypted' | 'mixed';
|
|
13
|
+
/** What a platform holds of a lifecycle event between two parties, as its `eventChainCheck` lookup answers. */
|
|
14
|
+
export type BTPEventFacts = {
|
|
15
|
+
eventType: string;
|
|
16
|
+
/** Who sent it */
|
|
17
|
+
from: string;
|
|
18
|
+
/** The invoice it is about: its issuer and id, as the event's own `document` names it */
|
|
19
|
+
document: {
|
|
20
|
+
from: string;
|
|
21
|
+
id: string;
|
|
22
|
+
};
|
|
23
|
+
/** A proposal is open until it is answered or withdrawn; any other event is answered. */
|
|
24
|
+
state: 'open' | 'answered' | 'withdrawn';
|
|
25
|
+
};
|
|
11
26
|
export type KeyHistory = {
|
|
12
27
|
fingerprint: string;
|
|
13
28
|
firstSeen: string;
|
|
@@ -26,6 +41,7 @@ export type BTPTrustRecord = Omit<BTPStorageRecord, 'updatedAt'> & {
|
|
|
26
41
|
privacyType: BTPEncryptionType;
|
|
27
42
|
retryAfterDate?: string;
|
|
28
43
|
metadata?: Record<string, unknown>;
|
|
44
|
+
permissions?: BTPTrustRecordPermissions;
|
|
29
45
|
};
|
|
30
46
|
export interface BTPTrustReqDoc {
|
|
31
47
|
id: string;
|
|
@@ -37,10 +53,290 @@ export interface BTPTrustReqDoc {
|
|
|
37
53
|
logoUrl?: string;
|
|
38
54
|
displayName?: string;
|
|
39
55
|
websiteUrl?: string;
|
|
40
|
-
message?: string
|
|
56
|
+
message?: string | {
|
|
57
|
+
format: 'text' | 'markdown';
|
|
58
|
+
content: string;
|
|
59
|
+
};
|
|
41
60
|
expiresAt?: string;
|
|
42
61
|
privacyType?: BTPEncryptionType;
|
|
62
|
+
own?: BTPDetailValues;
|
|
63
|
+
verification?: BTPVerification;
|
|
43
64
|
}
|
|
65
|
+
/** Since 1.2: what a verification says was checked: the sender's kind, and details by name in their shapes. */
|
|
66
|
+
export type BTPVerificationClaims = {
|
|
67
|
+
entityType?: 'person' | 'organisation';
|
|
68
|
+
} & BTPDetailValues;
|
|
69
|
+
/**
|
|
70
|
+
* Since 1.2: a provider's signed statement that it checked a sender. Signed by
|
|
71
|
+
* `verifiedBy` at `selector` over the RFC 8785 form of `{ subject, claims,
|
|
72
|
+
* verifiedAt, expiresAt, verifiedBy, selector }`, where `subject` is the
|
|
73
|
+
* request's `from`, so it cannot be copied into anyone else's request.
|
|
74
|
+
*/
|
|
75
|
+
export type BTPVerification = {
|
|
76
|
+
verifiedBy: string;
|
|
77
|
+
claims: BTPVerificationClaims;
|
|
78
|
+
verifiedAt: string;
|
|
79
|
+
expiresAt: string;
|
|
80
|
+
selector: string;
|
|
81
|
+
signature: BTPSignature;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Since 1.2: the facts about a verification, for its receiver to decide on.
|
|
85
|
+
* BTPS refuses nothing because of them and labels no one verified.
|
|
86
|
+
*/
|
|
87
|
+
export type BTPVerificationFacts = {
|
|
88
|
+
/** The signature is `verifiedBy`'s, over this sender's address and these claims */
|
|
89
|
+
signatureValid: boolean;
|
|
90
|
+
/** `expiresAt` has passed */
|
|
91
|
+
expired: boolean;
|
|
92
|
+
/** `verifiedBy` is on the domain of the operator named in the sender's `_btps.host` */
|
|
93
|
+
verifierServesSender: boolean;
|
|
94
|
+
/** `verifiedBy` is that operator: the serving provider's own signing identity */
|
|
95
|
+
verifierIsOperator: boolean;
|
|
96
|
+
};
|
|
97
|
+
/** Since 1.2: a key in a key rotation record. */
|
|
98
|
+
export type BTPRotatedKey = {
|
|
99
|
+
selector: string;
|
|
100
|
+
/** SHA-256 of the key's DER SPKI, base64; a verifier computes it from `publicKey` */
|
|
101
|
+
fingerprint: string;
|
|
102
|
+
/** The key's DER SPKI, base64, as a DNS key record's `p=` */
|
|
103
|
+
publicKey: string;
|
|
104
|
+
};
|
|
105
|
+
export type BTPKeyExpiryReason = 'compromised' | 'lost';
|
|
106
|
+
/** Since 1.2: what a key rotation record signs: the identity's key `from` hands over to `to`. */
|
|
107
|
+
export type BTPKeyRotation = {
|
|
108
|
+
type: 'btps.keyRotation.v1';
|
|
109
|
+
identity: string;
|
|
110
|
+
from: BTPRotatedKey;
|
|
111
|
+
to: BTPRotatedKey;
|
|
112
|
+
/** When `to` starts signing */
|
|
113
|
+
at: string;
|
|
114
|
+
/** SHA-256 of the previous record's signed object, lowercase hex; null on the first record only */
|
|
115
|
+
prev: string | null;
|
|
116
|
+
} & ({
|
|
117
|
+
expiry: 'planned';
|
|
118
|
+
} | {
|
|
119
|
+
expiry: 'immediate';
|
|
120
|
+
compromisedSince: string;
|
|
121
|
+
reason: BTPKeyExpiryReason;
|
|
122
|
+
});
|
|
123
|
+
/** Since 1.2: what a key expiry record signs: a key the identity already rotated away from, found compromised. */
|
|
124
|
+
export type BTPKeyExpiry = {
|
|
125
|
+
type: 'btps.keyExpiry.v1';
|
|
126
|
+
identity: string;
|
|
127
|
+
key: {
|
|
128
|
+
selector: string;
|
|
129
|
+
fingerprint: string;
|
|
130
|
+
};
|
|
131
|
+
compromisedSince: string;
|
|
132
|
+
reason: BTPKeyExpiryReason;
|
|
133
|
+
at: string;
|
|
134
|
+
prev: string;
|
|
135
|
+
};
|
|
136
|
+
/** `from` and `to` sign a rotation; the identity's `current` key signs an expiry. */
|
|
137
|
+
export type BTPKeyChainSignature = BTPSignature & {
|
|
138
|
+
by: 'from' | 'to' | 'current';
|
|
139
|
+
};
|
|
140
|
+
/** Since 1.2: one record of an identity's key chain, with an optional RFC 3161 token over the same bytes. */
|
|
141
|
+
export type BTPKeyChainRecord = {
|
|
142
|
+
rotation: BTPKeyRotation;
|
|
143
|
+
signatures: BTPKeyChainSignature[];
|
|
144
|
+
timestamp?: string;
|
|
145
|
+
} | {
|
|
146
|
+
expiry: BTPKeyExpiry;
|
|
147
|
+
signatures: BTPKeyChainSignature[];
|
|
148
|
+
timestamp?: string;
|
|
149
|
+
};
|
|
150
|
+
/** Since 1.2: one key of a verified chain, and its window. */
|
|
151
|
+
export type BTPKeyChainKey = {
|
|
152
|
+
selector: string;
|
|
153
|
+
fingerprint: string;
|
|
154
|
+
/** SPKI PEM */
|
|
155
|
+
publicKey: string;
|
|
156
|
+
/** The `at` of the record that introduced it; none for the chain's start */
|
|
157
|
+
validFrom?: string;
|
|
158
|
+
/** The `at` of the rotation away from it; none for the current key */
|
|
159
|
+
validUntil?: string;
|
|
160
|
+
/** How it was rotated away, if it was */
|
|
161
|
+
rotatedAway?: 'planned' | 'immediate';
|
|
162
|
+
/** Set by a rotation with immediate expiry, or by an expiry record */
|
|
163
|
+
compromisedSince?: string;
|
|
164
|
+
reason?: BTPKeyExpiryReason;
|
|
165
|
+
/** When the expiry was declared: the record's own `at` */
|
|
166
|
+
expiredAt?: string;
|
|
167
|
+
};
|
|
168
|
+
/**
|
|
169
|
+
* Since 1.2: what DNS says of an identity, for checking its key chain online.
|
|
170
|
+
* - `hostOnly`: there is no DNS key record for the identity at the domain's
|
|
171
|
+
* current `s=`; its keys are its host's to answer, so the operator's signed
|
|
172
|
+
* answer anchors its chain.
|
|
173
|
+
* - `published`: the fingerprints of the keys DNS publishes for the identity,
|
|
174
|
+
* at the chain's last `to.selector` and at the domain's `s=`, empty when
|
|
175
|
+
* neither has one. The chain anchors only when its last key is one of them.
|
|
176
|
+
* "No record where the chain ends" is `published` with no fingerprints, never
|
|
177
|
+
* `hostOnly`: otherwise a host could anchor a chain of its own making.
|
|
178
|
+
*/
|
|
179
|
+
export type BTPKeyChainDns = {
|
|
180
|
+
kind: 'hostOnly';
|
|
181
|
+
} | {
|
|
182
|
+
kind: 'published';
|
|
183
|
+
fingerprints: string[];
|
|
184
|
+
};
|
|
185
|
+
/**
|
|
186
|
+
* Since 1.2: what asking an identity's host for its key chain gave.
|
|
187
|
+
* - `chain`: the operator's signed answer, checked; `[]` for an identity that
|
|
188
|
+
* never rotated. `answer` is that answer as it came, signature and all, for
|
|
189
|
+
* an evidence bundle to keep.
|
|
190
|
+
* - `unavailable`: no chain to be had (a 1.1 host, an unreachable one, or one
|
|
191
|
+
* that answered with an error): the identity's keys are checked by DNS, as
|
|
192
|
+
* in 1.1.
|
|
193
|
+
* - `invalid`: an answer that fails its checks (its signature, its `reqId`,
|
|
194
|
+
* its time, the identity it names): refused, never taken for unavailable.
|
|
195
|
+
*/
|
|
196
|
+
export type BTPKeyChainLookup = {
|
|
197
|
+
status: 'chain';
|
|
198
|
+
records: BTPKeyChainRecord[];
|
|
199
|
+
answer?: BTPServerResponse;
|
|
200
|
+
} | {
|
|
201
|
+
status: 'unavailable';
|
|
202
|
+
reason: string;
|
|
203
|
+
} | {
|
|
204
|
+
status: 'invalid';
|
|
205
|
+
reason: string;
|
|
206
|
+
};
|
|
207
|
+
/** Since 1.2: the facts about a key chain. It decides nothing; `keyChainProblem` is the online refusal. */
|
|
208
|
+
export type BTPKeyChainFacts = {
|
|
209
|
+
/** Every record is well-formed and signed as its kind requires, `prev` links hold, and the chain rules hold */
|
|
210
|
+
chainValid: boolean;
|
|
211
|
+
/** The first rule broken, when not valid */
|
|
212
|
+
problem?: string;
|
|
213
|
+
/** A rotation without its `from` signature (a lost key) whose authority the anchor cannot confirm */
|
|
214
|
+
authorityUnverified: boolean;
|
|
215
|
+
/** A key has two successors */
|
|
216
|
+
forked: boolean;
|
|
217
|
+
/** The chain's keys in order, start first: the only path, or the one branch an anchor picks; empty otherwise */
|
|
218
|
+
keys: BTPKeyChainKey[];
|
|
219
|
+
/** Each branch's last key, when forked; `void` when its first record is signed by a key expired at the time */
|
|
220
|
+
branches?: {
|
|
221
|
+
tip: string;
|
|
222
|
+
void: boolean;
|
|
223
|
+
}[];
|
|
224
|
+
/** What confirms the chain, and up to which key: a kept fingerprint anchors itself and the records leading to it */
|
|
225
|
+
anchored: {
|
|
226
|
+
by: 'kept-fingerprint' | 'online';
|
|
227
|
+
upTo: string;
|
|
228
|
+
} | false;
|
|
229
|
+
};
|
|
230
|
+
/** Since 1.2: an agreement, by its originator, its id and the SHA-256 of its content. */
|
|
231
|
+
export type BTPAgreementRef = {
|
|
232
|
+
originator: string;
|
|
233
|
+
id: string;
|
|
234
|
+
contentSha256: string;
|
|
235
|
+
};
|
|
236
|
+
/**
|
|
237
|
+
* Since 1.2: an agreement's signers in order, how they answer, and the answers
|
|
238
|
+
* its originator's platform has taken, in order, each by the SHA-256 of its
|
|
239
|
+
* record: what `agreementOrderProblem` checks an answer against.
|
|
240
|
+
*/
|
|
241
|
+
export type BTPAgreementAnswers = {
|
|
242
|
+
signers: string[];
|
|
243
|
+
signingOrder: 'any' | 'sequential';
|
|
244
|
+
answered: {
|
|
245
|
+
signer: string;
|
|
246
|
+
decision: 'accepted' | 'declined';
|
|
247
|
+
sha256: string;
|
|
248
|
+
}[];
|
|
249
|
+
};
|
|
250
|
+
/**
|
|
251
|
+
* Since 1.2: a signer's answer to an agreement, signed over its RFC 8785 form.
|
|
252
|
+
* `previous`, in a sequential agreement, is the SHA-256 of the statement
|
|
253
|
+
* record before it.
|
|
254
|
+
*/
|
|
255
|
+
export type BTPAgreementStatement = {
|
|
256
|
+
agreement: BTPAgreementRef;
|
|
257
|
+
terms: string[];
|
|
258
|
+
signer: string;
|
|
259
|
+
decision: 'accepted' | 'declined';
|
|
260
|
+
signedAt: string;
|
|
261
|
+
previous?: string;
|
|
262
|
+
};
|
|
263
|
+
/**
|
|
264
|
+
* Since 1.2: a signed statement. Signed by the signer's identity key at
|
|
265
|
+
* `selector`, or by its device key, when it carries the whole delegated
|
|
266
|
+
* artifact that delivered it, as it arrived.
|
|
267
|
+
*/
|
|
268
|
+
export type BTPStatementRecord = {
|
|
269
|
+
statement: BTPAgreementStatement;
|
|
270
|
+
signature: BTPSignature;
|
|
271
|
+
} & ({
|
|
272
|
+
selector: string;
|
|
273
|
+
delegatedArtifact?: never;
|
|
274
|
+
} | {
|
|
275
|
+
delegatedArtifact: BTPTransporterArtifact & {
|
|
276
|
+
delegation: BTPDelegation;
|
|
277
|
+
};
|
|
278
|
+
selector?: never;
|
|
279
|
+
});
|
|
280
|
+
/** Since 1.2: what a statement record's signature shows. BTPS reports these and decides nothing. */
|
|
281
|
+
export type BTPStatementSignatureFacts = {
|
|
282
|
+
/** The statement is signed by its signer's key, or by a device its delegation vouches for */
|
|
283
|
+
signatureValid: boolean;
|
|
284
|
+
/** Which kind of key signed it, from the record itself */
|
|
285
|
+
keyKind: 'identity' | 'device';
|
|
286
|
+
/** For a device: who signed its delegation, and who attested it, if anyone */
|
|
287
|
+
delegatedBy?: string;
|
|
288
|
+
attestedBy?: string;
|
|
289
|
+
};
|
|
290
|
+
/** Since 1.2: a tax or registration number, for any country (ISO 3166-1 alpha-2, e.g. `AU`). */
|
|
291
|
+
export type BTPNumberInCountry = {
|
|
292
|
+
number: string;
|
|
293
|
+
country: string;
|
|
294
|
+
};
|
|
295
|
+
/** Since 1.2: a display or trading name, picture or logo, and website: `detail:profile`. */
|
|
296
|
+
export type BTPDetailProfile = {
|
|
297
|
+
displayName: string;
|
|
298
|
+
logo?: {
|
|
299
|
+
sha256: string;
|
|
300
|
+
source: string;
|
|
301
|
+
};
|
|
302
|
+
website?: string;
|
|
303
|
+
};
|
|
304
|
+
/** Since 1.2: the value each detail permission carries. */
|
|
305
|
+
export type BTPDetailValueOf = {
|
|
306
|
+
'detail:legalName': string;
|
|
307
|
+
'detail:profile': BTPDetailProfile;
|
|
308
|
+
'detail:email': string;
|
|
309
|
+
'detail:phone': string;
|
|
310
|
+
'detail:address': string;
|
|
311
|
+
'detail:taxNo': BTPNumberInCountry;
|
|
312
|
+
/** `YYYY-MM-DD` */
|
|
313
|
+
'detail:dob': string;
|
|
314
|
+
'detail:registrationNumber': BTPNumberInCountry;
|
|
315
|
+
};
|
|
316
|
+
/** Since 1.2: detail values by permission name, e.g. `{ "detail:dob": "1990-04-21" }`. */
|
|
317
|
+
export type BTPDetailValues = {
|
|
318
|
+
[Name in keyof BTPDetailValueOf]?: BTPDetailValueOf[Name];
|
|
319
|
+
};
|
|
320
|
+
/**
|
|
321
|
+
* Since 1.2: a trust record's permissions, written by the platform, never the
|
|
322
|
+
* BTPS server, which only reads them. `trustPermissionsFromRequest` and
|
|
323
|
+
* `trustPermissionsFromResponse` compute them for the platform to save.
|
|
324
|
+
*/
|
|
325
|
+
export type BTPTrustRecordPermissions = {
|
|
326
|
+
/** What the request asked for */
|
|
327
|
+
requested: BTPTrustPermissions;
|
|
328
|
+
/** What the answer granted: the `send:` names checked on each document, and the details given */
|
|
329
|
+
granted: BTPPermissionName[];
|
|
330
|
+
/** The other side's details this side holds */
|
|
331
|
+
detailsHeld: BTPDetailPermission[];
|
|
332
|
+
/** This side's details the other side holds */
|
|
333
|
+
detailsShared: BTPDetailPermission[];
|
|
334
|
+
/** A change sent on an active trust, until it is answered */
|
|
335
|
+
pendingChange?: {
|
|
336
|
+
requested: BTPTrustPermissions;
|
|
337
|
+
requestedAt: string;
|
|
338
|
+
};
|
|
339
|
+
};
|
|
44
340
|
export interface BTPTrustResDoc {
|
|
45
341
|
id: string;
|
|
46
342
|
decision: BTPTrustDecisionType;
|
|
@@ -48,6 +344,10 @@ export interface BTPTrustResDoc {
|
|
|
48
344
|
decidedBy: string;
|
|
49
345
|
expiresAt?: string;
|
|
50
346
|
retryAfterDate?: string;
|
|
51
|
-
message?: string
|
|
347
|
+
message?: string | {
|
|
348
|
+
format: 'text' | 'markdown';
|
|
349
|
+
content: string;
|
|
350
|
+
};
|
|
52
351
|
privacyType?: BTPEncryptionType;
|
|
352
|
+
details?: BTPDetailValues;
|
|
53
353
|
}
|
|
@@ -0,0 +1,52 @@
|
|
|
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 { PemKeys } from '../crypto/types.js';
|
|
8
|
+
import type { Signer } from '../crypto/signer-interface.js';
|
|
9
|
+
import type { BtpsKeyResolver } from '../crypto/keyResolver.js';
|
|
10
|
+
import type { BTPError } from '../error/types.js';
|
|
11
|
+
import type { BTPVerification, BTPVerificationClaims, BTPVerificationFacts } from './types.js';
|
|
12
|
+
/**
|
|
13
|
+
* Since 1.2: a provider signs a statement that it checked `subject`, the
|
|
14
|
+
* address that will send the trust request carrying it. The result goes in the
|
|
15
|
+
* request's document as `verification`.
|
|
16
|
+
*/
|
|
17
|
+
export declare const signVerification: (statement: {
|
|
18
|
+
subject: string;
|
|
19
|
+
claims: BTPVerificationClaims;
|
|
20
|
+
verifiedAt: string;
|
|
21
|
+
expiresAt: string;
|
|
22
|
+
}, verifier: {
|
|
23
|
+
verifiedBy: string;
|
|
24
|
+
selector: string;
|
|
25
|
+
} & ({
|
|
26
|
+
pemFiles: PemKeys;
|
|
27
|
+
} | {
|
|
28
|
+
signer: Signer;
|
|
29
|
+
})) => Promise<BTPVerification>;
|
|
30
|
+
/**
|
|
31
|
+
* Since 1.2: why `verifiedBy` may not verify, or undefined. Only one who runs a
|
|
32
|
+
* BTPS server verifies: the `op` of its own domain's host record. This makes a
|
|
33
|
+
* verifier an operator, nothing more; whose verifications to trust stays each
|
|
34
|
+
* provider's to decide. A lookup that fails, rather than finding no record, is
|
|
35
|
+
* `BTP_ERROR_RESOLVE_DNS`, to try again.
|
|
36
|
+
*/
|
|
37
|
+
export declare const verifierRefusal: (verifiedBy: string) => Promise<{
|
|
38
|
+
error: BTPError;
|
|
39
|
+
problem: string;
|
|
40
|
+
} | undefined>;
|
|
41
|
+
/**
|
|
42
|
+
* Since 1.2: the facts about an opened trust request's verification, or
|
|
43
|
+
* undefined when it carries none. It refuses nothing: whose verifications to
|
|
44
|
+
* trust, and which facts to require, are each provider's to decide.
|
|
45
|
+
*/
|
|
46
|
+
export declare const verificationFacts: (request: {
|
|
47
|
+
from: string;
|
|
48
|
+
document?: unknown;
|
|
49
|
+
}, options?: {
|
|
50
|
+
keyResolver?: BtpsKeyResolver;
|
|
51
|
+
now?: number;
|
|
52
|
+
}) => Promise<BTPVerificationFacts | undefined>;
|
|
@@ -0,0 +1,55 @@
|
|
|
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 { signBtpPayload, signBtpPayloadWithSigner, verifySignature } from "../crypto/index.js";
|
|
9
|
+
import { signatureKey } from "../delegation/verifyTransporterSignature.js";
|
|
10
|
+
import { getHostAndSelector, parseIdentity } from "../utils/index.js";
|
|
11
|
+
import { BTP_ERROR_RESOLVE_DNS, BTP_ERROR_VALIDATION } from "../error/constant.js";
|
|
12
|
+
const signedStatement = (subject, verification) => {
|
|
13
|
+
const { claims, verifiedAt, expiresAt, verifiedBy, selector } = verification;
|
|
14
|
+
return { subject, claims, verifiedAt, expiresAt, verifiedBy, selector };
|
|
15
|
+
}, domainOf = (identity) => parseIdentity(identity)?.domainName.toLowerCase(), signVerification = async (statement, verifier) => {
|
|
16
|
+
const { subject, claims, verifiedAt, expiresAt } = statement, unsigned = {
|
|
17
|
+
verifiedBy: verifier.verifiedBy,
|
|
18
|
+
claims,
|
|
19
|
+
verifiedAt,
|
|
20
|
+
expiresAt,
|
|
21
|
+
selector: verifier.selector
|
|
22
|
+
}, payload = signedStatement(subject, unsigned), signature = "signer" in verifier ? await signBtpPayloadWithSigner(payload, verifier.signer) : signBtpPayload(payload, verifier.pemFiles);
|
|
23
|
+
return { ...unsigned, signature };
|
|
24
|
+
}, verifierRefusal = async (verifiedBy) => {
|
|
25
|
+
const domain = domainOf(verifiedBy);
|
|
26
|
+
let host;
|
|
27
|
+
try {
|
|
28
|
+
host = await getHostAndSelector(verifiedBy);
|
|
29
|
+
} catch {
|
|
30
|
+
return {
|
|
31
|
+
error: BTP_ERROR_RESOLVE_DNS,
|
|
32
|
+
problem: `could not look up ${domain}'s BTPS host record; try again`
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
if (host?.operator?.toLowerCase() !== verifiedBy.toLowerCase())
|
|
36
|
+
return {
|
|
37
|
+
error: BTP_ERROR_VALIDATION,
|
|
38
|
+
problem: `the verifier does not run a BTPS server: ${verifiedBy} is not the operator of ${domain}`
|
|
39
|
+
};
|
|
40
|
+
}, verificationFacts = async (request, options = {}) => {
|
|
41
|
+
const verification = request.document?.verification;
|
|
42
|
+
if (!verification) return;
|
|
43
|
+
const { signature, ...unsigned } = verification, key = await signatureKey(unsigned.verifiedBy, unsigned.selector, options.keyResolver), signatureValid = !!key && verifySignature(signedStatement(request.from, unsigned), signature, key).isValid, expired = Date.parse(unsigned.expiresAt) <= (options.now ?? Date.now()), operator = (await getHostAndSelector(request.from))?.operator, verifier = unsigned.verifiedBy.toLowerCase();
|
|
44
|
+
return {
|
|
45
|
+
signatureValid,
|
|
46
|
+
expired,
|
|
47
|
+
verifierServesSender: !!operator && domainOf(verifier) === domainOf(operator),
|
|
48
|
+
verifierIsOperator: !!operator && verifier === operator.toLowerCase()
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
export {
|
|
52
|
+
signVerification,
|
|
53
|
+
verificationFacts,
|
|
54
|
+
verifierRefusal
|
|
55
|
+
};
|