@btps/sdk 0.0.0-stage → 1.1.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 +171 -0
- package/LICENSE +190 -0
- package/NOTICE +25 -0
- package/README.md +261 -2
- package/dist/client/btpsAgent.d.ts +20 -0
- package/dist/client/btpsAgent.js +172 -0
- package/dist/client/btpsClient.d.ts +202 -0
- package/dist/client/btpsClient.js +602 -0
- package/dist/client/btpsTransporter.d.ts +52 -0
- package/dist/client/btpsTransporter.js +249 -0
- package/dist/client/constants/index.d.ts +11 -0
- package/dist/client/constants/index.js +20 -0
- package/dist/client/index.d.ts +12 -0
- package/dist/client/index.js +27 -0
- package/dist/client/libs/schema.js +56 -0
- package/dist/client/libs/timeouts.d.ts +22 -0
- package/dist/client/libs/timeouts.js +19 -0
- package/dist/client/types/index.d.ts +155 -0
- package/dist/client/types/index.js +7 -0
- package/dist/core/authentication/BtpsAuthentication.d.ts +128 -0
- package/dist/core/authentication/BtpsAuthentication.js +293 -0
- package/dist/core/authentication/index.d.ts +11 -0
- package/dist/core/authentication/index.js +12 -0
- package/dist/core/authentication/keyProof.d.ts +18 -0
- package/dist/core/authentication/keyProof.js +16 -0
- package/dist/core/authentication/storage/InMemoryAuthSessionStore.d.ts +55 -0
- package/dist/core/authentication/storage/InMemoryAuthSessionStore.js +62 -0
- package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +63 -0
- package/dist/core/authentication/storage/InMemoryTokenStore.js +63 -0
- package/dist/core/authentication/types.d.ts +135 -0
- package/dist/core/authentication/types.js +7 -0
- package/dist/core/crypto/decryptVerify.d.ts +9 -0
- package/dist/core/crypto/decryptVerify.js +45 -0
- package/dist/core/crypto/decrypter-interface.d.ts +25 -0
- package/dist/core/crypto/decrypter-interface.js +7 -0
- package/dist/core/crypto/index.d.ts +77 -0
- package/dist/core/crypto/index.js +210 -0
- package/dist/core/crypto/jcs.d.ts +28 -0
- package/dist/core/crypto/jcs.js +60 -0
- package/dist/core/crypto/keygen.d.ts +9 -0
- package/dist/core/crypto/keygen.js +35 -0
- package/dist/core/crypto/pem-decrypter.d.ts +26 -0
- package/dist/core/crypto/pem-decrypter.js +52 -0
- package/dist/core/crypto/pem-signer.d.ts +21 -0
- package/dist/core/crypto/pem-signer.js +34 -0
- package/dist/core/crypto/signEncrypt.d.ts +34 -0
- package/dist/core/crypto/signEncrypt.js +75 -0
- package/dist/core/crypto/signer-interface.d.ts +22 -0
- package/dist/core/crypto/signer-interface.js +7 -0
- package/dist/core/crypto/types.d.ts +79 -0
- package/dist/core/crypto/types.js +7 -0
- package/dist/core/delegation/BtpsDelegator.d.ts +102 -0
- package/dist/core/delegation/BtpsDelegator.js +118 -0
- package/dist/core/delegation/index.d.ts +7 -0
- package/dist/core/delegation/index.js +8 -0
- package/dist/core/error/constant.d.ts +66 -0
- package/dist/core/error/constant.js +194 -0
- package/dist/core/error/index.d.ts +35 -0
- package/dist/core/error/index.js +52 -0
- package/dist/core/error/types.d.ts +16 -0
- package/dist/core/error/types.js +7 -0
- package/dist/core/server/constants/btps-protocol.d.ts +17 -0
- package/dist/core/server/constants/btps-protocol.js +25 -0
- package/dist/core/server/constants/control.d.ts +7 -0
- package/dist/core/server/constants/control.js +11 -0
- package/dist/core/server/constants/currency.d.ts +7 -0
- package/dist/core/server/constants/currency.js +332 -0
- package/dist/core/server/constants/index.d.ts +26 -0
- package/dist/core/server/constants/index.js +61 -0
- package/dist/core/server/constants/limits.d.ts +50 -0
- package/dist/core/server/constants/limits.js +50 -0
- package/dist/core/server/helpers/BtpsMessageQueue.d.ts +13 -0
- package/dist/core/server/helpers/BtpsMessageQueue.js +12 -0
- package/dist/core/server/helpers/InMemoryQueue.d.ts +16 -0
- package/dist/core/server/helpers/InMemoryQueue.js +35 -0
- package/dist/core/server/helpers/index.d.ts +8 -0
- package/dist/core/server/helpers/index.js +9 -0
- package/dist/core/server/schemas/artifacts/agentSchema.js +51 -0
- package/dist/core/server/schemas/artifacts/artifacts.js +21 -0
- package/dist/core/server/schemas/artifacts/controlSchema.js +18 -0
- package/dist/core/server/schemas/artifacts/identityLookupSchema.js +21 -0
- package/dist/core/server/schemas/artifacts/transporterSchema.js +60 -0
- package/dist/core/server/schemas/btpsDocsSchema.d.ts +4519 -0
- package/dist/core/server/schemas/btpsDocsSchema.js +272 -0
- package/dist/core/server/schemas/helpers.js +87 -0
- package/dist/core/server/schemas/responseSchema.js +86 -0
- package/dist/core/server/schemas/schema.js +70 -0
- package/dist/core/server/schemas/shared.js +18 -0
- package/dist/core/server/types.d.ts +172 -0
- package/dist/core/server/types.js +7 -0
- package/dist/core/storage/AbstractIdentityStore.d.ts +17 -0
- package/dist/core/storage/AbstractIdentityStore.js +13 -0
- package/dist/core/storage/AbstractStorageStore.d.ts +16 -0
- package/dist/core/storage/AbstractStorageStore.js +17 -0
- package/dist/core/storage/JsonIdentityStore.d.ts +29 -0
- package/dist/core/storage/JsonIdentityStore.js +39 -0
- package/dist/core/storage/JsonStorageStore.d.ts +59 -0
- package/dist/core/storage/JsonStorageStore.js +110 -0
- package/dist/core/storage/index.d.ts +11 -0
- package/dist/core/storage/index.js +18 -0
- package/dist/core/storage/types.d.ts +28 -0
- package/dist/core/storage/types.js +7 -0
- package/dist/core/trust/index.d.ts +10 -0
- package/dist/core/trust/index.js +15 -0
- package/dist/core/trust/storage/AbstractTrustStore.d.ts +23 -0
- package/dist/core/trust/storage/AbstractTrustStore.js +13 -0
- package/dist/core/trust/storage/JsonTrustStore.d.ts +33 -0
- package/dist/core/trust/storage/JsonTrustStore.js +42 -0
- package/dist/core/trust/trustUtils.d.ts +78 -0
- package/dist/core/trust/trustUtils.js +41 -0
- package/dist/core/trust/types.d.ts +53 -0
- package/dist/core/trust/types.js +7 -0
- package/dist/core/utils/identity.d.ts +20 -0
- package/dist/core/utils/identity.js +22 -0
- package/dist/core/utils/index.d.ts +70 -0
- package/dist/core/utils/index.js +124 -0
- package/dist/core/utils/types.d.ts +10 -0
- package/dist/core/utils/types.js +7 -0
- package/dist/core/utils/validation.js +13 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -0
- package/dist/server/btpsServer.d.ts +292 -0
- package/dist/server/btpsServer.js +827 -0
- package/dist/server/index.d.ts +11 -0
- package/dist/server/index.js +15 -0
- package/dist/server/libs/abstractRateLimiter.d.ts +10 -0
- package/dist/server/libs/abstractRateLimiter.js +15 -0
- package/dist/server/libs/artifactSizeGuard.d.ts +27 -0
- package/dist/server/libs/artifactSizeGuard.js +44 -0
- package/dist/server/libs/artifactTimeWindow.d.ts +24 -0
- package/dist/server/libs/artifactTimeWindow.js +30 -0
- package/dist/server/libs/btpsFactory.d.ts +29 -0
- package/dist/server/libs/btpsFactory.js +49 -0
- package/dist/server/libs/btpsLightweightFactory.d.ts +35 -0
- package/dist/server/libs/btpsLightweightFactory.js +37 -0
- package/dist/server/libs/btpsRegistry.d.ts +14 -0
- package/dist/server/libs/btpsRegistry.js +16 -0
- package/dist/server/libs/btpsSimpleMetricsTracker.d.ts +13 -0
- package/dist/server/libs/btpsSimpleMetricsTracker.js +21 -0
- package/dist/server/libs/btpsSimpleRateLimiter.d.ts +28 -0
- package/dist/server/libs/btpsSimpleRateLimiter.js +46 -0
- package/dist/server/libs/connectionTimeout.d.ts +16 -0
- package/dist/server/libs/connectionTimeout.js +14 -0
- package/dist/server/libs/defaultMiddleware.d.ts +8 -0
- package/dist/server/libs/defaultMiddleware.js +128 -0
- package/dist/server/libs/inFlightLimit.d.ts +18 -0
- package/dist/server/libs/inFlightLimit.js +17 -0
- package/dist/server/libs/index.d.ts +18 -0
- package/dist/server/libs/index.js +34 -0
- package/dist/server/libs/middlewareManager.js +126 -0
- package/dist/server/libs/type.d.ts +22 -0
- package/dist/server/libs/type.js +7 -0
- package/dist/server/types.d.ts +236 -0
- package/dist/server/types.js +7 -0
- package/package.json +126 -4
|
@@ -0,0 +1,18 @@
|
|
|
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
|
+
/** How many requests one connection may have handled at once unless the server sets `maxInFlightPerConnection`. */
|
|
8
|
+
export declare const DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION = 32;
|
|
9
|
+
/** The smallest limit a server may set: one request at a time. */
|
|
10
|
+
export declare const MIN_MAX_IN_FLIGHT_PER_CONNECTION = 1;
|
|
11
|
+
/**
|
|
12
|
+
* The limit a server uses. At the limit it stops reading the connection until
|
|
13
|
+
* a request finishes, so a sender that does not wait for answers is slowed by
|
|
14
|
+
* TCP instead of filling the server's memory. A value it cannot use never
|
|
15
|
+
* stops the server: it is warned about and replaced by the minimum (when too
|
|
16
|
+
* small) or the default (when not a whole number).
|
|
17
|
+
*/
|
|
18
|
+
export declare const resolveMaxInFlightPerConnection: (configured: number | undefined) => number;
|
|
@@ -0,0 +1,17 @@
|
|
|
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
|
+
const DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION = 32, MIN_MAX_IN_FLIGHT_PER_CONNECTION = 1, resolveMaxInFlightPerConnection = (configured) => configured === void 0 ? 32 : Number.isInteger(configured) ? configured < 1 ? (console.warn(
|
|
9
|
+
`[BtpsServer] maxInFlightPerConnection ${configured} is below the minimum 1; using 1`
|
|
10
|
+
), 1) : configured : (console.warn(
|
|
11
|
+
`[BtpsServer] maxInFlightPerConnection ${configured} is not a whole number; using the default 32`
|
|
12
|
+
), 32);
|
|
13
|
+
export {
|
|
14
|
+
DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION,
|
|
15
|
+
MIN_MAX_IN_FLIGHT_PER_CONNECTION,
|
|
16
|
+
resolveMaxInFlightPerConnection
|
|
17
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
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
|
+
export * from './abstractRateLimiter.js';
|
|
8
|
+
export { DEFAULT_MAX_ARTIFACT_SIZE_KB, MIN_MAX_ARTIFACT_SIZE_KB } from './artifactSizeGuard.js';
|
|
9
|
+
export { DEFAULT_MAX_ARTIFACT_AGE_SECONDS, MIN_MAX_ARTIFACT_AGE_SECONDS, } from './artifactTimeWindow.js';
|
|
10
|
+
export { DEFAULT_CONNECTION_TIMEOUT_MS } from './connectionTimeout.js';
|
|
11
|
+
export { DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION, MIN_MAX_IN_FLIGHT_PER_CONNECTION, } from './inFlightLimit.js';
|
|
12
|
+
export * from './btpsFactory.js';
|
|
13
|
+
export * from './btpsLightweightFactory.js';
|
|
14
|
+
export * from './btpsRegistry.js';
|
|
15
|
+
export * from './btpsSimpleMetricsTracker.js';
|
|
16
|
+
export * from './btpsSimpleRateLimiter.js';
|
|
17
|
+
export * from './defaultMiddleware.js';
|
|
18
|
+
export * from './type.js';
|
|
@@ -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
|
+
|
|
8
|
+
export * from "./abstractRateLimiter.js";
|
|
9
|
+
import { DEFAULT_MAX_ARTIFACT_SIZE_KB, MIN_MAX_ARTIFACT_SIZE_KB } from "./artifactSizeGuard.js";
|
|
10
|
+
import {
|
|
11
|
+
DEFAULT_MAX_ARTIFACT_AGE_SECONDS,
|
|
12
|
+
MIN_MAX_ARTIFACT_AGE_SECONDS
|
|
13
|
+
} from "./artifactTimeWindow.js";
|
|
14
|
+
import { DEFAULT_CONNECTION_TIMEOUT_MS } from "./connectionTimeout.js";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION,
|
|
17
|
+
MIN_MAX_IN_FLIGHT_PER_CONNECTION
|
|
18
|
+
} from "./inFlightLimit.js";
|
|
19
|
+
export * from "./btpsFactory.js";
|
|
20
|
+
export * from "./btpsLightweightFactory.js";
|
|
21
|
+
export * from "./btpsRegistry.js";
|
|
22
|
+
export * from "./btpsSimpleMetricsTracker.js";
|
|
23
|
+
export * from "./btpsSimpleRateLimiter.js";
|
|
24
|
+
export * from "./defaultMiddleware.js";
|
|
25
|
+
export * from "./type.js";
|
|
26
|
+
export {
|
|
27
|
+
DEFAULT_CONNECTION_TIMEOUT_MS,
|
|
28
|
+
DEFAULT_MAX_ARTIFACT_AGE_SECONDS,
|
|
29
|
+
DEFAULT_MAX_ARTIFACT_SIZE_KB,
|
|
30
|
+
DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION,
|
|
31
|
+
MIN_MAX_ARTIFACT_AGE_SECONDS,
|
|
32
|
+
MIN_MAX_ARTIFACT_SIZE_KB,
|
|
33
|
+
MIN_MAX_IN_FLIGHT_PER_CONNECTION
|
|
34
|
+
};
|
|
@@ -0,0 +1,126 @@
|
|
|
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 { existsSync } from "fs";
|
|
9
|
+
import { resolve } from "path";
|
|
10
|
+
import isEmpty from "lodash/isEmpty.js";
|
|
11
|
+
import { BTPErrorException } from "../../core/error/index.js";
|
|
12
|
+
class MiddlewareManager {
|
|
13
|
+
constructor(middlewarePath) {
|
|
14
|
+
this.middlewarePath = middlewarePath;
|
|
15
|
+
this.configuredPath = !isEmpty(middlewarePath), this.configuredPath || (this.middlewarePath = `${process.cwd()}/btps.middleware.mjs`);
|
|
16
|
+
}
|
|
17
|
+
middleware = [];
|
|
18
|
+
lifecycleHooks = {};
|
|
19
|
+
configuredPath;
|
|
20
|
+
async loadMiddleware(dependencies) {
|
|
21
|
+
if (!this.middlewarePath) return;
|
|
22
|
+
const resolvedPath = resolve(this.middlewarePath);
|
|
23
|
+
if (!existsSync(resolvedPath)) {
|
|
24
|
+
this.configuredPath && console.warn(
|
|
25
|
+
`[MiddlewareManager] No middleware file at ${resolvedPath}; the server is running without middleware`
|
|
26
|
+
);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const createMiddleware = (await import(resolvedPath)).default;
|
|
31
|
+
if (typeof createMiddleware != "function")
|
|
32
|
+
throw new BTPErrorException({ message: "Middleware file must export a default function" });
|
|
33
|
+
const result = createMiddleware(dependencies);
|
|
34
|
+
if (this.isMiddlewareModule(result))
|
|
35
|
+
this.middleware = this.validateAndSortMiddleware(result.middleware), this.lifecycleHooks = {
|
|
36
|
+
onServerStart: result.onServerStart,
|
|
37
|
+
onServerStop: result.onServerStop,
|
|
38
|
+
onResponseSent: result.onResponseSent
|
|
39
|
+
};
|
|
40
|
+
else if (Array.isArray(result))
|
|
41
|
+
this.middleware = this.validateAndSortMiddleware(result);
|
|
42
|
+
else
|
|
43
|
+
throw new BTPErrorException({
|
|
44
|
+
message: "Middleware function must return an array or MiddlewareModule"
|
|
45
|
+
});
|
|
46
|
+
console.log(`[MiddlewareManager] Loaded ${this.middleware.length} middleware`);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
throw console.error("[MiddlewareManager] Failed to load middleware:", error), new BTPErrorException({
|
|
49
|
+
message: `Failed to load middleware from ${resolvedPath}: ${error}`
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
validateAndSortMiddleware(middleware) {
|
|
54
|
+
if (!Array.isArray(middleware))
|
|
55
|
+
throw new BTPErrorException({ message: "Middleware must be an array" });
|
|
56
|
+
const validMiddleware = [];
|
|
57
|
+
return middleware.forEach((mw, index) => {
|
|
58
|
+
try {
|
|
59
|
+
this.validateMiddlewareDefinition(mw, index), mw.config?.enabled !== !1 && validMiddleware.push(mw);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
console.warn(`[MiddlewareManager] Skipping invalid middleware at index ${index}:`, error);
|
|
62
|
+
}
|
|
63
|
+
}), validMiddleware.sort((a, b) => {
|
|
64
|
+
const priorityA = a.priority ?? Number.MAX_SAFE_INTEGER, priorityB = b.priority ?? Number.MAX_SAFE_INTEGER;
|
|
65
|
+
return priorityA - priorityB;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
validateMiddlewareDefinition(mw, index) {
|
|
69
|
+
if (!mw || typeof mw != "object")
|
|
70
|
+
throw new BTPErrorException({ message: "Middleware must be an object" });
|
|
71
|
+
const middleware = mw;
|
|
72
|
+
if (!middleware.phase || !["before", "after"].includes(middleware.phase))
|
|
73
|
+
throw new BTPErrorException({
|
|
74
|
+
message: "Middleware must have a valid phase (before or after)"
|
|
75
|
+
});
|
|
76
|
+
if (!middleware.step || !["parsing", "signatureVerification", "trustVerification", "onArtifact", "onError"].includes(
|
|
77
|
+
middleware.step
|
|
78
|
+
))
|
|
79
|
+
throw new BTPErrorException({ message: "Middleware must have a valid step" });
|
|
80
|
+
if (typeof middleware.handler != "function")
|
|
81
|
+
throw new BTPErrorException({ message: "Middleware must have a handler function" });
|
|
82
|
+
if (middleware.priority !== void 0 && (typeof middleware.priority != "number" || !Number.isInteger(middleware.priority) || middleware.priority < 0))
|
|
83
|
+
throw new BTPErrorException({
|
|
84
|
+
message: "Middleware priority must be a non-negative integer"
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
isMiddlewareModule(result) {
|
|
88
|
+
return result !== null && typeof result == "object" && "middleware" in result && Array.isArray(result.middleware);
|
|
89
|
+
}
|
|
90
|
+
getMiddleware(phase, step) {
|
|
91
|
+
return this.middleware.filter((mw) => mw.phase === phase && mw.step === step);
|
|
92
|
+
}
|
|
93
|
+
getAllMiddleware() {
|
|
94
|
+
return [...this.middleware];
|
|
95
|
+
}
|
|
96
|
+
getLifecycleHooks() {
|
|
97
|
+
return { ...this.lifecycleHooks };
|
|
98
|
+
}
|
|
99
|
+
async onServerStart() {
|
|
100
|
+
if (this.lifecycleHooks.onServerStart)
|
|
101
|
+
try {
|
|
102
|
+
await this.lifecycleHooks.onServerStart();
|
|
103
|
+
} catch (error) {
|
|
104
|
+
console.error("[MiddlewareManager] Error in onServerStart hook:", error);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async onServerStop() {
|
|
108
|
+
if (this.lifecycleHooks.onServerStop)
|
|
109
|
+
try {
|
|
110
|
+
await this.lifecycleHooks.onServerStop();
|
|
111
|
+
} catch (error) {
|
|
112
|
+
console.error("[MiddlewareManager] Error in onServerStop hook:", error);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async onResponseSent(response) {
|
|
116
|
+
if (this.lifecycleHooks.onResponseSent)
|
|
117
|
+
try {
|
|
118
|
+
await this.lifecycleHooks.onResponseSent(response);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
console.error("[MiddlewareManager] Error in onResponseSent hook:", error);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export {
|
|
125
|
+
MiddlewareManager
|
|
126
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
export interface IRateLimitOptions {
|
|
8
|
+
ipAddress?: number;
|
|
9
|
+
fromIdentity?: number;
|
|
10
|
+
cleanupIntervalSec?: number;
|
|
11
|
+
/** The most counters kept per type (default 100000); past it, the oldest is dropped */
|
|
12
|
+
maxEntries?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface IMetricsTracker {
|
|
15
|
+
onMessageReceived(sender: string, recipient?: string): void;
|
|
16
|
+
onMessageRejected(sender: string, recipient: string, reason: string): void;
|
|
17
|
+
onError(error: Error): void;
|
|
18
|
+
}
|
|
19
|
+
export interface CounterRecord {
|
|
20
|
+
count: number;
|
|
21
|
+
windowStart: number;
|
|
22
|
+
}
|
|
@@ -0,0 +1,236 @@
|
|
|
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 { TlsOptions, TLSSocket } from 'tls';
|
|
8
|
+
import { BTPTrustRecord } from '../core/trust/index.js';
|
|
9
|
+
import { AbstractTrustStore } from '../core/trust/storage/AbstractTrustStore.js';
|
|
10
|
+
import { BTPAgentArtifact, BTPControlArtifact, BTPIdentityLookupRequest, BTPServerResponse, BTPTransporterArtifact, CurrencyCode } from '../core/server/types.js';
|
|
11
|
+
import { BTPError } from '../core/error/types.js';
|
|
12
|
+
import { BTPErrorException } from '../core/error/index.js';
|
|
13
|
+
import { BTPIdentityRecord } from '../core/storage/types.js';
|
|
14
|
+
import { AbstractIdentityStore } from '../core/storage/AbstractIdentityStore.js';
|
|
15
|
+
import type { Signer } from '../core/crypto/signer-interface.js';
|
|
16
|
+
import type { z } from 'zod';
|
|
17
|
+
import type { BtpLetterDocSchema, BtpPayslipDocSchema } from '../core/server/schemas/btpsDocsSchema.js';
|
|
18
|
+
export interface BtpsTlsOptions extends TlsOptions {
|
|
19
|
+
cert: string;
|
|
20
|
+
key: string;
|
|
21
|
+
}
|
|
22
|
+
export interface BtpsServerOptions {
|
|
23
|
+
/** The server's own key, as a PEM key pair or a Signer holding it elsewhere (a KMS). */
|
|
24
|
+
serverIdentity: {
|
|
25
|
+
identity: string;
|
|
26
|
+
publicKey: string;
|
|
27
|
+
privateKey: string;
|
|
28
|
+
} | {
|
|
29
|
+
identity: string;
|
|
30
|
+
signer: Signer;
|
|
31
|
+
};
|
|
32
|
+
trustStore: AbstractTrustStore<BTPTrustRecord>;
|
|
33
|
+
tlsOptions: BtpsTlsOptions;
|
|
34
|
+
identityStore?: AbstractIdentityStore<BTPIdentityRecord>;
|
|
35
|
+
port?: number;
|
|
36
|
+
onError?: (err: BTPErrorException) => void;
|
|
37
|
+
/** Closes a connection after this long with no request being handled, in ms. Default 30000; no minimum. A connection is never closed while one of its requests is handled. */
|
|
38
|
+
connectionTimeoutMs?: number;
|
|
39
|
+
middlewarePath?: string;
|
|
40
|
+
/** The largest artifact this server can accept, in KB (1 KB = 1024 bytes). Default 5120 (5 MB), minimum 1024 (1 MB). */
|
|
41
|
+
maxArtifactSizeKb?: number;
|
|
42
|
+
/** How far an artifact's issuedAt may be from this server's clock, in seconds, either way. Default 300 (5 minutes), minimum 60. */
|
|
43
|
+
maxArtifactAgeSeconds?: number;
|
|
44
|
+
/** How many requests one connection may have handled at once; at the limit the server stops reading it until one finishes. Default 32, minimum 1. */
|
|
45
|
+
maxInFlightPerConnection?: number;
|
|
46
|
+
}
|
|
47
|
+
export type Phase = 'before' | 'after';
|
|
48
|
+
export type Step = 'parsing' | 'signatureVerification' | 'trustVerification' | 'onArtifact' | 'onError';
|
|
49
|
+
export interface MiddlewareConfig {
|
|
50
|
+
name?: string;
|
|
51
|
+
enabled?: boolean;
|
|
52
|
+
options?: Record<string, unknown>;
|
|
53
|
+
}
|
|
54
|
+
export interface MiddlewareContext {
|
|
55
|
+
dependencies: {
|
|
56
|
+
trustStore: AbstractTrustStore<BTPTrustRecord>;
|
|
57
|
+
identityStore?: AbstractIdentityStore<BTPIdentityRecord>;
|
|
58
|
+
};
|
|
59
|
+
config: Record<string, unknown>;
|
|
60
|
+
serverInstance: unknown;
|
|
61
|
+
currentTime: string;
|
|
62
|
+
}
|
|
63
|
+
export type BtpsErrorAction = 'destroy' | 'end';
|
|
64
|
+
export interface BTPContext {
|
|
65
|
+
socket: TLSSocket;
|
|
66
|
+
startTime: string;
|
|
67
|
+
remoteAddress: string;
|
|
68
|
+
rawPacket?: string;
|
|
69
|
+
sendRes?: (res: BTPServerResponse) => void;
|
|
70
|
+
sendError?: (err: BTPError, action?: BtpsErrorAction) => void;
|
|
71
|
+
}
|
|
72
|
+
export type SetRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
|
|
73
|
+
export type ArtifactResCtx = {
|
|
74
|
+
sendRes: Required<BTPContext>['sendRes'];
|
|
75
|
+
sendError: Required<BTPContext>['sendError'];
|
|
76
|
+
};
|
|
77
|
+
type HasArtifact<_P extends Phase, S extends Step> = S extends 'parsing' ? false : true;
|
|
78
|
+
type HasReqId<_P extends Phase, S extends Step> = S extends 'parsing' ? false : true;
|
|
79
|
+
type HasIsValid<P extends Phase, S extends Step> = P extends 'after' ? S extends 'signatureVerification' | 'trustVerification' | 'onArtifact' ? true : false : S extends 'trustVerification' | 'onArtifact' ? true : false;
|
|
80
|
+
type HasIsTrusted<P extends Phase, S extends Step> = P extends 'after' ? S extends 'trustVerification' | 'onArtifact' ? true : false : S extends 'onArtifact' ? true : false;
|
|
81
|
+
type HasError<_P extends Phase, _S extends Step> = false;
|
|
82
|
+
type HasRawPacket<P extends Phase, S extends Step> = S extends 'parsing' ? P extends 'before' ? false : true : false;
|
|
83
|
+
type HasIdentity<P extends Phase, S extends Step> = S extends 'parsing' ? P extends 'before' ? false : true : true;
|
|
84
|
+
type WithRespondNow<K extends string, T> = K extends 'agent' ? {
|
|
85
|
+
artifact: T;
|
|
86
|
+
type: K;
|
|
87
|
+
respondNow: boolean;
|
|
88
|
+
} : {
|
|
89
|
+
artifact: T;
|
|
90
|
+
type: K;
|
|
91
|
+
};
|
|
92
|
+
type ArtifactMap = {
|
|
93
|
+
transporter: BTPTransporterArtifact;
|
|
94
|
+
agent: BTPAgentArtifact;
|
|
95
|
+
identityLookup: BTPIdentityLookupRequest;
|
|
96
|
+
control: BTPControlArtifact;
|
|
97
|
+
};
|
|
98
|
+
type ProcessedArtifactMap = {
|
|
99
|
+
transporter: BTPTransporterArtifact;
|
|
100
|
+
agent: BTPAgentArtifact;
|
|
101
|
+
};
|
|
102
|
+
export type PreProcessedArtifact = {
|
|
103
|
+
[K in keyof ArtifactMap]: WithRespondNow<K, ArtifactMap[K]>;
|
|
104
|
+
}[keyof ArtifactMap];
|
|
105
|
+
export type ProcessedArtifact = {
|
|
106
|
+
[K in keyof ProcessedArtifactMap]: WithRespondNow<K, ProcessedArtifactMap[K]>;
|
|
107
|
+
}[keyof ProcessedArtifactMap];
|
|
108
|
+
type ArtifactDataType<_P extends Phase, S extends Step> = S extends 'parsing' ? PreProcessedArtifact : ProcessedArtifact;
|
|
109
|
+
export type BTPRequestCtx<P extends Phase = Phase, S extends Step = Step> = Omit<BTPContext, 'sendRes' | 'sendError'> & (HasRawPacket<P, S> extends true ? {
|
|
110
|
+
rawPacket: string;
|
|
111
|
+
} : {
|
|
112
|
+
rawPacket?: string;
|
|
113
|
+
}) & (HasArtifact<P, S> extends true ? {
|
|
114
|
+
data: ArtifactDataType<P, S>;
|
|
115
|
+
} : {
|
|
116
|
+
data?: ArtifactDataType<P, S>;
|
|
117
|
+
}) & (HasIsValid<P, S> extends true ? {
|
|
118
|
+
isValid: boolean;
|
|
119
|
+
} : {
|
|
120
|
+
isValid?: boolean;
|
|
121
|
+
}) & (HasIsTrusted<P, S> extends true ? {
|
|
122
|
+
isTrusted: boolean;
|
|
123
|
+
} : {
|
|
124
|
+
isTrusted?: boolean;
|
|
125
|
+
}) & (HasError<P, S> extends true ? {
|
|
126
|
+
error: BTPErrorException;
|
|
127
|
+
} : {
|
|
128
|
+
error?: BTPErrorException;
|
|
129
|
+
}) & (HasIdentity<P, S> extends true ? {
|
|
130
|
+
getIdentity: () => {
|
|
131
|
+
to: string;
|
|
132
|
+
from: string;
|
|
133
|
+
};
|
|
134
|
+
} : {
|
|
135
|
+
getIdentity: () => {
|
|
136
|
+
to?: string;
|
|
137
|
+
from?: string;
|
|
138
|
+
};
|
|
139
|
+
}) & {
|
|
140
|
+
[key: string]: unknown;
|
|
141
|
+
};
|
|
142
|
+
export type BTPResponseCtx<P extends Phase = Phase, S extends Step = Step> = SetRequired<BTPContext, 'sendRes' | 'sendError'> & (HasReqId<P, S> extends true ? {
|
|
143
|
+
reqId: string;
|
|
144
|
+
} : {
|
|
145
|
+
reqId?: string;
|
|
146
|
+
}) & (HasArtifact<P, S> extends true ? {
|
|
147
|
+
data: ArtifactDataType<P, S>;
|
|
148
|
+
} : {
|
|
149
|
+
data?: ArtifactDataType<P, S>;
|
|
150
|
+
}) & {
|
|
151
|
+
responseSent: boolean;
|
|
152
|
+
[key: string]: unknown;
|
|
153
|
+
};
|
|
154
|
+
export type Next = () => Promise<void> | void;
|
|
155
|
+
export type MiddlewareHandler<P extends Phase = Phase, S extends Step = Step> = (req: BTPRequestCtx<P, S>, res: BTPResponseCtx<P, S>, next: Next, context?: MiddlewareContext) => Promise<void> | void;
|
|
156
|
+
export interface MiddlewareDefinition<P extends Phase = Phase, S extends Step = Step> {
|
|
157
|
+
phase: P;
|
|
158
|
+
step: S;
|
|
159
|
+
priority?: number;
|
|
160
|
+
config?: MiddlewareConfig;
|
|
161
|
+
handler: MiddlewareHandler<P, S>;
|
|
162
|
+
}
|
|
163
|
+
export type MiddlewareDefinitionArray = Array<MiddlewareDefinition<'before', 'parsing'> | MiddlewareDefinition<'after', 'parsing'> | MiddlewareDefinition<'before', 'signatureVerification'> | MiddlewareDefinition<'after', 'signatureVerification'> | MiddlewareDefinition<'before', 'trustVerification'> | MiddlewareDefinition<'after', 'trustVerification'> | MiddlewareDefinition<'before', 'onArtifact'> | MiddlewareDefinition<'after', 'onArtifact'> | MiddlewareDefinition<'before', 'onError'> | MiddlewareDefinition<'after', 'onError'>>;
|
|
164
|
+
export interface MiddlewareModule {
|
|
165
|
+
middleware: MiddlewareDefinitionArray;
|
|
166
|
+
onServerStart?: () => Promise<void> | void;
|
|
167
|
+
onServerStop?: () => Promise<void> | void;
|
|
168
|
+
onResponseSent?: (response: BTPServerResponse) => Promise<void> | void;
|
|
169
|
+
}
|
|
170
|
+
export type Middleware<T, U> = (req: T, res: U, next: Next) => Promise<void>;
|
|
171
|
+
export interface BTPAttachment {
|
|
172
|
+
content: string;
|
|
173
|
+
type: 'application/pdf' | 'image/jpeg' | 'image/png';
|
|
174
|
+
filename?: string;
|
|
175
|
+
size: number;
|
|
176
|
+
sha256: string;
|
|
177
|
+
}
|
|
178
|
+
/** A link to another signed document: `correction_of`, `credits`, `instalment_of`, `follows`, or a prefixed code. */
|
|
179
|
+
export interface BTPDocReference {
|
|
180
|
+
type: string;
|
|
181
|
+
from: string;
|
|
182
|
+
id: string;
|
|
183
|
+
sha256: string;
|
|
184
|
+
}
|
|
185
|
+
export interface BTPInvoiceDoc {
|
|
186
|
+
type: 'invoice';
|
|
187
|
+
title: string;
|
|
188
|
+
id: string;
|
|
189
|
+
issuedAt: string;
|
|
190
|
+
dueAt?: string;
|
|
191
|
+
totalAmount: {
|
|
192
|
+
amount: number;
|
|
193
|
+
currency: CurrencyCode;
|
|
194
|
+
};
|
|
195
|
+
lineItems: {
|
|
196
|
+
columns: string[];
|
|
197
|
+
rows: Array<Record<string, string | number>>;
|
|
198
|
+
};
|
|
199
|
+
issuer?: {
|
|
200
|
+
name: string;
|
|
201
|
+
email?: string;
|
|
202
|
+
phone?: string;
|
|
203
|
+
address?: string;
|
|
204
|
+
identifiers?: Record<string, string>;
|
|
205
|
+
};
|
|
206
|
+
paymentLink?: {
|
|
207
|
+
linkText: string;
|
|
208
|
+
url: string;
|
|
209
|
+
};
|
|
210
|
+
description?: string;
|
|
211
|
+
attachments?: BTPAttachment[];
|
|
212
|
+
references?: BTPDocReference[];
|
|
213
|
+
template?: {
|
|
214
|
+
name: string;
|
|
215
|
+
data: Record<string, unknown>;
|
|
216
|
+
};
|
|
217
|
+
metadata?: Record<string, unknown>;
|
|
218
|
+
}
|
|
219
|
+
/** Proof of a payment: the invoice without what asks for payment, plus `payment`. */
|
|
220
|
+
export interface BTPReceiptDoc extends Omit<BTPInvoiceDoc, 'type' | 'dueAt' | 'paymentLink' | 'lineItems'> {
|
|
221
|
+
type: 'receipt';
|
|
222
|
+
lineItems?: BTPInvoiceDoc['lineItems'];
|
|
223
|
+
payment: {
|
|
224
|
+
amount: BTPInvoiceDoc['totalAmount'];
|
|
225
|
+
paidAt: string;
|
|
226
|
+
method?: string;
|
|
227
|
+
reference?: string;
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/** A payslip: earnings, deductions, contributions and leave, each named by an open code. */
|
|
231
|
+
export type BTPPayslipDoc = z.infer<typeof BtpPayslipDocSchema>;
|
|
232
|
+
/** A letter: a title and one body, `text` or `markdown`. */
|
|
233
|
+
export type BTPLetterDoc = z.infer<typeof BtpLetterDocSchema>;
|
|
234
|
+
/** What a `BTPS_DOC` carries. */
|
|
235
|
+
export type BTPDocument = BTPInvoiceDoc | BTPReceiptDoc | BTPPayslipDoc | BTPLetterDoc;
|
|
236
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,128 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@btps/sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.1",
|
|
4
|
+
"description": "The reference implementation of BTPS, the Billing Trust Protocol Secure: signed, encrypted, trust-first delivery of invoices and documents between organisations.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"btps",
|
|
7
|
+
"billing",
|
|
8
|
+
"invoice",
|
|
9
|
+
"e-invoicing",
|
|
10
|
+
"protocol",
|
|
11
|
+
"trust",
|
|
12
|
+
"signature",
|
|
13
|
+
"encryption",
|
|
14
|
+
"dns"
|
|
15
|
+
],
|
|
16
|
+
"homepage": "https://www.openbtps.org/docs/",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/openbtps/btps-node.git"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/openbtps/btps-node/issues"
|
|
23
|
+
},
|
|
24
|
+
"packageManager": "yarn@4.9.2",
|
|
25
|
+
"type": "module",
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=24"
|
|
28
|
+
},
|
|
29
|
+
"main": "./dist/index.js",
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"author": {
|
|
33
|
+
"name": "Bhupendra Tamang",
|
|
34
|
+
"email": "admin@openbtps.org"
|
|
35
|
+
},
|
|
36
|
+
"exports": {
|
|
37
|
+
".": {
|
|
38
|
+
"import": "./dist/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./server": {
|
|
41
|
+
"import": "./dist/server/index.js"
|
|
42
|
+
},
|
|
43
|
+
"./server/core": {
|
|
44
|
+
"import": "./dist/server/libs/index.js"
|
|
45
|
+
},
|
|
46
|
+
"./client": {
|
|
47
|
+
"import": "./dist/client/index.js"
|
|
48
|
+
},
|
|
49
|
+
"./crypto": {
|
|
50
|
+
"import": "./dist/core/crypto/index.js"
|
|
51
|
+
},
|
|
52
|
+
"./trust": {
|
|
53
|
+
"import": "./dist/core/trust/index.js"
|
|
54
|
+
},
|
|
55
|
+
"./authentication": {
|
|
56
|
+
"import": "./dist/core/authentication/index.js"
|
|
57
|
+
},
|
|
58
|
+
"./delegation": {
|
|
59
|
+
"import": "./dist/core/delegation/index.js"
|
|
60
|
+
},
|
|
61
|
+
"./error": {
|
|
62
|
+
"import": "./dist/core/error/index.js"
|
|
63
|
+
},
|
|
64
|
+
"./storage": {
|
|
65
|
+
"import": "./dist/core/storage/index.js"
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
"files": [
|
|
69
|
+
"dist",
|
|
70
|
+
"NOTICE",
|
|
71
|
+
"CHANGELOG.md"
|
|
72
|
+
],
|
|
73
|
+
"scripts": {
|
|
74
|
+
"clean": "rimraf dist",
|
|
75
|
+
"build:mjs": "node build/index.mjs",
|
|
76
|
+
"build:add-license": "bash scripts/add-license-header.sh",
|
|
77
|
+
"build:types": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && node build/pruneTypes.mjs",
|
|
78
|
+
"build": "yarn build:add-license && yarn clean && yarn build:mjs && yarn build:types && yarn build:add-license -dir ./dist",
|
|
79
|
+
"dev": "nodemon --config nodemon.json",
|
|
80
|
+
"start": "node ./dist/server/index.js",
|
|
81
|
+
"base64": "bash -c 'base64 -i \"$1\" | tr -d \"\\n\"' --",
|
|
82
|
+
"typecheck": "tsc --noEmit",
|
|
83
|
+
"test": "vitest run --coverage",
|
|
84
|
+
"test:e2e": "vitest run -c vitest.e2e.config.ts",
|
|
85
|
+
"test:security": "vitest run -c vitest.security.config.ts",
|
|
86
|
+
"test:watch": "vitest --watch",
|
|
87
|
+
"test:coverage": "vitest run --coverage",
|
|
88
|
+
"verify:btps-vectors": "node packages/verify-btps-vectors/bin/verify-btps-vectors.mjs --known-failing test/vectors/known-failing.json",
|
|
89
|
+
"build:strip-comments": "node build/stripComments.mjs"
|
|
90
|
+
},
|
|
91
|
+
"devDependencies": {
|
|
92
|
+
"@types/lodash": "^4",
|
|
93
|
+
"@types/proper-lockfile": "^4",
|
|
94
|
+
"@types/split2": "^4",
|
|
95
|
+
"@types/strip-comments": "^2",
|
|
96
|
+
"@typescript-eslint/eslint-plugin": "^6.0.0",
|
|
97
|
+
"@typescript-eslint/parser": "^6.0.0",
|
|
98
|
+
"@vitest/coverage-v8": "3.2.4",
|
|
99
|
+
"@vitest/ui": "^3.2.4",
|
|
100
|
+
"chalk": "^5.4.1",
|
|
101
|
+
"cli-table3": "^0.6.5",
|
|
102
|
+
"esbuild": "^0.25.5",
|
|
103
|
+
"esbuild-plugin-alias": "^0.2.1",
|
|
104
|
+
"eslint": "^8.0.0",
|
|
105
|
+
"eslint-config-prettier": "^9.0.0",
|
|
106
|
+
"eslint-import-resolver-typescript": "^4.4.3",
|
|
107
|
+
"eslint-plugin-import": "^2.29.0",
|
|
108
|
+
"fast-glob": "^3.3.3",
|
|
109
|
+
"nodemon": "^3.0.0",
|
|
110
|
+
"ora": "^8.2.0",
|
|
111
|
+
"prettier": "^3.0.0",
|
|
112
|
+
"rimraf": "^6.0.1",
|
|
113
|
+
"strip-comments": "^2.0.1",
|
|
114
|
+
"ts-loader": "^9.0.0",
|
|
115
|
+
"tsc-alias": "^1.8.16",
|
|
116
|
+
"typescript": "^5.8.3",
|
|
117
|
+
"vite-tsconfig-paths": "^5.1.4",
|
|
118
|
+
"vitest": "^3.2.4"
|
|
119
|
+
},
|
|
120
|
+
"dependencies": {
|
|
121
|
+
"@humanwhocodes/momoa": "^3.3.13",
|
|
122
|
+
"canonicalize": "^5.1.0",
|
|
123
|
+
"lodash": "^4.17.21",
|
|
124
|
+
"proper-lockfile": "^4.1.2",
|
|
125
|
+
"split2": "^4.2.0",
|
|
126
|
+
"zod": "^3.25.67"
|
|
127
|
+
}
|
|
128
|
+
}
|