@btps/sdk 1.1.3 → 1.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +422 -0
  2. package/bin/verify-evidence-bundle.mjs +96 -0
  3. package/dist/client/btpsAgent.d.ts +10 -1
  4. package/dist/client/btpsAgent.js +116 -18
  5. package/dist/client/btpsClient.d.ts +53 -7
  6. package/dist/client/btpsClient.js +265 -147
  7. package/dist/client/index.d.ts +1 -1
  8. package/dist/client/index.js +3 -1
  9. package/dist/client/libs/schema.js +78 -13
  10. package/dist/client/libs/timeouts.d.ts +6 -0
  11. package/dist/client/libs/timeouts.js +2 -1
  12. package/dist/client/types/index.d.ts +54 -2
  13. package/dist/core/authentication/BtpsAuthentication.d.ts +43 -1
  14. package/dist/core/authentication/BtpsAuthentication.js +152 -36
  15. package/dist/core/authentication/refreshSuccessor.js +47 -0
  16. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +17 -1
  17. package/dist/core/authentication/storage/InMemoryTokenStore.js +16 -4
  18. package/dist/core/authentication/types.d.ts +82 -0
  19. package/dist/core/crypto/contentKey.d.ts +34 -0
  20. package/dist/core/crypto/contentKey.js +64 -0
  21. package/dist/core/crypto/decryptVerify.d.ts +7 -1
  22. package/dist/core/crypto/decryptVerify.js +23 -5
  23. package/dist/core/crypto/decrypter-interface.d.ts +6 -0
  24. package/dist/core/crypto/index.d.ts +12 -0
  25. package/dist/core/crypto/index.js +7 -1
  26. package/dist/core/crypto/keyResolver.d.ts +48 -0
  27. package/dist/core/crypto/keyResolver.js +46 -0
  28. package/dist/core/crypto/pem-decrypter.d.ts +2 -0
  29. package/dist/core/crypto/pem-decrypter.js +13 -8
  30. package/dist/core/crypto/signEncrypt.d.ts +4 -1
  31. package/dist/core/crypto/signEncrypt.js +20 -5
  32. package/dist/core/crypto/types.d.ts +8 -1
  33. package/dist/core/delegation/BtpsDelegator.d.ts +4 -0
  34. package/dist/core/delegation/BtpsDelegator.js +3 -2
  35. package/dist/core/delegation/verifyTransporterSignature.d.ts +104 -0
  36. package/dist/core/delegation/verifyTransporterSignature.js +224 -0
  37. package/dist/core/error/constant.d.ts +39 -0
  38. package/dist/core/error/constant.js +55 -0
  39. package/dist/core/server/constants/btps-protocol.d.ts +21 -5
  40. package/dist/core/server/constants/btps-protocol.js +46 -8
  41. package/dist/core/server/constants/index.d.ts +7 -3
  42. package/dist/core/server/constants/index.js +19 -4
  43. package/dist/core/server/constants/limits.d.ts +18 -0
  44. package/dist/core/server/constants/limits.js +19 -1
  45. package/dist/core/server/constants/permissions.d.ts +38 -0
  46. package/dist/core/server/constants/permissions.js +38 -0
  47. package/dist/core/server/schemas/artifacts/agentSchema.js +2 -1
  48. package/dist/core/server/schemas/artifacts/artifacts.js +7 -1
  49. package/dist/core/server/schemas/artifacts/controlSchema.js +1 -1
  50. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +10 -1
  51. package/dist/core/server/schemas/artifacts/transporterSchema.js +92 -12
  52. package/dist/core/server/schemas/bounded.js +2 -2
  53. package/dist/core/server/schemas/btpsDocsSchema.d.ts +34185 -1084
  54. package/dist/core/server/schemas/btpsDocsSchema.js +300 -42
  55. package/dist/core/server/schemas/helpers.d.ts +9580 -0
  56. package/dist/core/server/schemas/helpers.js +76 -12
  57. package/dist/core/server/schemas/keyChainSchema.js +53 -0
  58. package/dist/core/server/schemas/responseSchema.js +52 -9
  59. package/dist/core/server/schemas/schema.js +3 -1
  60. package/dist/core/server/schemas/trustValues.d.ts +105 -0
  61. package/dist/core/server/schemas/trustValues.js +117 -0
  62. package/dist/core/server/types.d.ts +104 -6
  63. package/dist/core/storage/AbstractIdentityStore.d.ts +9 -0
  64. package/dist/core/storage/JsonIdentityStore.d.ts +3 -0
  65. package/dist/core/storage/JsonIdentityStore.js +3 -0
  66. package/dist/core/storage/types.d.ts +2 -0
  67. package/dist/core/trust/agreements.d.ts +107 -0
  68. package/dist/core/trust/agreements.js +116 -0
  69. package/dist/core/trust/evidence.d.ts +220 -0
  70. package/dist/core/trust/evidence.js +334 -0
  71. package/dist/core/trust/index.d.ts +10 -0
  72. package/dist/core/trust/index.js +14 -1
  73. package/dist/core/trust/keyRotation.d.ts +148 -0
  74. package/dist/core/trust/keyRotation.js +267 -0
  75. package/dist/core/trust/permissions.d.ts +114 -0
  76. package/dist/core/trust/permissions.js +115 -0
  77. package/dist/core/trust/shaping.d.ts +42 -0
  78. package/dist/core/trust/shaping.js +47 -0
  79. package/dist/core/trust/storage/AbstractTrustStore.d.ts +2 -1
  80. package/dist/core/trust/storage/JsonTrustStore.d.ts +3 -2
  81. package/dist/core/trust/timestamps.d.ts +49 -0
  82. package/dist/core/trust/timestamps.js +78 -0
  83. package/dist/core/trust/trustUtils.d.ts +13 -2
  84. package/dist/core/trust/trustUtils.js +28 -3
  85. package/dist/core/trust/types.d.ts +302 -2
  86. package/dist/core/trust/verification.d.ts +52 -0
  87. package/dist/core/trust/verification.js +55 -0
  88. package/dist/server/btpsServer.d.ts +70 -5
  89. package/dist/server/btpsServer.js +263 -143
  90. package/dist/server/index.d.ts +3 -0
  91. package/dist/server/index.js +17 -1
  92. package/dist/server/libs/agreementOrderCheck.d.ts +29 -0
  93. package/dist/server/libs/agreementOrderCheck.js +29 -0
  94. package/dist/server/libs/artifactTimeWindow.d.ts +2 -2
  95. package/dist/server/libs/artifactTimeWindow.js +2 -1
  96. package/dist/server/libs/detailsRequestLimit.d.ts +27 -0
  97. package/dist/server/libs/detailsRequestLimit.js +28 -0
  98. package/dist/server/libs/detailsResponseCheck.d.ts +27 -0
  99. package/dist/server/libs/detailsResponseCheck.js +27 -0
  100. package/dist/server/libs/eventChainCheck.d.ts +31 -0
  101. package/dist/server/libs/eventChainCheck.js +39 -0
  102. package/dist/server/libs/inFlightLimit.d.ts +10 -0
  103. package/dist/server/libs/inFlightLimit.js +7 -1
  104. package/dist/server/libs/index.d.ts +5 -0
  105. package/dist/server/libs/index.js +10 -0
  106. package/dist/server/libs/keyChains.d.ts +14 -0
  107. package/dist/server/libs/keyChains.js +17 -0
  108. package/dist/server/libs/wrapForAgent.d.ts +20 -0
  109. package/dist/server/libs/wrapForAgent.js +36 -0
  110. package/dist/server/types.d.ts +95 -9
  111. package/package.json +12 -3
