@btps/sdk 0.0.0-stage → 1.1.0

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 (167) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/LICENSE +190 -0
  3. package/NOTICE +25 -0
  4. package/README.md +261 -2
  5. package/dist/client/btpsAgent.d.ts +20 -0
  6. package/dist/client/btpsAgent.js +172 -0
  7. package/dist/client/btpsClient.d.ts +202 -0
  8. package/dist/client/btpsClient.js +602 -0
  9. package/dist/client/btpsTransporter.d.ts +52 -0
  10. package/dist/client/btpsTransporter.js +249 -0
  11. package/dist/client/constants.ts/index.d.ts +11 -0
  12. package/dist/client/constants.ts/index.js +20 -0
  13. package/dist/client/index.d.ts +12 -0
  14. package/dist/client/index.js +27 -0
  15. package/dist/client/libs/schema.d.ts +27604 -0
  16. package/dist/client/libs/schema.js +56 -0
  17. package/dist/client/libs/timeouts.d.ts +22 -0
  18. package/dist/client/libs/timeouts.js +19 -0
  19. package/dist/client/types/index.d.ts +155 -0
  20. package/dist/client/types/index.js +7 -0
  21. package/dist/core/authentication/BtpsAuthentication.d.ts +128 -0
  22. package/dist/core/authentication/BtpsAuthentication.js +293 -0
  23. package/dist/core/authentication/index.d.ts +11 -0
  24. package/dist/core/authentication/index.js +12 -0
  25. package/dist/core/authentication/keyProof.d.ts +18 -0
  26. package/dist/core/authentication/keyProof.js +16 -0
  27. package/dist/core/authentication/storage/InMemoryAuthSessionStore.d.ts +55 -0
  28. package/dist/core/authentication/storage/InMemoryAuthSessionStore.js +62 -0
  29. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +63 -0
  30. package/dist/core/authentication/storage/InMemoryTokenStore.js +63 -0
  31. package/dist/core/authentication/types.d.ts +135 -0
  32. package/dist/core/authentication/types.js +7 -0
  33. package/dist/core/crypto/decryptVerify.d.ts +9 -0
  34. package/dist/core/crypto/decryptVerify.js +45 -0
  35. package/dist/core/crypto/decrypter-interface.d.ts +25 -0
  36. package/dist/core/crypto/decrypter-interface.js +7 -0
  37. package/dist/core/crypto/index.d.ts +77 -0
  38. package/dist/core/crypto/index.js +210 -0
  39. package/dist/core/crypto/jcs.d.ts +28 -0
  40. package/dist/core/crypto/jcs.js +60 -0
  41. package/dist/core/crypto/keygen.d.ts +9 -0
  42. package/dist/core/crypto/keygen.js +35 -0
  43. package/dist/core/crypto/pem-decrypter.d.ts +26 -0
  44. package/dist/core/crypto/pem-decrypter.js +52 -0
  45. package/dist/core/crypto/pem-signer.d.ts +21 -0
  46. package/dist/core/crypto/pem-signer.js +34 -0
  47. package/dist/core/crypto/signEncrypt.d.ts +34 -0
  48. package/dist/core/crypto/signEncrypt.js +75 -0
  49. package/dist/core/crypto/signer-interface.d.ts +22 -0
  50. package/dist/core/crypto/signer-interface.js +7 -0
  51. package/dist/core/crypto/types.d.ts +79 -0
  52. package/dist/core/crypto/types.js +7 -0
  53. package/dist/core/delegation/BtpsDelegator.d.ts +102 -0
  54. package/dist/core/delegation/BtpsDelegator.js +118 -0
  55. package/dist/core/delegation/index.d.ts +7 -0
  56. package/dist/core/delegation/index.js +8 -0
  57. package/dist/core/error/constant.d.ts +66 -0
  58. package/dist/core/error/constant.js +194 -0
  59. package/dist/core/error/index.d.ts +35 -0
  60. package/dist/core/error/index.js +52 -0
  61. package/dist/core/error/types.d.ts +16 -0
  62. package/dist/core/error/types.js +7 -0
  63. package/dist/core/server/constants/btps-protocol.d.ts +17 -0
  64. package/dist/core/server/constants/btps-protocol.js +25 -0
  65. package/dist/core/server/constants/control.d.ts +7 -0
  66. package/dist/core/server/constants/control.js +11 -0
  67. package/dist/core/server/constants/currency.d.ts +7 -0
  68. package/dist/core/server/constants/currency.js +332 -0
  69. package/dist/core/server/constants/index.d.ts +26 -0
  70. package/dist/core/server/constants/index.js +61 -0
  71. package/dist/core/server/constants/limits.d.ts +50 -0
  72. package/dist/core/server/constants/limits.js +50 -0
  73. package/dist/core/server/helpers/BtpsMessageQueue.d.ts +13 -0
  74. package/dist/core/server/helpers/BtpsMessageQueue.js +12 -0
  75. package/dist/core/server/helpers/InMemoryQueue.d.ts +16 -0
  76. package/dist/core/server/helpers/InMemoryQueue.js +35 -0
  77. package/dist/core/server/helpers/index.d.ts +8 -0
  78. package/dist/core/server/helpers/index.js +9 -0
  79. package/dist/core/server/schemas/artifacts/agentSchema.d.ts +4565 -0
  80. package/dist/core/server/schemas/artifacts/agentSchema.js +51 -0
  81. package/dist/core/server/schemas/artifacts/artifacts.d.ts +4920 -0
  82. package/dist/core/server/schemas/artifacts/artifacts.js +21 -0
  83. package/dist/core/server/schemas/artifacts/controlSchema.d.ts +23 -0
  84. package/dist/core/server/schemas/artifacts/controlSchema.js +18 -0
  85. package/dist/core/server/schemas/artifacts/identityLookupSchema.d.ts +32 -0
  86. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +21 -0
  87. package/dist/core/server/schemas/artifacts/transporterSchema.d.ts +553 -0
  88. package/dist/core/server/schemas/artifacts/transporterSchema.js +60 -0
  89. package/dist/core/server/schemas/btpsDocsSchema.d.ts +4519 -0
  90. package/dist/core/server/schemas/btpsDocsSchema.js +272 -0
  91. package/dist/core/server/schemas/helpers.d.ts +1612 -0
  92. package/dist/core/server/schemas/helpers.js +87 -0
  93. package/dist/core/server/schemas/responseSchema.d.ts +6918 -0
  94. package/dist/core/server/schemas/responseSchema.js +86 -0
  95. package/dist/core/server/schemas/schema.d.ts +4916 -0
  96. package/dist/core/server/schemas/schema.js +70 -0
  97. package/dist/core/server/schemas/shared.d.ts +21 -0
  98. package/dist/core/server/schemas/shared.js +18 -0
  99. package/dist/core/server/types.d.ts +172 -0
  100. package/dist/core/server/types.js +7 -0
  101. package/dist/core/storage/AbstractIdentityStore.d.ts +17 -0
  102. package/dist/core/storage/AbstractIdentityStore.js +13 -0
  103. package/dist/core/storage/AbstractStorageStore.d.ts +16 -0
  104. package/dist/core/storage/AbstractStorageStore.js +17 -0
  105. package/dist/core/storage/JsonIdentityStore.d.ts +29 -0
  106. package/dist/core/storage/JsonIdentityStore.js +39 -0
  107. package/dist/core/storage/JsonStorageStore.d.ts +59 -0
  108. package/dist/core/storage/JsonStorageStore.js +110 -0
  109. package/dist/core/storage/index.d.ts +11 -0
  110. package/dist/core/storage/index.js +18 -0
  111. package/dist/core/storage/types.d.ts +28 -0
  112. package/dist/core/storage/types.js +7 -0
  113. package/dist/core/trust/index.d.ts +10 -0
  114. package/dist/core/trust/index.js +15 -0
  115. package/dist/core/trust/storage/AbstractTrustStore.d.ts +23 -0
  116. package/dist/core/trust/storage/AbstractTrustStore.js +13 -0
  117. package/dist/core/trust/storage/JsonTrustStore.d.ts +33 -0
  118. package/dist/core/trust/storage/JsonTrustStore.js +42 -0
  119. package/dist/core/trust/trustUtils.d.ts +78 -0
  120. package/dist/core/trust/trustUtils.js +41 -0
  121. package/dist/core/trust/types.d.ts +53 -0
  122. package/dist/core/trust/types.js +7 -0
  123. package/dist/core/utils/identity.d.ts +20 -0
  124. package/dist/core/utils/identity.js +22 -0
  125. package/dist/core/utils/index.d.ts +70 -0
  126. package/dist/core/utils/index.js +124 -0
  127. package/dist/core/utils/types.d.ts +10 -0
  128. package/dist/core/utils/types.js +7 -0
  129. package/dist/core/utils/validation.d.ts +14 -0
  130. package/dist/core/utils/validation.js +13 -0
  131. package/dist/index.d.ts +7 -0
  132. package/dist/index.js +8 -0
  133. package/dist/server/btpsServer.d.ts +292 -0
  134. package/dist/server/btpsServer.js +827 -0
  135. package/dist/server/index.d.ts +11 -0
  136. package/dist/server/index.js +15 -0
  137. package/dist/server/libs/abstractRateLimiter.d.ts +10 -0
  138. package/dist/server/libs/abstractRateLimiter.js +15 -0
  139. package/dist/server/libs/artifactSizeGuard.d.ts +27 -0
  140. package/dist/server/libs/artifactSizeGuard.js +44 -0
  141. package/dist/server/libs/artifactTimeWindow.d.ts +24 -0
  142. package/dist/server/libs/artifactTimeWindow.js +30 -0
  143. package/dist/server/libs/btpsFactory.d.ts +29 -0
  144. package/dist/server/libs/btpsFactory.js +49 -0
  145. package/dist/server/libs/btpsLightweightFactory.d.ts +35 -0
  146. package/dist/server/libs/btpsLightweightFactory.js +37 -0
  147. package/dist/server/libs/btpsRegistry.d.ts +14 -0
  148. package/dist/server/libs/btpsRegistry.js +16 -0
  149. package/dist/server/libs/btpsSimpleMetricsTracker.d.ts +13 -0
  150. package/dist/server/libs/btpsSimpleMetricsTracker.js +21 -0
  151. package/dist/server/libs/btpsSimpleRateLimiter.d.ts +28 -0
  152. package/dist/server/libs/btpsSimpleRateLimiter.js +46 -0
  153. package/dist/server/libs/connectionTimeout.d.ts +16 -0
  154. package/dist/server/libs/connectionTimeout.js +14 -0
  155. package/dist/server/libs/defaultMiddleware.d.ts +8 -0
  156. package/dist/server/libs/defaultMiddleware.js +128 -0
  157. package/dist/server/libs/inFlightLimit.d.ts +18 -0
  158. package/dist/server/libs/inFlightLimit.js +17 -0
  159. package/dist/server/libs/index.d.ts +18 -0
  160. package/dist/server/libs/index.js +34 -0
  161. package/dist/server/libs/middlewareManager.d.ts +59 -0
  162. package/dist/server/libs/middlewareManager.js +126 -0
  163. package/dist/server/libs/type.d.ts +22 -0
  164. package/dist/server/libs/type.js +7 -0
  165. package/dist/server/types.d.ts +236 -0
  166. package/dist/server/types.js +7 -0
  167. package/package.json +126 -4
