@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
|
@@ -4,13 +4,15 @@
|
|
|
4
4
|
* Licensed under the Apache License, Version 2.0
|
|
5
5
|
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
6
|
*/
|
|
7
|
-
import { TokenStore, BTPsTokenDocument } from '../types.js';
|
|
7
|
+
import { TokenStore, BTPsTokenDocument, BTPSealedSuccessor } from '../types.js';
|
|
8
8
|
/**
|
|
9
9
|
* In-memory implementation of RefreshTokenStore for storing refresh tokens
|
|
10
10
|
* Suitable for development and testing. For production, use a persistent store.
|
|
11
11
|
*/
|
|
12
12
|
export declare class InMemoryTokenStore<T extends BTPsTokenDocument = BTPsTokenDocument> implements TokenStore<T> {
|
|
13
13
|
private tokens;
|
|
14
|
+
/** Each consumed token, until it would have expired: how a second use is told from a made-up one. */
|
|
15
|
+
private consumed;
|
|
14
16
|
/**
|
|
15
17
|
* Store a refresh token in memory
|
|
16
18
|
* @param token - The refresh token value
|
|
@@ -48,6 +50,20 @@ export declare class InMemoryTokenStore<T extends BTPsTokenDocument = BTPsTokenD
|
|
|
48
50
|
* @returns The stored token, or undefined when there is none or it has expired
|
|
49
51
|
*/
|
|
50
52
|
consume(agentId: string, token: string): Promise<T | undefined>;
|
|
53
|
+
/**
|
|
54
|
+
* The token as it was when consumed, until it would have expired.
|
|
55
|
+
* @param agentId - The agent ID (or the user identity, for an auth token)
|
|
56
|
+
* @param token - The token
|
|
57
|
+
* @returns The consumed token, or undefined when it was never consumed or has expired
|
|
58
|
+
*/
|
|
59
|
+
isConsumed(agentId: string, token: string): Promise<T | undefined>;
|
|
60
|
+
/**
|
|
61
|
+
* Keep the sealed answer a consumed token was rotated with on its mark.
|
|
62
|
+
* @param agentId - The agent ID
|
|
63
|
+
* @param token - The consumed token
|
|
64
|
+
* @param successor - The sealed answer
|
|
65
|
+
*/
|
|
66
|
+
markSuccessor(agentId: string, token: string, successor: BTPSealedSuccessor): Promise<void>;
|
|
51
67
|
/**
|
|
52
68
|
* Clean up expired tokens from storage
|
|
53
69
|
*/
|
|
@@ -8,9 +8,10 @@
|
|
|
8
8
|
import { computeTrustId } from "../../trust/trustUtils.js";
|
|
9
9
|
class InMemoryTokenStore {
|
|
10
10
|
tokens = new Map();
|
|
11
|
+
consumed = new Map();
|
|
11
12
|
async store(token, agentId, userIdentity, expiryMs, decryptBy, metadata) {
|
|
12
|
-
const now = new Date(), expiresAt = new Date(now.getTime() + expiryMs);
|
|
13
|
-
this.
|
|
13
|
+
const now = new Date(), expiresAt = new Date(now.getTime() + expiryMs), key = this.makeKey(agentId ?? userIdentity, token);
|
|
14
|
+
this.consumed.delete(key), this.tokens.set(key, {
|
|
14
15
|
token,
|
|
15
16
|
agentId: agentId ?? "anonymous",
|
|
16
17
|
userIdentity,
|
|
@@ -40,7 +41,16 @@ class InMemoryTokenStore {
|
|
|
40
41
|
async consume(agentId, token) {
|
|
41
42
|
const key = this.makeKey(agentId, token), storedToken = this.tokens.get(key);
|
|
42
43
|
if (this.tokens.delete(key), !(!storedToken || new Date() > new Date(storedToken.expiresAt)))
|
|
43
|
-
return storedToken;
|
|
44
|
+
return this.consumed.set(key, { ...storedToken, consumedAt: ( new Date()).toISOString() }), storedToken;
|
|
45
|
+
}
|
|
46
|
+
async isConsumed(agentId, token) {
|
|
47
|
+
const consumedToken = this.consumed.get(this.makeKey(agentId, token));
|
|
48
|
+
if (!(!consumedToken || new Date() > new Date(consumedToken.expiresAt)))
|
|
49
|
+
return consumedToken;
|
|
50
|
+
}
|
|
51
|
+
async markSuccessor(agentId, token, successor) {
|
|
52
|
+
const key = this.makeKey(agentId, token), consumedToken = this.consumed.get(key);
|
|
53
|
+
consumedToken && this.consumed.set(key, { ...consumedToken, successor });
|
|
44
54
|
}
|
|
45
55
|
async cleanup() {
|
|
46
56
|
const now = new Date(), expiredTokens = [];
|
|
@@ -50,12 +60,14 @@ class InMemoryTokenStore {
|
|
|
50
60
|
}
|
|
51
61
|
for (const token of expiredTokens)
|
|
52
62
|
this.tokens.delete(token);
|
|
63
|
+
for (const [key, consumedToken] of this.consumed.entries())
|
|
64
|
+
now > new Date(consumedToken.expiresAt) && this.consumed.delete(key);
|
|
53
65
|
}
|
|
54
66
|
get size() {
|
|
55
67
|
return this.tokens.size;
|
|
56
68
|
}
|
|
57
69
|
clear() {
|
|
58
|
-
this.tokens.clear();
|
|
70
|
+
this.tokens.clear(), this.consumed.clear();
|
|
59
71
|
}
|
|
60
72
|
}
|
|
61
73
|
export {
|
|
@@ -31,7 +31,67 @@ export interface ServerAuthConfig {
|
|
|
31
31
|
tokenStore: TokenStore;
|
|
32
32
|
/** Token configuration */
|
|
33
33
|
tokenConfig?: TokenConfig;
|
|
34
|
+
/**
|
|
35
|
+
* Since 1.2, optional and off by default: the oldest a device key may be. A
|
|
36
|
+
* refresh signed by an older key is refused with `BTP_ERROR_KEY_TOO_OLD`,
|
|
37
|
+
* and the same refresh token stays usable, so the device moves to a new key
|
|
38
|
+
* (`rotateKey`) and is let in. A key's age runs from when it came into use:
|
|
39
|
+
* when the key before it was retired, or when the device registered.
|
|
40
|
+
*/
|
|
41
|
+
maxKeyAgeMs?: number;
|
|
42
|
+
/**
|
|
43
|
+
* Since 1.2: how long, in milliseconds, a just-rotated refresh token's old
|
|
44
|
+
* value still works, so a device that lost the answer to its refresh can ask
|
|
45
|
+
* again. Inside the window the same answer comes back, the same new token
|
|
46
|
+
* included; after it, a second use is theft. Default 30 000; 0 turns it off.
|
|
47
|
+
* Needs a token store with `isConsumed` and `markSuccessor`; without them it is 0.
|
|
48
|
+
*/
|
|
49
|
+
refreshGraceMs?: number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Since 1.2: the answer to a refresh, kept on the old token's consumed mark so a
|
|
53
|
+
* retry gets the same answer. Sealed with AES-256-GCM under a key derived
|
|
54
|
+
* (HKDF-SHA256) from the old token's value, bound to the device and the user,
|
|
55
|
+
* so only whoever holds the old token can open it and it cannot be moved to
|
|
56
|
+
* another device. Never the new token in plain text.
|
|
57
|
+
*/
|
|
58
|
+
export interface BTPSealedSuccessor {
|
|
59
|
+
/** When the old token was rotated, as an ISO 8601 timestamp: the grace window runs from here */
|
|
60
|
+
at: string;
|
|
61
|
+
/** Base64 */
|
|
62
|
+
iv: string;
|
|
63
|
+
/** Base64 */
|
|
64
|
+
ciphertext: string;
|
|
65
|
+
/** Base64 */
|
|
66
|
+
tag: string;
|
|
67
|
+
}
|
|
68
|
+
/** Since 1.2: a device moved to a new key. */
|
|
69
|
+
export interface BTPKeyRotatedInfo {
|
|
70
|
+
agentId: string;
|
|
71
|
+
identity: string;
|
|
72
|
+
previousFingerprint: string;
|
|
73
|
+
fingerprint: string;
|
|
74
|
+
/** When the device moved to the new key, as an ISO 8601 timestamp */
|
|
75
|
+
at: string;
|
|
34
76
|
}
|
|
77
|
+
/** Since 1.2: a refresh token was used a second time, which only a copy of it can do. */
|
|
78
|
+
export interface BTPRefreshTokenReusedInfo {
|
|
79
|
+
agentId: string;
|
|
80
|
+
identity: string;
|
|
81
|
+
/** The fingerprint of the key the revoked device held, when its record was found */
|
|
82
|
+
fingerprint?: string;
|
|
83
|
+
/** When the token was used again, as an ISO 8601 timestamp */
|
|
84
|
+
at: string;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Since 1.2, what BtpsAuthentication tells its listeners. With none attached,
|
|
88
|
+
* nothing happens. A listener that throws is warned about and never breaks a refresh.
|
|
89
|
+
*/
|
|
90
|
+
export type BtpsAuthenticationEvents = {
|
|
91
|
+
keyRotated: (info: BTPKeyRotatedInfo) => void;
|
|
92
|
+
/** The device was revoked: whoever holds the newer token, the device or a thief, is refused. */
|
|
93
|
+
refreshTokenReused: (info: BTPRefreshTokenReusedInfo) => void;
|
|
94
|
+
};
|
|
35
95
|
/**
|
|
36
96
|
* Stored refresh token information
|
|
37
97
|
*/
|
|
@@ -50,6 +110,10 @@ export interface BTPsTokenDocument {
|
|
|
50
110
|
decryptBy: string;
|
|
51
111
|
/** Additional metadata */
|
|
52
112
|
metadata?: Record<string, unknown>;
|
|
113
|
+
/** Since 1.2, on a consumed refresh token only: the answer it was rotated with, sealed */
|
|
114
|
+
successor?: BTPSealedSuccessor;
|
|
115
|
+
/** Since 1.2, on a consumed refresh token only: when `consume` took it, ISO 8601 */
|
|
116
|
+
consumedAt?: string;
|
|
53
117
|
}
|
|
54
118
|
export type AuthSession = BTPsTokenDocument & {
|
|
55
119
|
publicKeyFingerprint: string;
|
|
@@ -96,6 +160,24 @@ export interface TokenStore<T extends BTPsTokenDocument = BTPsTokenDocument> {
|
|
|
96
160
|
* exactly one gets it, so one registration code or refresh token is used once.
|
|
97
161
|
*/
|
|
98
162
|
consume(agentId: string, token: string): Promise<T | undefined>;
|
|
163
|
+
/**
|
|
164
|
+
* Since 1.2, optional: the token as it was when `consume` took it, kept until
|
|
165
|
+
* it would have expired; undefined for a token never taken, or past its life.
|
|
166
|
+
* Storing a token again clears the mark. With it, a refresh token used a
|
|
167
|
+
* second time is theft: the device is revoked and `refreshTokenReused` fires.
|
|
168
|
+
* Without it, a second use is refused as an unknown token, as in 1.1. The
|
|
169
|
+
* mark carries `consumedAt`, when `consume` took the token: a second use
|
|
170
|
+
* while the first refresh is still being made is told to try again, not
|
|
171
|
+
* taken for theft.
|
|
172
|
+
*/
|
|
173
|
+
isConsumed?(agentId: string, token: string): Promise<T | undefined>;
|
|
174
|
+
/**
|
|
175
|
+
* Since 1.2, optional: keep `successor` on a consumed token's mark, so
|
|
176
|
+
* `isConsumed` returns it. It is sealed, never the new token in plain text.
|
|
177
|
+
* With it and `isConsumed`, a refresh retried inside `refreshGraceMs` gets its
|
|
178
|
+
* first answer again; without it, the grace window is off.
|
|
179
|
+
*/
|
|
180
|
+
markSuccessor?(agentId: string, token: string, successor: BTPSealedSuccessor): Promise<void>;
|
|
99
181
|
/** Clean up expired tokens */
|
|
100
182
|
cleanup(): Promise<void>;
|
|
101
183
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
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 { BTPTransporterArtifact } from '../server/types.js';
|
|
8
|
+
import type { BTPDecryptionKey } from './types.js';
|
|
9
|
+
/** Since 1.2: an artifact's content key, wrapped to another key, kept beside the artifact. */
|
|
10
|
+
export type BTPContentKeySidecar = {
|
|
11
|
+
/** The content key, RSA-OAEP-wrapped to the key with this fingerprint, base64 */
|
|
12
|
+
encryptedKey: string;
|
|
13
|
+
/** The SHA-256 fingerprint of the key it is wrapped to, base64 */
|
|
14
|
+
recipientFingerprint: string;
|
|
15
|
+
};
|
|
16
|
+
type Encrypted = Pick<BTPTransporterArtifact, 'encryption' | 'document'>;
|
|
17
|
+
/**
|
|
18
|
+
* Since 1.2: the artifact's content key, unwrapped with the key it was
|
|
19
|
+
* wrapped to (`oldKey`, a PEM private key or a Decrypter with `unwrapKey`),
|
|
20
|
+
* checked to open the document, and wrapped to `newPublicKey` (SPKI PEM). The
|
|
21
|
+
* artifact itself is not changed. Keep the side-car beside it, and confirm it
|
|
22
|
+
* with `contentKeyOpens` before deleting the old private key.
|
|
23
|
+
*/
|
|
24
|
+
export declare const wrapContentKeyFor: (artifact: Encrypted, oldKey: BTPDecryptionKey, newPublicKey: string) => Promise<BTPContentKeySidecar>;
|
|
25
|
+
/**
|
|
26
|
+
* Since 1.2: whether a side-car opens its artifact with `newKey`: the content
|
|
27
|
+
* key unwraps, and the document's AES-GCM tag checks. Given a PEM private
|
|
28
|
+
* key, the side-car must also name it (`recipientFingerprint`), so one stored
|
|
29
|
+
* against another key fails even when the unwrap happens to work. Only when
|
|
30
|
+
* every stored artifact wrapped to an old key has a side-car that opens may
|
|
31
|
+
* that old private key be deleted.
|
|
32
|
+
*/
|
|
33
|
+
export declare const contentKeyOpens: (artifact: Encrypted, sidecar: BTPContentKeySidecar, newKey: BTPDecryptionKey) => Promise<boolean>;
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,64 @@
|
|
|
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 {
|
|
11
|
+
BTP_ERROR_DECRYPTION_UNINTENDED,
|
|
12
|
+
BTP_ERROR_UNSUPPORTED_ENCRYPT
|
|
13
|
+
} from "../error/constant.js";
|
|
14
|
+
import { decryptRSA, encryptRSA, getFingerprintFromPem } from "./index.js";
|
|
15
|
+
const encryptionOf = (artifact) => {
|
|
16
|
+
const { encryption, document } = artifact;
|
|
17
|
+
if (!encryption?.encryptedKey || typeof document != "string")
|
|
18
|
+
throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT, {
|
|
19
|
+
cause: "Only an encrypted artifact has a content key"
|
|
20
|
+
});
|
|
21
|
+
if (encryption.algorithm !== "aes-256-gcm")
|
|
22
|
+
throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT);
|
|
23
|
+
return { ...encryption, document };
|
|
24
|
+
}, unwrap = async (encryptedKey, key) => {
|
|
25
|
+
const wrapped = Buffer.from(encryptedKey, "base64");
|
|
26
|
+
if (typeof key == "string") return decryptRSA(key, wrapped);
|
|
27
|
+
if (key.unwrapKey) return Buffer.from(await key.unwrapKey(wrapped));
|
|
28
|
+
throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT, {
|
|
29
|
+
cause: "The Decrypter has no unwrapKey, so it cannot give the content key"
|
|
30
|
+
});
|
|
31
|
+
}, opens = (contentKey, artifact) => {
|
|
32
|
+
const { iv, authTag, document } = encryptionOf(artifact);
|
|
33
|
+
try {
|
|
34
|
+
const decipher = crypto.createDecipheriv("aes-256-gcm", contentKey, Buffer.from(iv, "base64"));
|
|
35
|
+
return decipher.setAuthTag(Buffer.from(authTag, "base64")), decipher.update(Buffer.from(document, "base64")), decipher.final(), !0;
|
|
36
|
+
} catch {
|
|
37
|
+
return !1;
|
|
38
|
+
}
|
|
39
|
+
}, wrapContentKeyFor = async (artifact, oldKey, newPublicKey) => {
|
|
40
|
+
const contentKey = await unwrap(encryptionOf(artifact).encryptedKey, oldKey);
|
|
41
|
+
if (!opens(contentKey, artifact))
|
|
42
|
+
throw new BTPErrorException(BTP_ERROR_DECRYPTION_UNINTENDED, {
|
|
43
|
+
cause: "The old key's content key does not open the document"
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
encryptedKey: encryptRSA(newPublicKey, contentKey).toString("base64"),
|
|
47
|
+
recipientFingerprint: getFingerprintFromPem(newPublicKey)
|
|
48
|
+
};
|
|
49
|
+
}, contentKeyOpens = async (artifact, sidecar, newKey) => {
|
|
50
|
+
try {
|
|
51
|
+
if (typeof newKey == "string") {
|
|
52
|
+
const publicKey = crypto.createPublicKey(newKey).export({ type: "spki", format: "pem" });
|
|
53
|
+
if (getFingerprintFromPem(publicKey.toString()) !== sidecar.recipientFingerprint)
|
|
54
|
+
return !1;
|
|
55
|
+
}
|
|
56
|
+
return opens(await unwrap(sidecar.encryptedKey, newKey), artifact);
|
|
57
|
+
} catch {
|
|
58
|
+
return !1;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
export {
|
|
62
|
+
contentKeyOpens,
|
|
63
|
+
wrapContentKeyFor
|
|
64
|
+
};
|
|
@@ -6,4 +6,10 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { BTPCryptoResponse, BTPDecryptionKey, VerifyEncryptedPayload } from './types.js';
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Verifies an artifact's signature, then decrypts its document and checks it.
|
|
11
|
+
* Since 1.2, `contentKey` is the document's content key wrapped to the
|
|
12
|
+
* receiver's own key instead of the envelope's (a device's `agentKey.key`): the
|
|
13
|
+
* signature is checked over the artifact as sent, and only the decryption uses it.
|
|
14
|
+
*/
|
|
15
|
+
export declare const decryptVerify: <T = unknown>(senderPubPem: string, encryptedPayload: VerifyEncryptedPayload<T>, receiverKey?: BTPDecryptionKey, contentKey?: string) => Promise<BTPCryptoResponse<T>>;
|
|
@@ -7,29 +7,47 @@
|
|
|
7
7
|
|
|
8
8
|
import { decryptBtpPayload, decryptBtpPayloadWithDecrypter, verifySignature } from "./index.js";
|
|
9
9
|
import { BTPErrorException } from "../error/index.js";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
BTP_ERROR_DOCUMENT_TYPE_MISMATCH,
|
|
12
|
+
BTP_ERROR_SIG_VERIFICATION,
|
|
13
|
+
BTP_ERROR_VALIDATION
|
|
14
|
+
} from "../error/constant.js";
|
|
11
15
|
import { decryptedDocumentProblem } from "../server/schemas/helpers.js";
|
|
16
|
+
import { verifierRefusal } from "../trust/verification.js";
|
|
12
17
|
import isEmpty from "lodash/isEmpty.js";
|
|
13
18
|
const genDecryptError = (error) => ({
|
|
14
19
|
payload: void 0,
|
|
15
20
|
error
|
|
16
|
-
}), decryptVerify = async (senderPubPem, encryptedPayload, receiverKey) => {
|
|
21
|
+
}), decryptVerify = async (senderPubPem, encryptedPayload, receiverKey, contentKey) => {
|
|
17
22
|
const { signature, delegation, ...restEncryptedPayload } = encryptedPayload, { isValid, error: sigError } = verifySignature(
|
|
18
23
|
restEncryptedPayload,
|
|
19
24
|
signature,
|
|
20
25
|
senderPubPem
|
|
21
26
|
);
|
|
22
|
-
if (!isValid
|
|
23
|
-
return genDecryptError(sigError);
|
|
27
|
+
if (!isValid)
|
|
28
|
+
return genDecryptError(sigError ?? new BTPErrorException(BTP_ERROR_SIG_VERIFICATION));
|
|
24
29
|
const { encryption, document } = restEncryptedPayload, hasReceiverKey = typeof receiverKey == "string" ? !isEmpty(receiverKey) : receiverKey !== void 0, needsDecryption = !isEmpty(encryption) && hasReceiverKey && !isEmpty(document) && typeof document == "string";
|
|
25
30
|
let decrypted = { data: document };
|
|
26
|
-
needsDecryption && receiverKey !== void 0
|
|
31
|
+
if (needsDecryption && receiverKey !== void 0) {
|
|
32
|
+
const wrapped = contentKey !== void 0 && encryption ? { ...encryption, encryptedKey: contentKey } : encryption;
|
|
33
|
+
decrypted = typeof receiverKey == "string" ? decryptBtpPayload(document, wrapped, receiverKey) : await decryptBtpPayloadWithDecrypter(document, wrapped, receiverKey);
|
|
34
|
+
}
|
|
27
35
|
const { data: decryptedData, error: decryptionErrors } = decrypted;
|
|
28
36
|
if (decryptionErrors) return genDecryptError(decryptionErrors);
|
|
29
37
|
if (needsDecryption) {
|
|
30
38
|
const problem = decryptedDocumentProblem(decryptedData, restEncryptedPayload);
|
|
31
39
|
if (problem)
|
|
32
40
|
return genDecryptError(new BTPErrorException(BTP_ERROR_VALIDATION, { cause: problem }));
|
|
41
|
+
const { documentType } = restEncryptedPayload, type = decryptedData?.type;
|
|
42
|
+
if (documentType !== void 0 && type !== documentType)
|
|
43
|
+
return genDecryptError(
|
|
44
|
+
new BTPErrorException(BTP_ERROR_DOCUMENT_TYPE_MISMATCH, {
|
|
45
|
+
cause: `the document is a ${String(type)}, not the ${documentType} its envelope names`
|
|
46
|
+
})
|
|
47
|
+
);
|
|
48
|
+
const { verification } = decryptedData ?? {}, verifier = restEncryptedPayload.type === "TRUST_REQ" && verification ? await verifierRefusal(verification.verifiedBy) : void 0;
|
|
49
|
+
if (verifier)
|
|
50
|
+
return genDecryptError(new BTPErrorException(verifier.error, { cause: verifier.problem }));
|
|
33
51
|
}
|
|
34
52
|
const decryptedPayload = {
|
|
35
53
|
...restEncryptedPayload,
|
|
@@ -22,4 +22,10 @@ export interface Decrypter {
|
|
|
22
22
|
/** Decrypts `request` and returns the plaintext bytes, or rejects if the
|
|
23
23
|
* key-wrap fails to unwrap or the AEAD tag check fails. */
|
|
24
24
|
decrypt(request: DecryptRequest): Promise<Uint8Array>;
|
|
25
|
+
/**
|
|
26
|
+
* Since 1.2, optional: unwraps an RSA-OAEP-wrapped AES-256 content key and
|
|
27
|
+
* returns it, so a provider can wrap it again to one of its user's devices
|
|
28
|
+
* (`wrapForAgent`). A KMS decrypter makes the same call inside `decrypt`.
|
|
29
|
+
*/
|
|
30
|
+
unwrapKey?(encryptedKey: Uint8Array): Promise<Uint8Array>;
|
|
25
31
|
}
|
|
@@ -6,18 +6,27 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { BTPCryptoOptions, BTPEncryption, BTPSignature, PemKeys } from './types.js';
|
|
8
8
|
import { BTPErrorException } from '../error/index.js';
|
|
9
|
+
import type { BTPArtifactType } from '../server/types.js';
|
|
9
10
|
import type { Signer } from './signer-interface.js';
|
|
10
11
|
import type { Decrypter } from './decrypter-interface.js';
|
|
11
12
|
export * from './decryptVerify.js';
|
|
12
13
|
export * from './jcs.js';
|
|
13
14
|
export * from './signEncrypt.js';
|
|
15
|
+
export * from './keyResolver.js';
|
|
16
|
+
export * from './contentKey.js';
|
|
14
17
|
export * from './keygen.js';
|
|
15
18
|
export * from './types.js';
|
|
16
19
|
export * from './signer-interface.js';
|
|
17
20
|
export * from './decrypter-interface.js';
|
|
18
21
|
export * from './pem-signer.js';
|
|
19
22
|
export * from './pem-decrypter.js';
|
|
20
|
-
|
|
23
|
+
/**
|
|
24
|
+
* Encrypts a document to the receiver's key. Given `documentType`, the
|
|
25
|
+
* document is checked against that type first, and an invalid one throws
|
|
26
|
+
* `BTP_ERROR_VALIDATION`. Without it, nothing is checked: a direct caller
|
|
27
|
+
* validates the document itself. `signEncrypt` and the clients always do.
|
|
28
|
+
*/
|
|
29
|
+
export declare const encryptBtpPayload: (payload: unknown | undefined, receiverPubPem: string, options?: BTPCryptoOptions["encryption"], documentType?: BTPArtifactType) => {
|
|
21
30
|
data: string;
|
|
22
31
|
encryption: {
|
|
23
32
|
algorithm: "aes-256-gcm";
|
|
@@ -27,7 +36,13 @@ export declare const encryptBtpPayload: (payload: unknown | undefined, receiverP
|
|
|
27
36
|
type: import("./types.js").EncryptionMode;
|
|
28
37
|
};
|
|
29
38
|
};
|
|
30
|
-
|
|
39
|
+
/**
|
|
40
|
+
* Decrypts a document with the receiver's key. Given `documentType`, the
|
|
41
|
+
* decrypted document is checked against that type, and an invalid one is
|
|
42
|
+
* returned as a `BTP_ERROR_VALIDATION` error. Without it, nothing is checked:
|
|
43
|
+
* a direct caller validates the document itself. `decryptVerify` always does.
|
|
44
|
+
*/
|
|
45
|
+
export declare const decryptBtpPayload: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, receiverPrivPem: string, documentType?: BTPArtifactType) => {
|
|
31
46
|
data?: T;
|
|
32
47
|
error?: BTPErrorException;
|
|
33
48
|
};
|
|
@@ -35,7 +50,7 @@ export declare const decryptBtpPayload: <T = unknown>(payload: unknown | undefin
|
|
|
35
50
|
* Decrypts like `decryptBtpPayload`, through a Decrypter that holds the
|
|
36
51
|
* receiver's private key elsewhere (a KMS, a device) instead of a PEM key.
|
|
37
52
|
*/
|
|
38
|
-
export declare const decryptBtpPayloadWithDecrypter: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, decrypter: Decrypter) => Promise<{
|
|
53
|
+
export declare const decryptBtpPayloadWithDecrypter: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, decrypter: Decrypter, documentType?: BTPArtifactType) => Promise<{
|
|
39
54
|
data?: T;
|
|
40
55
|
error?: BTPErrorException;
|
|
41
56
|
}>;
|
|
@@ -50,6 +65,16 @@ export declare const encryptRSA: (publicKeyPem: string, data: Buffer) => Buffer;
|
|
|
50
65
|
*/
|
|
51
66
|
export declare const decryptRSA: (privateKeyPem: string, encrypted: Buffer) => Buffer;
|
|
52
67
|
export declare const getFingerprintFromPem: (pem: string, hashAlgorithm?: string) => string;
|
|
68
|
+
/**
|
|
69
|
+
* Since 1.2: what a sync names of the send it copies (`syncOf`): the sent
|
|
70
|
+
* artifact's id, and the lowercase hex SHA-256 of its RFC 8785 form, signature included.
|
|
71
|
+
*/
|
|
72
|
+
export declare const syncOfArtifact: (artifact: {
|
|
73
|
+
id: string;
|
|
74
|
+
}) => {
|
|
75
|
+
id: string;
|
|
76
|
+
sha256: string;
|
|
77
|
+
};
|
|
53
78
|
export declare const signBtpPayload: (payload: unknown | undefined, senderPemFiles: PemKeys) => BTPSignature;
|
|
54
79
|
/**
|
|
55
80
|
* Signs like `signBtpPayload`, through a Signer that holds the sender's
|
|
@@ -5,31 +5,44 @@
|
|
|
5
5
|
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import crypto, { constants
|
|
9
|
-
import { performance } from "perf_hooks";
|
|
8
|
+
import crypto, { constants } from "crypto";
|
|
10
9
|
import {
|
|
11
10
|
BTP_ERROR_UNSUPPORTED_ENCRYPT,
|
|
12
11
|
BTP_ERROR_DECRYPTION_UNINTENDED,
|
|
13
12
|
BTP_ERROR_SIG_MISMATCH,
|
|
14
13
|
BTP_ERROR_SIG_VERIFICATION,
|
|
15
|
-
BTP_ERROR_UNKNOWN
|
|
14
|
+
BTP_ERROR_UNKNOWN,
|
|
15
|
+
BTP_ERROR_VALIDATION
|
|
16
16
|
} from "../error/constant.js";
|
|
17
17
|
import { BTPErrorException } from "../error/index.js";
|
|
18
|
+
import { processBtpDocSchema } from "../server/schemas/helpers.js";
|
|
18
19
|
import { assertStrictJson, canonicalize, canonicalizeValue } from "./jcs.js";
|
|
19
20
|
import { assertFullLengthAuthTag } from "./pem-decrypter.js";
|
|
20
21
|
export * from "./decryptVerify.js";
|
|
21
22
|
export * from "./jcs.js";
|
|
22
23
|
export * from "./signEncrypt.js";
|
|
24
|
+
export * from "./keyResolver.js";
|
|
25
|
+
export * from "./contentKey.js";
|
|
23
26
|
export * from "./keygen.js";
|
|
24
27
|
export * from "./types.js";
|
|
25
28
|
export * from "./signer-interface.js";
|
|
26
29
|
export * from "./decrypter-interface.js";
|
|
27
30
|
export * from "./pem-signer.js";
|
|
28
31
|
export * from "./pem-decrypter.js";
|
|
29
|
-
const
|
|
32
|
+
const documentTypeError = (document, documentType) => {
|
|
33
|
+
if (!documentType) return;
|
|
34
|
+
const parsed = processBtpDocSchema(documentType)?.safeParse(document);
|
|
35
|
+
if (!(!parsed || parsed.success))
|
|
36
|
+
return new BTPErrorException(BTP_ERROR_VALIDATION, {
|
|
37
|
+
cause: `Document is not a valid ${documentType} document`,
|
|
38
|
+
meta: { issues: parsed.error.issues }
|
|
39
|
+
});
|
|
40
|
+
}, encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
30
41
|
algorithm: "aes-256-gcm",
|
|
31
42
|
mode: "standardEncrypt"
|
|
32
|
-
}) => {
|
|
43
|
+
}, documentType) => {
|
|
44
|
+
const invalid = documentTypeError(payload, documentType);
|
|
45
|
+
if (invalid) throw invalid;
|
|
33
46
|
const aesKey = crypto.randomBytes(32), iv = crypto.randomBytes(12), algorithm = options.algorithm, stringifiedPayload = typeof payload != "string" ? JSON.stringify(payload) : payload, cipher = crypto.createCipheriv(algorithm, aesKey, iv);
|
|
34
47
|
let encryptedPayload = cipher.update(stringifiedPayload, "utf8", "base64");
|
|
35
48
|
encryptedPayload += cipher.final("base64");
|
|
@@ -44,7 +57,7 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
|
44
57
|
type: options.mode
|
|
45
58
|
}
|
|
46
59
|
};
|
|
47
|
-
}, decryptBtpPayload = (payload = "", encryption, receiverPrivPem) => {
|
|
60
|
+
}, decryptBtpPayload = (payload = "", encryption, receiverPrivPem, documentType) => {
|
|
48
61
|
if (encryption.algorithm !== "aes-256-gcm")
|
|
49
62
|
return {
|
|
50
63
|
data: void 0,
|
|
@@ -65,14 +78,13 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
|
65
78
|
decipher.setAuthTag(authTag);
|
|
66
79
|
const stringifiedPayload = typeof payload != "string" ? JSON.stringify(payload) : payload;
|
|
67
80
|
let decryptedPayload = decipher.update(stringifiedPayload, "base64", "utf8");
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
};
|
|
81
|
+
decryptedPayload += decipher.final("utf8"), assertStrictJson(decryptedPayload);
|
|
82
|
+
const data = JSON.parse(decryptedPayload), invalid = documentTypeError(data, documentType);
|
|
83
|
+
return invalid ? { data: void 0, error: invalid } : { data, error: void 0 };
|
|
72
84
|
} catch (err) {
|
|
73
85
|
return { data: void 0, error: decryptionError(err) };
|
|
74
86
|
}
|
|
75
|
-
}, decryptBtpPayloadWithDecrypter = async (payload = "", encryption, decrypter) => {
|
|
87
|
+
}, decryptBtpPayloadWithDecrypter = async (payload = "", encryption, decrypter, documentType) => {
|
|
76
88
|
if (encryption.algorithm !== "aes-256-gcm")
|
|
77
89
|
return {
|
|
78
90
|
data: void 0,
|
|
@@ -85,10 +97,9 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
|
85
97
|
ciphertext: Buffer.from(stringifiedPayload, "base64"),
|
|
86
98
|
authTag: Buffer.from(encryption.authTag, "base64")
|
|
87
99
|
}), decryptedPayload = Buffer.from(plaintext).toString("utf8");
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
};
|
|
100
|
+
assertStrictJson(decryptedPayload);
|
|
101
|
+
const data = JSON.parse(decryptedPayload), invalid = documentTypeError(data, documentType);
|
|
102
|
+
return invalid ? { data: void 0, error: invalid } : { data, error: void 0 };
|
|
92
103
|
} catch (err) {
|
|
93
104
|
return { data: void 0, error: decryptionError(err) };
|
|
94
105
|
}
|
|
@@ -128,7 +139,10 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
|
128
139
|
type: "spki"
|
|
129
140
|
}).export({ format: "der", type: "spki" });
|
|
130
141
|
return crypto.createHash(hashAlgorithm).update(der).digest("base64");
|
|
131
|
-
},
|
|
142
|
+
}, syncOfArtifact = (artifact) => ({
|
|
143
|
+
id: artifact.id,
|
|
144
|
+
sha256: crypto.createHash("sha256").update(canonicalizeValue(artifact), "utf8").digest("hex")
|
|
145
|
+
}), signedBytes = (payload) => Buffer.from(
|
|
132
146
|
typeof payload == "string" ? canonicalize(payload) : canonicalizeValue(payload),
|
|
133
147
|
"utf8"
|
|
134
148
|
), signBtpPayload = (payload = "", senderPemFiles) => {
|
|
@@ -189,10 +203,9 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
|
189
203
|
function generateUserToken(userIdentity, length = 12, charactersFrom = DEFAULT_ALPHABET) {
|
|
190
204
|
if (length < 8 || length > 24)
|
|
191
205
|
throw new BTPErrorException({ message: "Token length must be between 8 and 24 characters." });
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
return Array.from(sliced).map((byte) => charactersFrom[byte % charactersFrom.length]).join("").toUpperCase();
|
|
206
|
+
let token = "";
|
|
207
|
+
for (let i = 0; i < length; i++) token += charactersFrom[crypto.randomInt(charactersFrom.length)];
|
|
208
|
+
return token.toUpperCase();
|
|
196
209
|
}
|
|
197
210
|
export {
|
|
198
211
|
DEFAULT_ALPHABET,
|
|
@@ -206,5 +219,6 @@ export {
|
|
|
206
219
|
getFingerprintFromPem,
|
|
207
220
|
signBtpPayload,
|
|
208
221
|
signBtpPayloadWithSigner,
|
|
222
|
+
syncOfArtifact,
|
|
209
223
|
verifySignature
|
|
210
224
|
};
|
|
@@ -0,0 +1,48 @@
|
|
|
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 type { BTPKeyChainLookup } from '../trust/types.js';
|
|
9
|
+
/** What a key is looked up for: checking a signature, or encrypting to a receiver. */
|
|
10
|
+
export type BTPKeyUse = 'verify' | 'encrypt';
|
|
11
|
+
/** Since 1.2: the longest a key chain is trusted from a cache, in seconds, unless a server sets `keyChainMaxCacheSeconds`. */
|
|
12
|
+
export declare const DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS = 300;
|
|
13
|
+
/**
|
|
14
|
+
* Since 1.2: finds the public keys BTPS checks and encrypts with, so a
|
|
15
|
+
* provider can put its own cache in front of every lookup. Given as the
|
|
16
|
+
* `keyResolver` option of BtpsServer, BtpsClient (and so BtpsAgent and
|
|
17
|
+
* BtpsTransporter), BtpsDelegator, and signEncrypt's `lookup`. It only finds
|
|
18
|
+
* keys: every signature, time window and delegation rule stays inside BTPS.
|
|
19
|
+
*/
|
|
20
|
+
export interface BtpsKeyResolver {
|
|
21
|
+
/** The PEM public key of `identity` at `selector`, or undefined when there is none. */
|
|
22
|
+
resolvePublicKey(identity: string, selector: string, use: BTPKeyUse): Promise<string | undefined>;
|
|
23
|
+
/**
|
|
24
|
+
* Since 1.2, optional: `identity`'s key chain, from its host (see
|
|
25
|
+
* `BtpsClient.lookupKeyChain`). A resolver that caches it keeps an answer no
|
|
26
|
+
* longer than the server's `keyChainMaxCacheSeconds`: that is the longest a
|
|
27
|
+
* revoked key can still be taken.
|
|
28
|
+
*/
|
|
29
|
+
resolveKeyChain?(identity: string): Promise<BTPKeyChainLookup>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Since 1.2: the lookup BTPS does without a resolver, to wrap with a cache. A
|
|
33
|
+
* signature key is looked up in DNS only. A receiver's key is looked up in DNS
|
|
34
|
+
* first, then from the receiver's host, in an answer its domain's operator
|
|
35
|
+
* signed; that needs `from`, the sender's own identity, and the TLS options
|
|
36
|
+
* for the connection. Without `from`, an encryption key is looked up in DNS only.
|
|
37
|
+
*
|
|
38
|
+
* Since 1.2, it also gives an identity's key chain from its host, asking as
|
|
39
|
+
* `from`, and keeps each answer (a chain, or none to be had) for
|
|
40
|
+
* `keyChainMaxCacheSeconds`. An answer that fails its checks is not kept.
|
|
41
|
+
* Without `from`, it has no `resolveKeyChain`, so a server given it still
|
|
42
|
+
* asks for chains itself, as its own identity.
|
|
43
|
+
*/
|
|
44
|
+
export declare const createDefaultKeyResolver: (options?: {
|
|
45
|
+
from?: string;
|
|
46
|
+
btpMtsOptions?: Omit<ConnectionOptions, "port" | "host">;
|
|
47
|
+
keyChainMaxCacheSeconds?: number;
|
|
48
|
+
}) => BtpsKeyResolver;
|
|
@@ -0,0 +1,46 @@
|
|
|
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 { resolvePublicKey } from "../utils/index.js";
|
|
9
|
+
const DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS = 300, createDefaultKeyResolver = (options) => {
|
|
10
|
+
const clientFor = async (identity) => {
|
|
11
|
+
const { BtpsClient } = await import("../../client/btpsClient.js");
|
|
12
|
+
return new BtpsClient({ to: identity, btpMtsOptions: options?.btpMtsOptions, maxRetries: 0 });
|
|
13
|
+
}, maxAgeMs = (options?.keyChainMaxCacheSeconds ?? DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS) * 1e3, chains = new Map(), from = options?.from;
|
|
14
|
+
return {
|
|
15
|
+
async resolvePublicKey(identity, selector, use) {
|
|
16
|
+
const inDns = await resolvePublicKey(identity, selector);
|
|
17
|
+
if (inDns || use === "verify" || !options?.from) return inDns;
|
|
18
|
+
const client = await clientFor(identity);
|
|
19
|
+
try {
|
|
20
|
+
return (await client.resolveIdentity(identity, options.from)).response?.publicKey;
|
|
21
|
+
} finally {
|
|
22
|
+
client.destroy();
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
|
|
26
|
+
...from && {
|
|
27
|
+
async resolveKeyChain(identity) {
|
|
28
|
+
const key = identity.toLowerCase(), cached = chains.get(key);
|
|
29
|
+
if (cached && cached.until > Date.now()) return cached.lookup;
|
|
30
|
+
const client = await clientFor(identity);
|
|
31
|
+
try {
|
|
32
|
+
const lookup = await client.lookupKeyChain(identity, from), now = Date.now();
|
|
33
|
+
if (lookup.status === "invalid" ? chains.delete(key) : chains.set(key, { lookup, until: now + maxAgeMs }), chains.size > 1e4)
|
|
34
|
+
for (const [name, kept] of chains) kept.until <= now && chains.delete(name);
|
|
35
|
+
return lookup;
|
|
36
|
+
} finally {
|
|
37
|
+
client.destroy();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
export {
|
|
44
|
+
DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS,
|
|
45
|
+
createDefaultKeyResolver
|
|
46
|
+
};
|