@@ -5,7 +5,7 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
  import { BTPErrorException } from '../error/index.js';
8
- import { BTPAgentArtifact, BTPArtifact, BTPDelegation, BTPDocType, BTPServerResponse, BTPTransporterArtifact } from '../server/types.js';
8
+ import { BTPAgentArtifact, BTPArtifact, BTPDelegation, BTPDocType, BTPServerResponse, BTPShaped, BTPTransporterArtifact } from '../server/types.js';
9
9
  import type { Signer } from './signer-interface.js';
10
10
  import type { Decrypter } from './decrypter-interface.js';
11
11
  export type EncryptionMode = 'none' | 'standardEncrypt' | '2faEncrypt';
@@ -39,6 +39,11 @@ export type BTPCryptoOptions = {
39
39
  algorithm: EncryptionAlgorithmType;
40
40
  mode: EncryptionMode;
41
41
  };
42
+ /**
43
+ * Since 1.2, for a trust request with permissions: whether to send it as 1.1 allows when the
44
+ * receiver's server speaks 1.1 (the default), or refuse with its version (`false`).
45
+ */
46
+ versionFallback?: boolean;
42
47
  };
43
48
  type WithGenericDocument<TArtifact extends BTPArtifact, T> = Omit<TArtifact, 'document'> & {
44
49
  document: T;
@@ -47,6 +52,8 @@ export type BTPCryptoArtifact<T = BTPDocType> = WithGenericDocument<BTPAgentArti
47
52
  export interface BTPCryptoResponse<T = BTPDocType> {
48
53
  payload?: BTPCryptoArtifact<T> | BTPServerResponse<T>;
49
54
  error?: BTPErrorException;
55
+ /** Since 1.2: a trust request sent as its 1.1 receiver allows, and what it left out */
56
+ shaped?: BTPShaped;
50
57
  }
51
58
  export interface VerifyEncryptedPayload<T = unknown | string> {
52
59
  document?: T;
@@ -7,12 +7,15 @@
7
7
  import type { BTPTransporterArtifact, BTPDelegation, BTPAttestation } from '../server/types.js';
8
8
  import type { BTPSigningKey, PemKeys } from '../crypto/types.js';
9
9
  import type { Signer } from '../crypto/signer-interface.js';
10
+ import type { BtpsKeyResolver } from '../crypto/keyResolver.js';
10
11
  /**
11
12
  * Delegator configuration options
12
13
  */
13
14
  export type BtpsDelegatorOptions = {
14
15
  identity: string;
15
16
  autoInit?: boolean;
17
+ /** Since 1.2: finds the delegator's own published key; without it, DNS as before */
18
+ keyResolver?: BtpsKeyResolver;
16
19
  } & ({
17
20
  privateKey: PemKeys['privateKey'];
18
21
  } | {
@@ -25,6 +28,7 @@ export type BtpsDelegatorOptions = {
25
28
  export declare class BtpsDelegator {
26
29
  private readonly identity;
27
30
  private readonly key;
31
+ private readonly keyResolver?;
28
32
  private publicKey?;
29
33
  private selector;
30
34
  private isInitialized;
@@ -12,12 +12,13 @@ import { BTP_ERROR_SIG_VERIFICATION, BTPErrorException } from "../error/index.js
12
12
  class BtpsDelegator {
13
13
  identity;
14
14
  key;
15
+ keyResolver;
15
16
  publicKey;
16
17
  selector = "btps1";
17
18
  isInitialized = !1;
18
19
  ready;
19
20
  constructor(options) {
20
- this.identity = options.identity, this.key = "signer" in options ? options.signer : options.privateKey, options.autoInit !== !1 && (this.ready = this.init(), this.ready.catch(() => {
21
+ this.identity = options.identity, this.key = "signer" in options ? options.signer : options.privateKey, this.keyResolver = options.keyResolver, options.autoInit !== !1 && (this.ready = this.init(), this.ready.catch(() => {
21
22
  }));
22
23
  }
23
24
  async init() {
@@ -37,7 +38,7 @@ class BtpsDelegator {
37
38
  const dnsHostAndSelector = await getHostAndSelector(this.identity);
38
39
  if (!dnsHostAndSelector) return { isValid: !1, publicKey: void 0 };
39
40
  this.selector = dnsHostAndSelector.selector;
40
- const publicKey = await resolvePublicKey(this.identity, this.selector);
41
+ const publicKey = this.keyResolver ? await this.keyResolver.resolvePublicKey(this.identity, this.selector, "verify") : await resolvePublicKey(this.identity, this.selector);
41
42
  return publicKey ? { isValid: typeof this.key == "string" ? this.isKeyPairMatching(this.key, publicKey) : await this.isSignerMatching(this.key, publicKey), publicKey } : { isValid: !1, publicKey: void 0 };
42
43
  }
43
44
  async isSignerMatching(signer, publicKeyPem) {
@@ -0,0 +1,104 @@
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 { BTPErrorException } from '../error/index.js';
8
+ import type { BTPAttestation, BTPDelegation, BTPTransporterArtifact } from '../server/types.js';
9
+ import type { BtpsKeyResolver } from '../crypto/keyResolver.js';
10
+ import { type BTPCheckedKeyChain } from '../trust/keyRotation.js';
11
+ import type { BTPKeyChainFacts, BTPKeyChainLookup } from '../trust/types.js';
12
+ type Verified = {
13
+ isValid: boolean;
14
+ error?: BTPErrorException;
15
+ };
16
+ /** A signature key: from the resolver when one is given, else from DNS, as without one. */
17
+ export declare const signatureKey: (identity: string, selector: string, keyResolver?: BtpsKeyResolver) => Promise<string | undefined>;
18
+ /**
19
+ * Since 1.2: how a verifier checks a signing key against its identity's key
20
+ * chain, when it does: where it gets a chain, how long a key rotated away as
21
+ * planned is still taken, and how far ahead of its clock a record may be dated.
22
+ */
23
+ export type BTPKeyChainCheck = {
24
+ resolveKeyChain: (identity: string) => Promise<BTPKeyChainLookup>;
25
+ retiredKeyGraceSeconds: number;
26
+ maxSkewSeconds?: number;
27
+ /**
28
+ * Chains already checked, by identity, each kept for `checkedForSeconds`
29
+ * while its records are the same, so a chain's signatures are checked once
30
+ * per window, not on every arrival.
31
+ */
32
+ checked?: Map<string, {
33
+ hash: string;
34
+ chain: BTPCheckedKeyChain;
35
+ until: number;
36
+ }>;
37
+ checkedForSeconds?: number;
38
+ };
39
+ /**
40
+ * Since 1.2: `identity`'s key chain as a verifier online takes it: asked of its
41
+ * host, checked once, and anchored on what DNS publishes for it.
42
+ *
43
+ * - `none`: no chain to be had (a 1.1 host, an unreachable one) or an empty
44
+ * one: its keys are DNS's, as in 1.1;
45
+ * - `refused`: an answer that fails its checks, a DNS lookup that fails (never
46
+ * taken for host-only), or a chain `keyChainProblem` refuses;
47
+ * - `checked`: the chain's facts, anchored online.
48
+ *
49
+ * The chain must end at a key DNS publishes for the identity, at its last
50
+ * selector or the domain's `s=`; only when DNS has neither is it host-only.
51
+ */
52
+ export declare const onlineKeyChain: (identity: string, keyChains: BTPKeyChainCheck) => Promise<{
53
+ status: "none";
54
+ } | {
55
+ status: "refused";
56
+ error: BTPErrorException;
57
+ } | {
58
+ status: "checked";
59
+ facts: BTPKeyChainFacts;
60
+ }>;
61
+ /**
62
+ * Since 1.2: the key `identity` signs with at `selector`, checked against its
63
+ * key chain when `keyChains` is given. With no chain to be had (a 1.1 host, an
64
+ * unreachable one) or an empty one, it is the DNS key, as in 1.1. Otherwise:
65
+ *
66
+ * - the chain must come checked from the host, and end at a key DNS
67
+ * publishes for the identity, at the chain's last selector or the domain's
68
+ * `s=`. Only when DNS has neither is the identity host-only. A DNS lookup
69
+ * that fails refuses: it is never taken for host-only;
70
+ * - the key is the chain's key at `selector`, or the chain's key DNS
71
+ * publishes there (the same key under a later selector);
72
+ * - an expired key is `BTP_ERROR_KEY_REVOKED`, and a key rotated away as
73
+ * planned past the grace `BTP_ERROR_KEY_RETIRED`.
74
+ *
75
+ * No key and no error: none found, refused by the caller as before.
76
+ */
77
+ export declare const checkedSignatureKey: (identity: string, selector: string, keyResolver?: BtpsKeyResolver, keyChains?: BTPKeyChainCheck) => Promise<{
78
+ key?: string;
79
+ error?: BTPErrorException;
80
+ }>;
81
+ /** A delegation's attestation, signed by the attestor over the delegation. */
82
+ export declare const verifyAttestation: (delegation: Omit<BTPDelegation, "attestation"> & {
83
+ attestation: BTPAttestation;
84
+ }, keyResolver?: BtpsKeyResolver, keyChains?: BTPKeyChainCheck) => Promise<Verified>;
85
+ /**
86
+ * A delegated artifact: the delegation is allowed (by the sender itself, or its
87
+ * domain's operator), attested by the operator when the sender delegates for
88
+ * itself, signed by its delegator, and the artifact is signed by the agent.
89
+ */
90
+ export declare const verifyDelegation: (artifactWithDelegation: Omit<BTPTransporterArtifact, "delegation"> & {
91
+ delegation: BTPDelegation;
92
+ }, keyResolver?: BtpsKeyResolver, keyChains?: BTPKeyChainCheck) => Promise<Verified>;
93
+ /**
94
+ * Since 1.2, exported: a transporter artifact's signature, checked as a server
95
+ * checks it on arrival. Signed by its sender's own key from DNS, or, when it is
96
+ * delegated, through `verifyDelegation`. On success it also gives the key that
97
+ * signed the artifact itself, the one to verify it against when decrypting.
98
+ * Since 1.2, every key is found through `keyResolver` when one is given, and,
99
+ * with `keyChains`, checked against its identity's key chain.
100
+ */
101
+ export declare const verifyTransporterSignature: (artifact: BTPTransporterArtifact, keyResolver?: BtpsKeyResolver, keyChains?: BTPKeyChainCheck) => Promise<Verified & {
102
+ signerKey?: string;
103
+ }>;
104
+ export {};
@@ -0,0 +1,224 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+
8
+ import { BTPErrorException } from "../error/index.js";
9
+ import {
10
+ BTP_ERROR_ATTESTATION_VERIFICATION,
11
+ BTP_ERROR_DELEGATION_INVALID,
12
+ BTP_ERROR_DELEGATION_SIG_VERIFICATION,
13
+ BTP_ERROR_RESOLVE_PUBKEY
14
+ } from "../error/constant.js";
15
+ import { createHash } from "crypto";
16
+ import { getFingerprintFromPem, verifySignature } from "../crypto/index.js";
17
+ import { canonicalizeValue } from "../crypto/jcs.js";
18
+ import {
19
+ getDnsIdentityParts,
20
+ getHostAndSelector,
21
+ isDelegationAllowed,
22
+ resolvePublicKey
23
+ } from "../utils/index.js";
24
+ import {
25
+ checkKeyChain,
26
+ keyAt,
27
+ keyChainFactsOf,
28
+ keyChainProblemOf,
29
+ keyChainSignerProblem
30
+ } from "../trust/keyRotation.js";
31
+ const signatureKey = (identity, selector, keyResolver) => keyResolver ? keyResolver.resolvePublicKey(identity, selector, "verify") : resolvePublicKey(identity, selector), CHECKED_SWEEP_AT = 1e4, checkedChainOf = (identity, records, keyChains) => {
32
+ const { checked, checkedForSeconds = 0 } = keyChains;
33
+ if (!checked || checkedForSeconds <= 0) return checkKeyChain(records, identity);
34
+ const key = identity.toLowerCase(), hash = createHash("sha256").update(canonicalizeValue(records), "utf8").digest("hex"), now = Date.now(), kept = checked.get(key);
35
+ if (kept && kept.hash === hash && kept.until > now) return kept.chain;
36
+ const chain = checkKeyChain(records, identity);
37
+ if (checked.size >= CHECKED_SWEEP_AT)
38
+ for (const [name, entry] of checked) entry.until <= now && checked.delete(name);
39
+ return checked.set(key, { hash, chain, until: now + checkedForSeconds * 1e3 }), chain;
40
+ }, refused = (error, cause) => ({
41
+ error: new BTPErrorException(error, { cause })
42
+ }), onlineKeyChain = async (identity, keyChains) => {
43
+ const lookup = await keyChains.resolveKeyChain(identity);
44
+ if (lookup.status === "invalid")
45
+ return {
46
+ status: "refused",
47
+ ...refused(BTP_ERROR_RESOLVE_PUBKEY, `${identity}'s key chain is refused: ${lookup.reason}`)
48
+ };
49
+ if (lookup.status === "unavailable" || lookup.records.length === 0) return { status: "none" };
50
+ const chain = checkedChainOf(identity, lookup.records, keyChains);
51
+ let dns;
52
+ try {
53
+ const fingerprintAt = async (at) => {
54
+ const pem = at === void 0 ? void 0 : await getDnsIdentityParts(identity, at, "pem");
55
+ return typeof pem == "string" ? getFingerprintFromPem(pem) : void 0;
56
+ }, last = keyChainFactsOf(chain, {}).keys.at(-1)?.selector, domain = (await getHostAndSelector(identity))?.selector, fingerprints = [await fingerprintAt(last), await fingerprintAt(domain)].filter(
57
+ (fingerprint) => fingerprint !== void 0
58
+ );
59
+ dns = fingerprints.length ? { kind: "published", fingerprints } : { kind: "hostOnly" };
60
+ } catch (error) {
61
+ return {
62
+ status: "refused",
63
+ ...refused(
64
+ BTP_ERROR_RESOLVE_PUBKEY,
65
+ `could not read ${identity}'s keys in DNS: ${error instanceof Error ? error.message : error}`
66
+ )
67
+ };
68
+ }
69
+ const problem = keyChainProblemOf(chain, {
70
+ fromOperator: !0,
71
+ dns,
72
+ maxSkewSeconds: keyChains.maxSkewSeconds
73
+ });
74
+ return problem ? {
75
+ status: "refused",
76
+ ...refused(BTP_ERROR_RESOLVE_PUBKEY, `${identity}'s key chain is refused: ${problem}`)
77
+ } : {
78
+ status: "checked",
79
+ facts: keyChainFactsOf(chain, { online: { fromOperator: !0, dns } })
80
+ };
81
+ }, checkedSignatureKey = async (identity, selector, keyResolver, keyChains) => {
82
+ if (!keyChains) return { key: await signatureKey(identity, selector, keyResolver) };
83
+ const online = await onlineKeyChain(identity, keyChains);
84
+ if (online.status === "refused") return { error: online.error };
85
+ if (online.status === "none") return { key: await signatureKey(identity, selector, keyResolver) };
86
+ const { facts } = online;
87
+ let key = keyAt(facts, { selector });
88
+ if (!key) {
89
+ const published = await signatureKey(identity, selector, keyResolver);
90
+ if (key = published ? keyAt(facts, { fingerprint: getFingerprintFromPem(published) }) : void 0, !key)
91
+ return refused(
92
+ BTP_ERROR_RESOLVE_PUBKEY,
93
+ `${selector} names no key of ${identity}'s key chain`
94
+ );
95
+ }
96
+ const refusal = keyChainSignerProblem(key, {
97
+ retiredKeyGraceSeconds: keyChains.retiredKeyGraceSeconds
98
+ });
99
+ return refusal ? refused(refusal, `${identity}'s key at ${selector}`) : { key: key.publicKey };
100
+ }, verifyAttestation = async (delegation, keyResolver, keyChains) => {
101
+ const { attestation, ...restDelegation } = delegation, { signature, ...restAttestation } = attestation, { key: attestorPubKey, error: keyError } = await checkedSignatureKey(
102
+ attestation.signedBy,
103
+ attestation.selector,
104
+ keyResolver,
105
+ keyChains
106
+ );
107
+ if (keyError) return { isValid: !1, error: keyError };
108
+ if (!attestorPubKey)
109
+ return {
110
+ isValid: !1,
111
+ error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
112
+ cause: `Attestor ${attestation.signedBy} public key not found`,
113
+ meta: { attestation }
114
+ })
115
+ };
116
+ const signedMsg = { ...restDelegation, attestation: restAttestation }, { isValid, error } = verifySignature(signedMsg, signature, attestorPubKey);
117
+ return {
118
+ isValid,
119
+ error: error ? new BTPErrorException(BTP_ERROR_ATTESTATION_VERIFICATION, {
120
+ cause: `Attestation signature verification failed of attestor ${attestation.signedBy}`,
121
+ meta: { attestation }
122
+ }) : void 0
123
+ };
124
+ }, verifyDelegation = async (artifactWithDelegation, keyResolver, keyChains) => {
125
+ const operator = (await getHostAndSelector(artifactWithDelegation.from))?.operator;
126
+ if (!isDelegationAllowed(artifactWithDelegation, operator))
127
+ return {
128
+ isValid: !1,
129
+ error: new BTPErrorException(BTP_ERROR_DELEGATION_INVALID, {
130
+ cause: operator ? `Delegation is not allowed: ${artifactWithDelegation.delegation.signedBy} is not the operator of ${artifactWithDelegation.from}'s domain` : `Delegation is not allowed: ${artifactWithDelegation.from}'s domain declares no operator`
131
+ })
132
+ };
133
+ const { delegation, ...restArtifact } = artifactWithDelegation;
134
+ if (delegation.signedBy === artifactWithDelegation.from && !delegation.attestation)
135
+ return {
136
+ isValid: !1,
137
+ error: new BTPErrorException(BTP_ERROR_DELEGATION_INVALID, {
138
+ cause: "Custom managed domain delegation requires attestation. Either provide attestation or directly send without delegation via transporter",
139
+ meta: {
140
+ delegation,
141
+ from: artifactWithDelegation.from
142
+ }
143
+ })
144
+ };
145
+ if (delegation.attestation) {
146
+ if (delegation.attestation.signedBy !== operator)
147
+ return {
148
+ isValid: !1,
149
+ error: new BTPErrorException(BTP_ERROR_ATTESTATION_VERIFICATION, {
150
+ cause: `${delegation.attestation.signedBy} is not the operator of ${artifactWithDelegation.from}'s domain`
151
+ })
152
+ };
153
+ const { isValid: isValid2, error: error2 } = await verifyAttestation(
154
+ delegation,
155
+ keyResolver,
156
+ keyChains
157
+ );
158
+ if (!isValid2) return { isValid: isValid2, error: error2 };
159
+ }
160
+ const { key: delegatorPubKey, error: keyError } = await checkedSignatureKey(
161
+ delegation.signedBy,
162
+ delegation.selector,
163
+ keyResolver,
164
+ keyChains
165
+ );
166
+ if (keyError) return { isValid: !1, error: keyError };
167
+ if (!delegatorPubKey)
168
+ return {
169
+ isValid: !1,
170
+ error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
171
+ cause: `Delegator ${delegation.signedBy} public key not found`,
172
+ meta: { delegation }
173
+ })
174
+ };
175
+ const { signature, attestation, ...restDelegation } = delegation, signedMsg = { ...artifactWithDelegation, delegation: restDelegation }, { isValid: isValidDelegation } = verifySignature(signedMsg, signature, delegatorPubKey);
176
+ if (!isValidDelegation)
177
+ return {
178
+ isValid: isValidDelegation,
179
+ error: new BTPErrorException(BTP_ERROR_DELEGATION_SIG_VERIFICATION, {
180
+ cause: `Delegation signature verification failed of delegator ${delegation.signedBy}`,
181
+ meta: {
182
+ delegation
183
+ }
184
+ })
185
+ };
186
+ const { signature: origSignature, ...origSignedMsg } = restArtifact, { isValid, error } = verifySignature(origSignedMsg, origSignature, delegation.agentPubKey);
187
+ return {
188
+ isValid,
189
+ error: error ? new BTPErrorException(BTP_ERROR_DELEGATION_SIG_VERIFICATION, {
190
+ cause: `Delegated artifact's original artifact signature verification failed of agent ${delegation.agentId}`,
191
+ meta: {
192
+ delegation
193
+ }
194
+ }) : void 0
195
+ };
196
+ }, verifyTransporterSignature = async (artifact, keyResolver, keyChains) => {
197
+ if (artifact.delegation) {
198
+ const delegated = await verifyDelegation(
199
+ artifact,
200
+ keyResolver,
201
+ keyChains
202
+ );
203
+ return delegated.isValid ? { ...delegated, signerKey: artifact.delegation.agentPubKey } : delegated;
204
+ }
205
+ const { signature, ...signedMsg } = artifact, { key: publicKey, error: keyError } = await checkedSignatureKey(
206
+ artifact.from,
207
+ artifact.selector,
208
+ keyResolver,
209
+ keyChains
210
+ );
211
+ if (keyError) return { isValid: !1, error: keyError };
212
+ if (!publicKey)
213
+ return { isValid: !1, error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY) };
214
+ const verified = verifySignature(signedMsg, signature, publicKey);
215
+ return verified.isValid ? { ...verified, signerKey: publicKey } : verified;
216
+ };
217
+ export {
218
+ checkedSignatureKey,
219
+ onlineKeyChain,
220
+ signatureKey,
221
+ verifyAttestation,
222
+ verifyDelegation,
223
+ verifyTransporterSignature
224
+ };
@@ -29,6 +29,20 @@ export declare const BTP_ERROR_TRUST_EXPIRED: BTPError;
29
29
  export declare const BTP_ERROR_TRUST_REVOKED: BTPError;
30
30
  export declare const BTP_ERROR_TRUST_ALREADY_ACTIVE: BTPError;
31
31
  export declare const BTP_ERROR_EVENT_UNRELATED: BTPError;
32
+ /**
33
+ * Since 1.2: a `withdrawn` or `follows` from the invoice's issuer, a
34
+ * `withdrawn` that does not take back the payer's own open proposal about the
35
+ * same invoice, or a `follows` that names no `withdrawn` about it. It
36
+ * concerns the sender's own events, so the sender is told which.
37
+ */
38
+ export declare const BTP_ERROR_EVENT_CHAIN: BTPError;
39
+ /**
40
+ * Since 1.2: an agreement's answer that is not its sender's turn: from someone
41
+ * who is not a signer, a second answer, out of turn, or after a decline.
42
+ * Raised by the platform's own check in flight (`agreementOrderCheck`
43
+ * middleware), never by the server, with the broken rule in its message.
44
+ */
45
+ export declare const BTP_ERROR_AGREEMENT_ORDER: BTPError;
32
46
  export declare const BTP_ERROR_RESOLVE_DNS: BTPError;
33
47
  export declare const BTP_ERROR_RESOLVE_PUBKEY: BTPError;
34
48
  export declare const BTP_ERROR_RATE_LIMITER: BTPError;
@@ -53,7 +67,32 @@ export declare const BTP_ERROR_UNSUPPORTED_ENCRYPT: BTPError;
53
67
  export declare const BTP_ERROR_DECRYPTION_UNINTENDED: BTPError;
54
68
  export declare const BTP_ERROR_UNKNOWN: BTPError;
55
69
  export declare const BTP_ERROR_AGENT_ID: BTPError;
70
+ /** Since 1.2: a sync that did not come from a device of its own address. */
71
+ export declare const BTP_ERROR_SYNC_NOT_ALLOWED: BTPError;
72
+ /** Since 1.2: something a trust's permissions do not cover, such as a name the request never asked for. */
73
+ export declare const BTP_ERROR_PERMISSION: BTPError;
74
+ /** Since 1.2: a trust answer that leaves out a required permission, or one that cannot be checked. */
75
+ export declare const BTP_ERROR_PERMISSION_REQUIRED: BTPError;
76
+ /** Since 1.2: a document whose type is not the documentType its envelope names. */
77
+ export declare const BTP_ERROR_DOCUMENT_TYPE_MISMATCH: BTPError;
78
+ /** Since 1.2: a details refresh naming a detail its receiver or answerer does not hold by the trust. */
79
+ export declare const BTP_ERROR_DETAILS_NOT_HELD: BTPError;
80
+ /** Since 1.2: a details request over the limit the provider sets; its meta says when to ask again. */
81
+ export declare const BTP_ERROR_DETAILS_RATE_LIMITED: BTPError;
56
82
  export declare const BTP_ERROR_KEY_ROTATION_PROOF: BTPError;
83
+ /** Since 1.2: the device key is older than the server's maxKeyAgeMs. */
84
+ export declare const BTP_ERROR_KEY_TOO_OLD: BTPError;
85
+ /**
86
+ * Since 1.2: signed by a key its identity rotated away from, planned, longer
87
+ * ago than the receiver's retiredKeyGraceSeconds. A stale key: sign again
88
+ * with the current one.
89
+ */
90
+ export declare const BTP_ERROR_KEY_RETIRED: BTPError;
91
+ /**
92
+ * Since 1.2: signed by a key its identity rotated away from with immediate
93
+ * expiry, or expired: compromised or lost. A security incident, not a stale key.
94
+ */
95
+ export declare const BTP_ERROR_KEY_REVOKED: BTPError;
57
96
  export declare const BTP_ERROR_ARTIFACT_TIME_WINDOW: BTPError;
58
97
  export declare const BTP_ERROR_ARTIFACT_TOO_LARGE: BTPError;
59
98
  export declare const BTP_ERROR_VERSION_UNSUPPORTED: BTPError;
@@ -48,6 +48,14 @@ const BTP_ERROR_SOCKET_CLOSED = {
48
48
  code: "BTP_ERROR_EVENT_UNRELATED",
49
49
  message: "Event does not relate to an artifact exchanged between its parties",
50
50
  status: 400
51
+ }, BTP_ERROR_EVENT_CHAIN = {
52
+ code: "BTP_ERROR_EVENT_CHAIN",
53
+ message: "Event names an earlier event it cannot follow or withdraw",
54
+ status: 400
55
+ }, BTP_ERROR_AGREEMENT_ORDER = {
56
+ code: "BTP_ERROR_AGREEMENT_ORDER",
57
+ message: "Answer is not its sender's turn",
58
+ status: 400
51
59
  }, BTP_ERROR_RESOLVE_DNS = {
52
60
  code: "BTP_ERROR_RESOLVE_DNS",
53
61
  message: "No valid DNS record found"
@@ -110,10 +118,46 @@ const BTP_ERROR_SOCKET_CLOSED = {
110
118
  code: "BTP_ERROR_AGENT_ID",
111
119
  message: "An agent id names a registered device, not an identity",
112
120
  status: 403
121
+ }, BTP_ERROR_SYNC_NOT_ALLOWED = {
122
+ code: "BTP_ERROR_SYNC_NOT_ALLOWED",
123
+ message: "A sync comes only from a device of its own address, inside that device's artifact.send",
124
+ status: 403
125
+ }, BTP_ERROR_PERMISSION = {
126
+ code: "BTP_ERROR_PERMISSION",
127
+ message: "This trust does not permit it",
128
+ status: 403
129
+ }, BTP_ERROR_PERMISSION_REQUIRED = {
130
+ code: "BTP_ERROR_PERMISSION_REQUIRED",
131
+ message: "The answer does not grant every permission the request requires",
132
+ status: 403
133
+ }, BTP_ERROR_DOCUMENT_TYPE_MISMATCH = {
134
+ code: "BTP_ERROR_DOCUMENT_TYPE_MISMATCH",
135
+ message: "The document is not the type its envelope names",
136
+ status: 400
137
+ }, BTP_ERROR_DETAILS_NOT_HELD = {
138
+ code: "BTP_ERROR_DETAILS_NOT_HELD",
139
+ message: "That detail is not held by this trust",
140
+ status: 403
141
+ }, BTP_ERROR_DETAILS_RATE_LIMITED = {
142
+ code: "BTP_ERROR_DETAILS_RATE_LIMITED",
143
+ message: "Too many details requests on this trust. Ask again later",
144
+ status: 429
113
145
  }, BTP_ERROR_KEY_ROTATION_PROOF = {
114
146
  code: "BTP_ERROR_KEY_ROTATION_PROOF",
115
147
  message: "A new device key needs a proof signed by that key",
116
148
  status: 401
149
+ }, BTP_ERROR_KEY_TOO_OLD = {
150
+ code: "BTP_ERROR_KEY_TOO_OLD",
151
+ message: "This device key is older than the server allows. Move to a new key first",
152
+ status: 401
153
+ }, BTP_ERROR_KEY_RETIRED = {
154
+ code: "BTP_ERROR_KEY_RETIRED",
155
+ message: "The key that signed this is retired. Sign with the current key",
156
+ status: 401
157
+ }, BTP_ERROR_KEY_REVOKED = {
158
+ code: "BTP_ERROR_KEY_REVOKED",
159
+ message: "The key that signed this is revoked: it may be in other hands",
160
+ status: 401
117
161
  }, BTP_ERROR_ARTIFACT_TIME_WINDOW = {
118
162
  code: "BTP_ERROR_ARTIFACT_TIME_WINDOW",
119
163
  message: "Artifact was not issued within the time window of this server",
@@ -159,6 +203,7 @@ const BTP_ERROR_SOCKET_CLOSED = {
159
203
  export {
160
204
  BTPS_ERROR_ACTION_TYPE,
161
205
  BTP_ERROR_AGENT_ID,
206
+ BTP_ERROR_AGREEMENT_ORDER,
162
207
  BTP_ERROR_ARTIFACT_NOT_ACCEPTED,
163
208
  BTP_ERROR_ARTIFACT_TIME_WINDOW,
164
209
  BTP_ERROR_ARTIFACT_TOO_LARGE,
@@ -170,12 +215,21 @@ export {
170
215
  BTP_ERROR_DECRYPTION_UNINTENDED,
171
216
  BTP_ERROR_DELEGATION_INVALID,
172
217
  BTP_ERROR_DELEGATION_SIG_VERIFICATION,
218
+ BTP_ERROR_DETAILS_NOT_HELD,
219
+ BTP_ERROR_DETAILS_RATE_LIMITED,
220
+ BTP_ERROR_DOCUMENT_TYPE_MISMATCH,
221
+ BTP_ERROR_EVENT_CHAIN,
173
222
  BTP_ERROR_EVENT_UNRELATED,
174
223
  BTP_ERROR_IDENTITY,
175
224
  BTP_ERROR_IDENTITY_NOT_FOUND,
176
225
  BTP_ERROR_INVALID_ACTION,
177
226
  BTP_ERROR_INVALID_JSON,
227
+ BTP_ERROR_KEY_RETIRED,
228
+ BTP_ERROR_KEY_REVOKED,
178
229
  BTP_ERROR_KEY_ROTATION_PROOF,
230
+ BTP_ERROR_KEY_TOO_OLD,
231
+ BTP_ERROR_PERMISSION,
232
+ BTP_ERROR_PERMISSION_REQUIRED,
179
233
  BTP_ERROR_PRIVACY_TYPE,
180
234
  BTP_ERROR_RATE_LIMITER,
181
235
  BTP_ERROR_RESOLVE_DNS,
@@ -184,6 +238,7 @@ export {
184
238
  BTP_ERROR_SIG_VERIFICATION,
185
239
  BTP_ERROR_SOCKET_CLOSED,
186
240
  BTP_ERROR_SOCKET_TIMEOUT,
241
+ BTP_ERROR_SYNC_NOT_ALLOWED,
187
242
  BTP_ERROR_TEMPORARILY_UNAVAILABLE,
188
243
  BTP_ERROR_TIMEOUT,
189
244
  BTP_ERROR_TRUST_ALREADY_ACTIVE,
@@ -4,14 +4,30 @@
4
4
  * Licensed under the Apache License, Version 2.0
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
- export declare const BTP_PROTOCOL_VERSION = "1.1.0";
7
+ export declare const BTP_PROTOCOL_VERSION = "1.2.0";
8
8
  export declare const MIN_SUPPORTED_VERSION = "1.1.0";
9
- export declare const MAX_SUPPORTED_VERSION = "1.1.0";
9
+ export declare const MAX_SUPPORTED_VERSION = "1.2.0";
10
+ /** How far a server lets an artifact's `issuedAt` be from its own clock unless it sets `maxArtifactAgeSeconds`: 5 minutes. */
11
+ export declare const DEFAULT_MAX_ARTIFACT_AGE_SECONDS = 300;
10
12
  /**
11
- * Whether an artifact's `version` is one this SDK speaks. Compared by major and
12
- * minor only, so a later 1.1.x is still 1.1. 1.1 refuses 1.0: no independent
13
- * provider runs 1.0, so the break costs nothing now.
13
+ * Whether an artifact's `version` is one this SDK speaks: 1.1 and 1.2. It
14
+ * refuses 1.0: no independent provider runs 1.0, so the break costs nothing.
14
15
  */
15
16
  export declare const isSupportedVersion: (version: unknown) => boolean;
17
+ /** Whether `version` is older than `than`, by major and minor. One that is not a version is older. */
18
+ export declare const isVersionBelow: (version: string, than: string) => boolean;
19
+ /** An artifact before it is signed: its type, its document, and the rest of its envelope. */
20
+ export type BTPVersionedArtifact = {
21
+ type?: string;
22
+ document?: unknown;
23
+ [key: string]: unknown;
24
+ };
25
+ /**
26
+ * The version an artifact is stamped with: 1.1.0 whenever everything in it can
27
+ * be said in 1.1, so a 1.1 receiver takes it, and 1.2.0 only when it uses
28
+ * something 1.2 adds. An encrypted artifact is stamped from its document before
29
+ * it is encrypted.
30
+ */
31
+ export declare const artifactVersion: (artifact: BTPVersionedArtifact) => string;
16
32
  export declare const BTPS_DNS_HOST_NAME_SPACE = "_btps.host";
17
33
  export declare const BTPS_DNS_IDENTITY_NAME_SPACE = "_btps.identity";
@@ -5,21 +5,59 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
 
8
- const BTP_PROTOCOL_VERSION = "1.1.0", MIN_SUPPORTED_VERSION = "1.1.0", MAX_SUPPORTED_VERSION = "1.1.0", majorMinor = (version) => {
8
+ import { DETAILS_ARTIFACT_TYPES, PERMISSION_ENVELOPE_FIELDS } from "./permissions.js";
9
+ const BTP_PROTOCOL_VERSION = "1.2.0", MIN_SUPPORTED_VERSION = "1.1.0", MAX_SUPPORTED_VERSION = "1.2.0", DEFAULT_MAX_ARTIFACT_AGE_SECONDS = 300, rank = (version) => {
9
10
  const match = /^(\d+)\.(\d+)(?:\.\d+)?$/.exec(version);
10
- return match ? [Number(match[1]), Number(match[2])] : void 0;
11
+ return match ? Number(match[1]) * 1e3 + Number(match[2]) : void 0;
11
12
  }, isSupportedVersion = (version) => {
12
13
  if (typeof version != "string") return !1;
13
- const given = majorMinor(version), min = majorMinor(MIN_SUPPORTED_VERSION), max = majorMinor(MAX_SUPPORTED_VERSION);
14
- if (!given || !min || !max) return !1;
15
- const rank = ([major, minor]) => major * 1e3 + minor;
16
- return rank(given) >= rank(min) && rank(given) <= rank(max);
17
- }, BTPS_DNS_HOST_NAME_SPACE = "_btps.host", BTPS_DNS_IDENTITY_NAME_SPACE = "_btps.identity";
14
+ const given = rank(version), min = rank(MIN_SUPPORTED_VERSION), max = rank(MAX_SUPPORTED_VERSION);
15
+ return given === void 0 || min === void 0 || max === void 0 ? !1 : given >= min && given <= max;
16
+ }, isVersionBelow = (version, than) => {
17
+ const given = rank(version), needed = rank(than);
18
+ return given === void 0 || needed !== void 0 && given < needed;
19
+ }, documentOf = (artifact) => typeof artifact.document == "object" && artifact.document !== null ? artifact.document : void 0, USES_1_2 = [
20
+
21
+ (artifact) => {
22
+ const event = documentOf(artifact);
23
+ return artifact.type === "BTPS_EVENT" && event !== void 0 && (event.eventType === "withdrawn" || event.follows !== void 0);
24
+ },
25
+
26
+ (artifact) => artifact.syncOf !== void 0,
27
+
28
+ (artifact) => documentOf(artifact)?.type === "agreement_event",
29
+
30
+ (artifact) => {
31
+ const document = documentOf(artifact), isNote = (value) => typeof value == "object" && value !== null;
32
+ return document !== void 0 && (isNote(document.description) || isNote(document.message));
33
+ },
34
+
35
+ (artifact) => documentOf(artifact)?.discount !== void 0,
36
+
37
+ (artifact) => documentOf(artifact)?.type === "agreement",
38
+
39
+ (artifact) => {
40
+ const document = documentOf(artifact);
41
+ return (document?.type === "letter" || document?.type === "payslip") && document.template !== void 0;
42
+ },
43
+
44
+ (artifact) => Object.keys(PERMISSION_ENVELOPE_FIELDS).some((field) => artifact[field] !== void 0),
45
+
46
+ (artifact) => {
47
+ const document = documentOf(artifact);
48
+ return artifact.type === "TRUST_REQ" && (document?.own !== void 0 || document?.verification !== void 0) || artifact.type === "TRUST_RES" && document?.details !== void 0;
49
+ },
50
+
51
+ (artifact) => DETAILS_ARTIFACT_TYPES.includes(artifact.type)
52
+ ], artifactVersion = (artifact) => USES_1_2.some((uses) => uses(artifact)) ? "1.2.0" : MIN_SUPPORTED_VERSION, BTPS_DNS_HOST_NAME_SPACE = "_btps.host", BTPS_DNS_IDENTITY_NAME_SPACE = "_btps.identity";
18
53
  export {
19
54
  BTPS_DNS_HOST_NAME_SPACE,
20
55
  BTPS_DNS_IDENTITY_NAME_SPACE,
21
56
  BTP_PROTOCOL_VERSION,
57
+ DEFAULT_MAX_ARTIFACT_AGE_SECONDS,
22
58
  MAX_SUPPORTED_VERSION,
23
59
  MIN_SUPPORTED_VERSION,
24
- isSupportedVersion
60
+ artifactVersion,
61
+ isSupportedVersion,
62
+ isVersionBelow
25
63
  };