@@ -0,0 +1,15 @@
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 { default as default2 } from "./storage/JsonTrustStore.js";
9
+ import { AbstractTrustStore } from "./storage/AbstractTrustStore.js";
10
+ export * from "./types.js";
11
+ export * from "./trustUtils.js";
12
+ export {
13
+ AbstractTrustStore,
14
+ default2 as JsonTrustStore
15
+ };
@@ -0,0 +1,23 @@
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 { AbstractStorageStore } from '../../storage/AbstractStorageStore.js';
8
+ import { BTPTrustRecord } from '../types.js';
9
+ export declare abstract class AbstractTrustStore<T extends BTPTrustRecord> extends AbstractStorageStore<T> {
10
+ abstract getAll(receiverId?: string): Promise<T[]>;
11
+ /**
12
+ * Whether an artifact with this id passed between these two identities, in
13
+ * either direction, as the platform recorded it. Every `BTPS_EVENT` names
14
+ * the artifact that delivered its invoice (`relatesTo`) and is refused
15
+ * unless this answers true, so a sender cannot send events about invoices
16
+ * that were never exchanged.
17
+ */
18
+ abstract isKnownArtifact(query: {
19
+ artifactId: string;
20
+ from: string;
21
+ to: string;
22
+ }): Promise<boolean>;
23
+ }
@@ -0,0 +1,13 @@
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 { AbstractStorageStore } from "../../storage/AbstractStorageStore.js";
9
+ class AbstractTrustStore extends AbstractStorageStore {
10
+ }
11
+ export {
12
+ AbstractTrustStore
13
+ };
@@ -0,0 +1,33 @@
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 { BTPTrustRecord } from '../types.js';
8
+ import { AbstractTrustStore } from '../index.js';
9
+ import { StorageStoreOptions } from '../../storage/types.js';
10
+ import { JsonStorageStore } from '../../storage/JsonStorageStore.js';
11
+ /**
12
+ * JSON-based TrustStore for self-hosted environments.
13
+ * Uses a Map internally for fast lookup and persists trust records to a single JSON file.
14
+ * Supports multi-tenant BTPS inboxes by indexing records by to Identity + from Identity.
15
+ */
16
+ declare class JsonTrustStore extends JsonStorageStore<BTPTrustRecord> implements AbstractTrustStore<BTPTrustRecord> {
17
+ constructor(options: StorageStoreOptions);
18
+ /**
19
+ * Creates a new trust record. Fails if one already exists for to/from.
20
+ */
21
+ create(record: Omit<BTPTrustRecord, 'id'>, computedId?: string): Promise<BTPTrustRecord>;
22
+ /**
23
+ * Returns all trust records, optionally filtered by to.
24
+ */
25
+ getAll(receiverId?: string): Promise<BTPTrustRecord[]>;
26
+ /**
27
+ * This store keeps trust records only, not artifacts, so it knows of none
28
+ * and a server using it as is accepts no `BTPS_EVENT`. To accept events,
29
+ * extend it and answer from wherever the platform keeps delivered artifacts.
30
+ */
31
+ isKnownArtifact(): Promise<boolean>;
32
+ }
33
+ export default JsonTrustStore;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+
8
+ import { computeTrustId } from "../index.js";
9
+ import { BTPErrorException } from "../../error/index.js";
10
+ import { JsonStorageStore } from "../../storage/JsonStorageStore.js";
11
+ class JsonTrustStore extends JsonStorageStore {
12
+ constructor(options) {
13
+ super(options);
14
+ }
15
+ async create(record, computedId) {
16
+ if ("id" in record)
17
+ throw new BTPErrorException({
18
+ code: "INVALID_CONFIG",
19
+ message: "Record passed to create() must not include an id"
20
+ });
21
+ const id = computedId ?? computeTrustId(record.senderId, record.receiverId);
22
+ if (await this.getById(id))
23
+ throw new BTPErrorException({
24
+ code: "INVALID_CONFIG",
25
+ message: `Record already exists for ${record.senderId} \u2192 ${record.receiverId}`
26
+ });
27
+ const newRecord = { id, ...record };
28
+ return this.recordMap.set(id, newRecord), this.dirty = !0, this.writeDebounced(), newRecord;
29
+ }
30
+ async getAll(receiverId) {
31
+ this.loaded || await this.init(), await this.reloadIfChanged();
32
+ const all = [...this.recordMap.values()];
33
+ return receiverId ? all.filter((r) => r.receiverId === receiverId) : all;
34
+ }
35
+ async isKnownArtifact() {
36
+ return !1;
37
+ }
38
+ }
39
+ var JsonTrustStore_default = JsonTrustStore;
40
+ export {
41
+ JsonTrustStore_default as default
42
+ };
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ import { BTPErrorException } from '../error/index.js';
8
+ import { BTPTrustRecord } from './types.js';
9
+ import { AbstractTrustStore } from './storage/AbstractTrustStore.js';
10
+ /**
11
+ * Checks if a trust record is active.
12
+ * Used in for artifact type other than TRUST_RES and TRUST_REQ
13
+ * only allow message to be sent if trust record is active
14
+ * @param trust - The trust record to check
15
+ * @returns True if the trust record is active, false otherwise
16
+ */
17
+ export declare const isTrustActive: (trust?: BTPTrustRecord) => boolean;
18
+ /**
19
+ * Validates a trust request.
20
+ * Used in for artifact type TRUST_REQ
21
+ * only allow message to be sent if trust record is not active
22
+ * considers blocked and retryAfterDate as one can send new trust request after the retryAfterDate
23
+ * @param trust - The trust record to check
24
+ * @returns Object indicating validity and optional BTPS error
25
+ */
26
+ export declare const validateTrustRequest: (trust?: BTPTrustRecord) => {
27
+ isValid: boolean;
28
+ error?: BTPErrorException;
29
+ };
30
+ /**
31
+ * Computes a globally unique, deterministic trust ID
32
+ * for a given `from` and `to` identity pair using SHA-256.
33
+ *
34
+ * This ID is:
35
+ * - Directional: `from:to` ≠ `to:from`
36
+ * - Collision-resistant: suitable for billions of records
37
+ * - Index-safe: 64-character hex string for database keys
38
+ * - Human-debuggable: logs clearly as a hash
39
+ *
40
+ * @param from - Sender identity (e.g. "finance$company.com")
41
+ * @param to - Receiver identity (e.g. "billing$vendor.org")
42
+ * @returns 64-character hexadecimal SHA-256 hash of "from:to"
43
+ */
44
+ export declare function computeTrustId(senderId: string, receiverId: string): string;
45
+ /**
46
+ * The trust record id of a device (agent) registered for an identity. Device
47
+ * records share the trust store with the records between two identities, so
48
+ * their ids carry an `agent:` prefix that no identity can have (an identity has
49
+ * no `:`): a lookup for a device can never find a record between two
50
+ * identities, whatever `agentId` it is given.
51
+ *
52
+ * @param agentId - The device's agent id, as `createAgent` issued it
53
+ * @param identity - The identity the device is registered for
54
+ */
55
+ export declare function computeAgentTrustId(agentId: string, identity: string): string;
56
+ /**
57
+ * Validates a TRUST_RES by checking if the response is authorized.
58
+ * Ensures that only the original receiver of a trust request is allowed to respond.
59
+ *
60
+ * @param senderId - The identity sending the trust response (e.g., userB$domain)
61
+ * @param receiverId - The identity receiving the trust response (e.g., userA$domain)
62
+ * @param trustStore - The TrustStore instance
63
+ * @returns Object indicating validity and optional BTPS error
64
+ */
65
+ export declare function validateTrustResponse(senderId: string, // The responder
66
+ receiverId: string, // The original requester
67
+ trustStore: AbstractTrustStore<BTPTrustRecord>): Promise<{
68
+ isValid: boolean;
69
+ error?: BTPErrorException;
70
+ }>;
71
+ /**
72
+ * Determines whether a trust request can be retried.
73
+ * Applies to previously rejected, revoked, or pending trusts.
74
+ *
75
+ * @param trust - The trust record to check
76
+ * @returns True if retry is allowed, false otherwise
77
+ */
78
+ export declare function canRetryTrust(trust?: BTPTrustRecord): boolean;
@@ -0,0 +1,41 @@
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 { createHash } from "crypto";
9
+ import {
10
+ BTP_ERROR_TRUST_ALREADY_ACTIVE,
11
+ BTP_ERROR_TRUST_BLOCKED,
12
+ BTP_ERROR_TRUST_NOT_ALLOWED,
13
+ BTPErrorException
14
+ } from "../error/index.js";
15
+ import isEmpty from "lodash/isEmpty.js";
16
+ const isTrustActive = (trust) => !(isEmpty(trust) || trust.status !== "accepted" || trust.expiresAt && new Date(trust.expiresAt).getTime() < Date.now()), validateTrustRequest = (trust) => isTrustActive(trust) ? { isValid: !1, error: new BTPErrorException(BTP_ERROR_TRUST_ALREADY_ACTIVE) } : trust?.status === "blocked" ? { isValid: !1, error: new BTPErrorException(BTP_ERROR_TRUST_BLOCKED) } : trust?.retryAfterDate && new Date(trust.retryAfterDate).getTime() > Date.now() ? { isValid: !1, error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED) } : { isValid: !0, error: void 0 };
17
+ function computeTrustId(senderId, receiverId) {
18
+ const input = `${senderId}:${receiverId}`.toLowerCase();
19
+ return createHash("sha256").update(input).digest("hex");
20
+ }
21
+ function computeAgentTrustId(agentId, identity) {
22
+ return computeTrustId(`agent:${agentId}`, identity);
23
+ }
24
+ async function validateTrustResponse(senderId, receiverId, trustStore) {
25
+ const flippedId = computeTrustId(receiverId, senderId), trustRecord = await trustStore.getById(flippedId), buildError = (cause) => ({
26
+ isValid: !1,
27
+ error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED, { cause })
28
+ });
29
+ return trustRecord ? trustRecord.status !== "pending" ? buildError(`Trust request from ${receiverId} to ${senderId} is not pending`) : trustRecord.receiverId !== senderId ? buildError(`Only ${trustRecord.receiverId} can respond to this trust request`) : { isValid: !0 } : buildError(`No pending trust request found from ${receiverId} to ${senderId}`);
30
+ }
31
+ function canRetryTrust(trust) {
32
+ return isEmpty(trust) ? !0 : trust.status === "accepted" || trust.status === "blocked" ? !1 : trust.retryAfterDate ? new Date(trust.retryAfterDate).getTime() <= Date.now() : !0;
33
+ }
34
+ export {
35
+ canRetryTrust,
36
+ computeAgentTrustId,
37
+ computeTrustId,
38
+ isTrustActive,
39
+ validateTrustRequest,
40
+ validateTrustResponse
41
+ };
@@ -0,0 +1,53 @@
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 { BTPStorageRecord } from '../storage/types.js';
8
+ export type BTPTrustStatus = 'accepted' | 'rejected' | 'revoked' | 'pending' | 'blocked';
9
+ export type BTPTrustDecisionType = Exclude<BTPTrustStatus, 'pending'>;
10
+ export type BTPEncryptionType = 'unencrypted' | 'encrypted' | 'mixed';
11
+ export type KeyHistory = {
12
+ fingerprint: string;
13
+ firstSeen: string;
14
+ lastSeen: string;
15
+ };
16
+ export type BTPTrustRecord = Omit<BTPStorageRecord, 'updatedAt'> & {
17
+ senderId: string;
18
+ receiverId: string;
19
+ status: BTPTrustStatus;
20
+ decidedBy: string;
21
+ decidedAt: string;
22
+ expiresAt?: string;
23
+ publicKeyBase64: string;
24
+ publicKeyFingerprint: string;
25
+ keyHistory: KeyHistory[];
26
+ privacyType: BTPEncryptionType;
27
+ retryAfterDate?: string;
28
+ metadata?: Record<string, unknown>;
29
+ };
30
+ export interface BTPTrustReqDoc {
31
+ id: string;
32
+ name: string;
33
+ email: string;
34
+ reason: string;
35
+ phone: string;
36
+ address?: string;
37
+ logoUrl?: string;
38
+ displayName?: string;
39
+ websiteUrl?: string;
40
+ message?: string;
41
+ expiresAt?: string;
42
+ privacyType?: BTPEncryptionType;
43
+ }
44
+ export interface BTPTrustResDoc {
45
+ id: string;
46
+ decision: BTPTrustDecisionType;
47
+ decidedAt: string;
48
+ decidedBy: string;
49
+ expiresAt?: string;
50
+ retryAfterDate?: string;
51
+ message?: string;
52
+ privacyType?: BTPEncryptionType;
53
+ }
@@ -0,0 +1,7 @@
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
+
@@ -0,0 +1,20 @@
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 { ParsedIdentity } from './types.js';
8
+ /**
9
+ * Splits an identity into its account and domain: `account$domain`. The one
10
+ * place the address rule lives, so every check that needs it uses this.
11
+ *
12
+ * An identity has exactly one separator. The account is letters, digits, `.`,
13
+ * `_` and `-`; the domain follows DNS's rules, with at least two labels. So
14
+ * no character can look like another (a Cyrillic `і` for an `i`), and no `:`
15
+ * can appear: a trust id is a hash of `from:to`, and a device's record id
16
+ * carries an `agent:` prefix that no identity can then imitate. Letters
17
+ * compare without case, as in DNS and in trust ids.
18
+ */
19
+ export declare const parseIdentity: (identity: string) => ParsedIdentity | null;
20
+ export declare const isValidIdentity: (identity?: string) => boolean;
@@ -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
+
8
+ const ACCOUNT = /^[a-z0-9._-]{1,64}$/, DOMAIN_LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/, parseIdentity = (identity) => {
9
+ const parts = identity.split("$");
10
+ if (parts.length !== 2) return null;
11
+ const [accountName, domainName] = parts;
12
+ if (!ACCOUNT.test(accountName.toLowerCase())) return null;
13
+ const labels = domainName.toLowerCase().split(".");
14
+ return domainName.length > 253 || labels.length < 2 || !labels.every((label) => DOMAIN_LABEL.test(label)) ? null : {
15
+ accountName,
16
+ domainName
17
+ };
18
+ }, isValidIdentity = (identity = "") => !!parseIdentity(identity);
19
+ export {
20
+ isValidIdentity,
21
+ parseIdentity
22
+ };
@@ -0,0 +1,70 @@
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 { BTPControlArtifact, BTPAgentArtifact, BTPIdentityLookupRequest, BTPTransporterArtifact } from '../../server/index.js';
8
+ export * from './types.js';
9
+ import { parseIdentity, isValidIdentity } from './identity.js';
10
+ export { parseIdentity, isValidIdentity };
11
+ export declare function pemToBase64(pem: string): string;
12
+ export declare function base64ToPem(base64: string): string;
13
+ export declare const getHostAndSelector: (identity: string) => Promise<{
14
+ version: string;
15
+ host: string;
16
+ selector: string;
17
+ operator?: string;
18
+ } | undefined>;
19
+ export declare const getDnsIdentityParts: (identity: string, selector: string, type?: "key" | "pem" | "version") => Promise<{
20
+ key: string;
21
+ version: string;
22
+ pem: string;
23
+ } | string | undefined>;
24
+ export declare const getBtpAddressParts: (input: string) => URL | null;
25
+ export declare const resolvePublicKey: (identity: string, selector: string) => Promise<string | undefined>;
26
+ /**
27
+ * Checks if the artifact is a BTP transport artifact
28
+ * @param artifact - The artifact to check
29
+ * @returns True if the artifact is a BTP transport artifact, false otherwise
30
+ */
31
+ export declare const isBtpsTransportArtifact: (artifact: unknown) => artifact is BTPTransporterArtifact;
32
+ export declare const isBtpsAgentArtifact: (artifact: unknown) => artifact is BTPAgentArtifact;
33
+ /**
34
+ * Checks if the artifact is a BTP control artifact
35
+ * @param artifact - The artifact to check
36
+ * @returns True if the artifact is a BTP control artifact, false otherwise
37
+ */
38
+ export declare const isBtpsControlArtifact: (artifact: unknown) => artifact is BTPControlArtifact;
39
+ /**
40
+ * Checks if the artifact is a BTP identity request
41
+ * @param artifact - The artifact to check
42
+ * @returns True if the artifact is a BTP identity request, false otherwise
43
+ */
44
+ export declare const isBtpsIdentityRequest: (artifact: unknown) => artifact is BTPIdentityLookupRequest;
45
+ /**
46
+ * Computes a globally unique, deterministic ID
47
+ * for a given `from` and `to` identity pair using SHA-256.
48
+ *
49
+ * This ID is:
50
+ * - Collision-resistant: suitable for billions of records
51
+ * - Index-safe: 64-character hex string for database keys
52
+ * - Human-debuggable: logs clearly as a hash
53
+ *
54
+ * @param identity - Identity (e.g. "finance$company.com")
55
+ * @returns 64-character hexadecimal SHA-256 hash of "identity"
56
+ */
57
+ export declare function computeId(identity: string): string;
58
+ /**
59
+ * Checks if the artifact can be delegated
60
+ * @param artifact - The artifact to check
61
+ * @param operator - The identity operating the sender's domain (`op` in its `_btps.host` record)
62
+ * @returns True if the artifact can be delegated, false otherwise
63
+ * @condition for delegation:
64
+ * - The artifact must have a delegation, a from and a delegation signedBy
65
+ * - signedBy is the sender itself, as for a custom domain like `alice$alice.com`
66
+ * (an attestation by the operator is then required), or
67
+ * - signedBy is the operator of the sender's domain. Being on the same domain is
68
+ * not enough: on a shared domain every user can hold a key of their own.
69
+ */
70
+ export declare const isDelegationAllowed: (artifact: BTPTransporterArtifact, operator?: string) => boolean;
@@ -0,0 +1,124 @@
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 { resolveTxt } from "dns/promises";
9
+ import {
10
+ BTPS_DNS_HOST_NAME_SPACE,
11
+ BTPS_DNS_IDENTITY_NAME_SPACE
12
+ } from "../server/constants/btps-protocol.js";
13
+ import { createHash } from "crypto";
14
+ import { transformToBTPErrorException } from "../error/index.js";
15
+ export * from "./types.js";
16
+ import { parseIdentity, isValidIdentity } from "./identity.js";
17
+ function pemToBase64(pem) {
18
+ return pem.replace(/-----BEGIN PUBLIC KEY-----/, "").replace(/-----END PUBLIC KEY-----/, "").replace(/\r?\n/g, "").trim();
19
+ }
20
+ function base64ToPem(base64) {
21
+ return ["-----BEGIN PUBLIC KEY-----", ...base64.match(/.{1,64}/g) || [], "-----END PUBLIC KEY-----"].join(`
22
+ `);
23
+ }
24
+ const parseBtpsTxtRecord = (txtRecords) => {
25
+ const flat = txtRecords.map((r) => r.join("")).join("");
26
+ return Object.fromEntries(
27
+ flat.split(";").map((field) => {
28
+ const at = field.indexOf("=");
29
+ return at === -1 ? [] : [field.slice(0, at).trim(), field.slice(at + 1).trim()];
30
+ }).filter((pair) => pair.length === 2 && pair[0] !== "")
31
+ );
32
+ }, resolveBtpsTxt = async (dnsName) => {
33
+ try {
34
+ return await resolveTxt(dnsName);
35
+ } catch (error) {
36
+ const code = error?.code;
37
+ if (code === "ENOTFOUND" || code === "ENODATA") return [];
38
+ throw transformToBTPErrorException(error);
39
+ }
40
+ }, getHostAndSelector = async (identity) => {
41
+ const parsedIdentity = parseIdentity(identity);
42
+ if (!parsedIdentity)
43
+ return;
44
+ const dnsName = `${BTPS_DNS_HOST_NAME_SPACE}.${parsedIdentity.domainName}`, txtRecords = await resolveBtpsTxt(dnsName);
45
+ if (!txtRecords.length)
46
+ return;
47
+ const parts = parseBtpsTxtRecord(txtRecords);
48
+ if (!parts.v || !parts.u || !parts.s) return;
49
+ const operator = parts.op;
50
+ return {
51
+ version: parts.v,
52
+ host: parts.u,
53
+ selector: parts.s,
54
+ ...operator && isValidIdentity(operator) ? { operator } : {}
55
+ };
56
+ }, getDnsIdentityParts = async (identity, selector, type) => {
57
+ const typeMap = {
58
+ key: "k",
59
+ version: "v",
60
+ pem: "p"
61
+ }, parsedIdentity = parseIdentity(identity);
62
+ if (!parsedIdentity)
63
+ return;
64
+ const { accountName, domainName } = parsedIdentity, dnsName = `${selector}.${BTPS_DNS_IDENTITY_NAME_SPACE}.${accountName}.${domainName}`, txtRecords = await resolveBtpsTxt(dnsName);
65
+ if (!txtRecords.length)
66
+ return;
67
+ const parts = parseBtpsTxtRecord(txtRecords);
68
+ return type ? type === "pem" ? base64ToPem(parts.p) : parts[typeMap[type]] : {
69
+ key: parts.k,
70
+ version: parts.v,
71
+ pem: base64ToPem(parts.p)
72
+ };
73
+ }, getBtpAddressParts = (input) => {
74
+ try {
75
+ const normalized = input.startsWith("btps://") ? input : `btps://${input}`;
76
+ return new URL(normalized);
77
+ } catch {
78
+ return null;
79
+ }
80
+ }, resolvePublicKey = async (identity, selector) => await getDnsIdentityParts(identity, selector, "pem"), isBtpsTransportArtifact = (artifact) => {
81
+ if (typeof artifact != "object" || artifact === null)
82
+ return !1;
83
+ const maybe = artifact;
84
+ return typeof maybe.from == "string" && typeof maybe.type == "string" && !("agentId" in maybe);
85
+ }, isBtpsAgentArtifact = (artifact) => {
86
+ if (typeof artifact != "object" || artifact === null)
87
+ return !1;
88
+ const maybe = artifact;
89
+ return typeof maybe.to == "string" && typeof maybe.action == "string" && "agentId" in maybe && "signature" in maybe;
90
+ }, isBtpsControlArtifact = (artifact) => {
91
+ if (typeof artifact != "object" || artifact === null)
92
+ return !1;
93
+ const maybe = artifact;
94
+ return typeof maybe.action == "string" && !("agentId" in maybe) && !("document" in maybe) && !("signature" in maybe) && !("to" in maybe);
95
+ }, isBtpsIdentityRequest = (artifact) => {
96
+ if (typeof artifact != "object" || artifact === null)
97
+ return !1;
98
+ const maybe = artifact;
99
+ return typeof maybe.identity == "string" && typeof maybe.hostSelector == "string" && !("signature" in maybe) && !("document" in maybe) && !("to" in maybe);
100
+ };
101
+ function computeId(identity) {
102
+ const input = identity.toLowerCase();
103
+ return createHash("sha256").update(input).digest("hex");
104
+ }
105
+ const isDelegationAllowed = (artifact, operator) => {
106
+ const { delegation, from } = artifact || {}, signedBy = delegation?.signedBy;
107
+ return !from || !signedBy || !parseIdentity(from) || !parseIdentity(signedBy) ? !1 : from === signedBy || !!operator && signedBy === operator;
108
+ };
109
+ export {
110
+ base64ToPem,
111
+ computeId,
112
+ getBtpAddressParts,
113
+ getDnsIdentityParts,
114
+ getHostAndSelector,
115
+ isBtpsAgentArtifact,
116
+ isBtpsControlArtifact,
117
+ isBtpsIdentityRequest,
118
+ isBtpsTransportArtifact,
119
+ isDelegationAllowed,
120
+ isValidIdentity,
121
+ parseIdentity,
122
+ pemToBase64,
123
+ resolvePublicKey
124
+ };
@@ -0,0 +1,10 @@
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 type ParsedIdentity = {
8
+ accountName: string;
9
+ domainName: string;
10
+ };
@@ -0,0 +1,7 @@
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
+
@@ -0,0 +1,14 @@
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 { z, ZodError } from 'zod';
8
+ export declare function validate<T>(schema: z.ZodSchema<T>, data: unknown): {
9
+ success: true;
10
+ data: T;
11
+ } | {
12
+ success: false;
13
+ error: ZodError;
14
+ };
@@ -0,0 +1,13 @@
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
+ function validate(schema, data) {
9
+ return schema.safeParse(data);
10
+ }
11
+ export {
12
+ validate
13
+ };
@@ -0,0 +1,7 @@
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 './core/utils/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
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 "./core/utils/index.js";