@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.
Files changed (155) hide show
  1. package/CHANGELOG.md +171 -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/index.d.ts +11 -0
  12. package/dist/client/constants/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.js +56 -0
  16. package/dist/client/libs/timeouts.d.ts +22 -0
  17. package/dist/client/libs/timeouts.js +19 -0
  18. package/dist/client/types/index.d.ts +155 -0
  19. package/dist/client/types/index.js +7 -0
  20. package/dist/core/authentication/BtpsAuthentication.d.ts +128 -0
  21. package/dist/core/authentication/BtpsAuthentication.js +293 -0
  22. package/dist/core/authentication/index.d.ts +11 -0
  23. package/dist/core/authentication/index.js +12 -0
  24. package/dist/core/authentication/keyProof.d.ts +18 -0
  25. package/dist/core/authentication/keyProof.js +16 -0
  26. package/dist/core/authentication/storage/InMemoryAuthSessionStore.d.ts +55 -0
  27. package/dist/core/authentication/storage/InMemoryAuthSessionStore.js +62 -0
  28. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +63 -0
  29. package/dist/core/authentication/storage/InMemoryTokenStore.js +63 -0
  30. package/dist/core/authentication/types.d.ts +135 -0
  31. package/dist/core/authentication/types.js +7 -0
  32. package/dist/core/crypto/decryptVerify.d.ts +9 -0
  33. package/dist/core/crypto/decryptVerify.js +45 -0
  34. package/dist/core/crypto/decrypter-interface.d.ts +25 -0
  35. package/dist/core/crypto/decrypter-interface.js +7 -0
  36. package/dist/core/crypto/index.d.ts +77 -0
  37. package/dist/core/crypto/index.js +210 -0
  38. package/dist/core/crypto/jcs.d.ts +28 -0
  39. package/dist/core/crypto/jcs.js +60 -0
  40. package/dist/core/crypto/keygen.d.ts +9 -0
  41. package/dist/core/crypto/keygen.js +35 -0
  42. package/dist/core/crypto/pem-decrypter.d.ts +26 -0
  43. package/dist/core/crypto/pem-decrypter.js +52 -0
  44. package/dist/core/crypto/pem-signer.d.ts +21 -0
  45. package/dist/core/crypto/pem-signer.js +34 -0
  46. package/dist/core/crypto/signEncrypt.d.ts +34 -0
  47. package/dist/core/crypto/signEncrypt.js +75 -0
  48. package/dist/core/crypto/signer-interface.d.ts +22 -0
  49. package/dist/core/crypto/signer-interface.js +7 -0
  50. package/dist/core/crypto/types.d.ts +79 -0
  51. package/dist/core/crypto/types.js +7 -0
  52. package/dist/core/delegation/BtpsDelegator.d.ts +102 -0
  53. package/dist/core/delegation/BtpsDelegator.js +118 -0
  54. package/dist/core/delegation/index.d.ts +7 -0
  55. package/dist/core/delegation/index.js +8 -0
  56. package/dist/core/error/constant.d.ts +66 -0
  57. package/dist/core/error/constant.js +194 -0
  58. package/dist/core/error/index.d.ts +35 -0
  59. package/dist/core/error/index.js +52 -0
  60. package/dist/core/error/types.d.ts +16 -0
  61. package/dist/core/error/types.js +7 -0
  62. package/dist/core/server/constants/btps-protocol.d.ts +17 -0
  63. package/dist/core/server/constants/btps-protocol.js +25 -0
  64. package/dist/core/server/constants/control.d.ts +7 -0
  65. package/dist/core/server/constants/control.js +11 -0
  66. package/dist/core/server/constants/currency.d.ts +7 -0
  67. package/dist/core/server/constants/currency.js +332 -0
  68. package/dist/core/server/constants/index.d.ts +26 -0
  69. package/dist/core/server/constants/index.js +61 -0
  70. package/dist/core/server/constants/limits.d.ts +50 -0
  71. package/dist/core/server/constants/limits.js +50 -0
  72. package/dist/core/server/helpers/BtpsMessageQueue.d.ts +13 -0
  73. package/dist/core/server/helpers/BtpsMessageQueue.js +12 -0
  74. package/dist/core/server/helpers/InMemoryQueue.d.ts +16 -0
  75. package/dist/core/server/helpers/InMemoryQueue.js +35 -0
  76. package/dist/core/server/helpers/index.d.ts +8 -0
  77. package/dist/core/server/helpers/index.js +9 -0
  78. package/dist/core/server/schemas/artifacts/agentSchema.js +51 -0
  79. package/dist/core/server/schemas/artifacts/artifacts.js +21 -0
  80. package/dist/core/server/schemas/artifacts/controlSchema.js +18 -0
  81. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +21 -0
  82. package/dist/core/server/schemas/artifacts/transporterSchema.js +60 -0
  83. package/dist/core/server/schemas/btpsDocsSchema.d.ts +4519 -0
  84. package/dist/core/server/schemas/btpsDocsSchema.js +272 -0
  85. package/dist/core/server/schemas/helpers.js +87 -0
  86. package/dist/core/server/schemas/responseSchema.js +86 -0
  87. package/dist/core/server/schemas/schema.js +70 -0
  88. package/dist/core/server/schemas/shared.js +18 -0
  89. package/dist/core/server/types.d.ts +172 -0
  90. package/dist/core/server/types.js +7 -0
  91. package/dist/core/storage/AbstractIdentityStore.d.ts +17 -0
  92. package/dist/core/storage/AbstractIdentityStore.js +13 -0
  93. package/dist/core/storage/AbstractStorageStore.d.ts +16 -0
  94. package/dist/core/storage/AbstractStorageStore.js +17 -0
  95. package/dist/core/storage/JsonIdentityStore.d.ts +29 -0
  96. package/dist/core/storage/JsonIdentityStore.js +39 -0
  97. package/dist/core/storage/JsonStorageStore.d.ts +59 -0
  98. package/dist/core/storage/JsonStorageStore.js +110 -0
  99. package/dist/core/storage/index.d.ts +11 -0
  100. package/dist/core/storage/index.js +18 -0
  101. package/dist/core/storage/types.d.ts +28 -0
  102. package/dist/core/storage/types.js +7 -0
  103. package/dist/core/trust/index.d.ts +10 -0
  104. package/dist/core/trust/index.js +15 -0
  105. package/dist/core/trust/storage/AbstractTrustStore.d.ts +23 -0
  106. package/dist/core/trust/storage/AbstractTrustStore.js +13 -0
  107. package/dist/core/trust/storage/JsonTrustStore.d.ts +33 -0
  108. package/dist/core/trust/storage/JsonTrustStore.js +42 -0
  109. package/dist/core/trust/trustUtils.d.ts +78 -0
  110. package/dist/core/trust/trustUtils.js +41 -0
  111. package/dist/core/trust/types.d.ts +53 -0
  112. package/dist/core/trust/types.js +7 -0
  113. package/dist/core/utils/identity.d.ts +20 -0
  114. package/dist/core/utils/identity.js +22 -0
  115. package/dist/core/utils/index.d.ts +70 -0
  116. package/dist/core/utils/index.js +124 -0
  117. package/dist/core/utils/types.d.ts +10 -0
  118. package/dist/core/utils/types.js +7 -0
  119. package/dist/core/utils/validation.js +13 -0
  120. package/dist/index.d.ts +7 -0
  121. package/dist/index.js +8 -0
  122. package/dist/server/btpsServer.d.ts +292 -0
  123. package/dist/server/btpsServer.js +827 -0
  124. package/dist/server/index.d.ts +11 -0
  125. package/dist/server/index.js +15 -0
  126. package/dist/server/libs/abstractRateLimiter.d.ts +10 -0
  127. package/dist/server/libs/abstractRateLimiter.js +15 -0
  128. package/dist/server/libs/artifactSizeGuard.d.ts +27 -0
  129. package/dist/server/libs/artifactSizeGuard.js +44 -0
  130. package/dist/server/libs/artifactTimeWindow.d.ts +24 -0
  131. package/dist/server/libs/artifactTimeWindow.js +30 -0
  132. package/dist/server/libs/btpsFactory.d.ts +29 -0
  133. package/dist/server/libs/btpsFactory.js +49 -0
  134. package/dist/server/libs/btpsLightweightFactory.d.ts +35 -0
  135. package/dist/server/libs/btpsLightweightFactory.js +37 -0
  136. package/dist/server/libs/btpsRegistry.d.ts +14 -0
  137. package/dist/server/libs/btpsRegistry.js +16 -0
  138. package/dist/server/libs/btpsSimpleMetricsTracker.d.ts +13 -0
  139. package/dist/server/libs/btpsSimpleMetricsTracker.js +21 -0
  140. package/dist/server/libs/btpsSimpleRateLimiter.d.ts +28 -0
  141. package/dist/server/libs/btpsSimpleRateLimiter.js +46 -0
  142. package/dist/server/libs/connectionTimeout.d.ts +16 -0
  143. package/dist/server/libs/connectionTimeout.js +14 -0
  144. package/dist/server/libs/defaultMiddleware.d.ts +8 -0
  145. package/dist/server/libs/defaultMiddleware.js +128 -0
  146. package/dist/server/libs/inFlightLimit.d.ts +18 -0
  147. package/dist/server/libs/inFlightLimit.js +17 -0
  148. package/dist/server/libs/index.d.ts +18 -0
  149. package/dist/server/libs/index.js +34 -0
  150. package/dist/server/libs/middlewareManager.js +126 -0
  151. package/dist/server/libs/type.d.ts +22 -0
  152. package/dist/server/libs/type.js +7 -0
  153. package/dist/server/types.d.ts +236 -0
  154. package/dist/server/types.js +7 -0
  155. package/package.json +126 -4
@@ -0,0 +1,172 @@
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 { BTPSignature, BTPEncryption } from '../crypto/types.js';
8
+ import { BTPTrustReqDoc, BTPTrustResDoc } from '../trust/types.js';
9
+ import { BTPDocument } from '../../server/types.js';
10
+ import type { z } from 'zod';
11
+ import type { BtpLifecycleEventSchema } from './schemas/btpsDocsSchema.js';
12
+ import { AGENT_ACTIONS, AGENT_ACTIONS_REQUIRING_DOCUMENT, TRANSPORTER_ACTIONS } from './constants/index.js';
13
+ import { CURRENCY_CODES } from './constants/currency.js';
14
+ import { BTPErrorException } from '../error/index.js';
15
+ import { IdentityPubKeyRecord } from '../storage/types.js';
16
+ export type BTPArtifactType = (typeof TRANSPORTER_ACTIONS)[number];
17
+ export type CurrencyCode = (typeof CURRENCY_CODES)[number];
18
+ export type AgentAction = (typeof AGENT_ACTIONS)[number];
19
+ export type AgentActionRequiringDocument = (typeof AGENT_ACTIONS_REQUIRING_DOCUMENT)[number];
20
+ /** A lifecycle event: what a `BTPS_EVENT` carries (paid, partially paid, disputed, refund, response). */
21
+ export type BTPLifecycleEvent = z.infer<typeof BtpLifecycleEventSchema>;
22
+ export type BTPDocType = BTPDocument | BTPLifecycleEvent | BTPTrustReqDoc | BTPTrustResDoc;
23
+ export type BTPAttestation = {
24
+ signedBy: string;
25
+ issuedAt: string;
26
+ signature: BTPSignature;
27
+ selector: string;
28
+ };
29
+ export interface BTPDelegation {
30
+ agentId: string;
31
+ agentPubKey: string;
32
+ signedBy: string;
33
+ signature: BTPSignature;
34
+ issuedAt: string;
35
+ attestation?: BTPAttestation;
36
+ selector: string;
37
+ }
38
+ export interface BTPAuthReqDoc {
39
+ identity: string;
40
+ authToken: string;
41
+ publicKey: string;
42
+ agentInfo?: Record<string, string | string[]>;
43
+ /** On an auth.refresh that moves the device to a new key: that key's signature over keyProofPayload. */
44
+ keyProof?: BTPSignature;
45
+ }
46
+ export interface BTPAuthResDoc {
47
+ agentId: string;
48
+ refreshToken: string;
49
+ expiresAt: string;
50
+ decryptBy: string;
51
+ }
52
+ export interface BTPStringQueryFilter {
53
+ like?: string;
54
+ in?: string[];
55
+ eq?: string;
56
+ ne?: string;
57
+ notIn?: [string];
58
+ notLike?: string;
59
+ }
60
+ export interface BTPAgentQueryDoc {
61
+ title?: BTPStringQueryFilter;
62
+ from?: BTPStringQueryFilter;
63
+ to?: BTPStringQueryFilter;
64
+ }
65
+ export interface BTPAgentQuery {
66
+ since?: string;
67
+ until?: string;
68
+ limit?: number;
69
+ cursor?: string;
70
+ query?: BTPAgentQueryDoc;
71
+ sort?: 'asc' | 'desc';
72
+ }
73
+ export interface BTPAgentMutation {
74
+ id: string;
75
+ document: BTPDocType;
76
+ }
77
+ export interface BTPAgentCreate {
78
+ type: BTPArtifactType;
79
+ document: BTPDocType;
80
+ }
81
+ export interface BTPIdsPayload {
82
+ ids: string[];
83
+ }
84
+ export interface BTPGenericArtifact<T = string> {
85
+ version: string;
86
+ id: string;
87
+ document?: T;
88
+ issuedAt: string;
89
+ to: string;
90
+ signature: BTPSignature;
91
+ }
92
+ export interface BTPControlArtifact extends Omit<BTPGenericArtifact, 'document' | 'signature' | 'to'> {
93
+ action: 'QUIT' | 'PING';
94
+ }
95
+ export interface BTPIdentityLookupRequest extends Omit<BTPGenericArtifact, 'document' | 'signature' | 'to'> {
96
+ identity: string;
97
+ from: string;
98
+ hostSelector: string;
99
+ identitySelector?: string;
100
+ }
101
+ export type BTPAgentDocument = BTPTransporterArtifact | BTPAuthReqDoc | BTPAgentMutation | BTPAgentQuery | BTPIdsPayload | string;
102
+ export interface BTPAgentArtifact extends BTPGenericArtifact<BTPAgentDocument> {
103
+ action: AgentAction;
104
+ agentId: string;
105
+ encryption: BTPEncryption | null;
106
+ }
107
+ export interface BTPTransporterArtifact extends BTPGenericArtifact<BTPDocType | string> {
108
+ document: BTPDocType | string;
109
+ type: BTPArtifactType;
110
+ from: string;
111
+ encryption: BTPEncryption | null;
112
+ delegation?: BTPDelegation;
113
+ selector: string;
114
+ /** On a BTPS_EVENT only: the id of the BTPS_DOC artifact that delivered the invoice it is about. */
115
+ relatesTo?: string;
116
+ }
117
+ export type BTPArtifact = BTPAgentArtifact | BTPTransporterArtifact | BTPIdentityLookupRequest | BTPControlArtifact;
118
+ export type BTPStatus = {
119
+ ok: boolean;
120
+ code: number;
121
+ message?: string;
122
+ /** On an error, its BTPS code, e.g. 'BTP_ERROR_TRUST_EXPIRED' */
123
+ error?: string;
124
+ };
125
+ export interface BTPQueryResultEntry<T = BTPTransporterArtifact | BTPDeliveryFailureArtifact> {
126
+ artifact: T;
127
+ meta?: {
128
+ seen?: boolean;
129
+ seenAt?: string;
130
+ [key: string]: unknown;
131
+ };
132
+ }
133
+ export interface BTPQueryResult<T = BTPTransporterArtifact | BTPDeliveryFailureArtifact> {
134
+ results: BTPQueryResultEntry<T>[];
135
+ cursor?: string;
136
+ total?: number;
137
+ hasNext?: boolean;
138
+ }
139
+ export interface BTPDeliveryFailureDoc {
140
+ id: string;
141
+ reason: string;
142
+ failedAt: string;
143
+ retryCount?: number;
144
+ document?: BTPTransporterArtifact;
145
+ errorLog?: BTPErrorException;
146
+ recipient: string;
147
+ transportArtifactId: string;
148
+ agentArtifactId?: string;
149
+ }
150
+ export interface BTPDeliveryFailureArtifact {
151
+ id: string;
152
+ issuedAt: string;
153
+ document: BTPDeliveryFailureDoc;
154
+ type: 'BTP_DELIVERY_FAILURE';
155
+ from: string;
156
+ to: string;
157
+ }
158
+ export type BTPIdentityResDoc = Omit<IdentityPubKeyRecord, 'createdAt'>;
159
+ export type BTPServerResDocs = BTPAuthResDoc | BTPQueryResult | BTPIdentityResDoc | string;
160
+ export type BTPServerResponse<T = BTPServerResDocs> = {
161
+ version: string;
162
+ status: BTPStatus;
163
+ id: string;
164
+ issuedAt: string;
165
+ type: 'btps_error' | 'btps_response';
166
+ reqId?: string;
167
+ document?: T;
168
+ signature?: BTPSignature;
169
+ encryption?: BTPEncryption;
170
+ signedBy?: string;
171
+ selector?: string;
172
+ };
@@ -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,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
+ import { AbstractStorageStore } from '../storage/AbstractStorageStore.js';
8
+ import { BTPIdentityRecord, IdentityPubKeyRecord } from '../storage/types.js';
9
+ export declare abstract class AbstractIdentityStore<T extends BTPIdentityRecord> extends AbstractStorageStore<T> {
10
+ /**
11
+ * The public key record of an identity at a selector (its current one when not given).
12
+ * @param computedId - The record id the server computes with `computeId(identity)`.
13
+ * Use it as the record id as given; never hash it again. The server computes it
14
+ * so every store keys records the same fixed-length way, however long the identity.
15
+ */
16
+ abstract getPublicKeyRecord(computedId: string, selector?: string): Promise<IdentityPubKeyRecord | undefined>;
17
+ }
@@ -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 AbstractIdentityStore extends AbstractStorageStore {
10
+ }
11
+ export {
12
+ AbstractIdentityStore
13
+ };
@@ -0,0 +1,16 @@
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, StorageStoreOptions } from './types.js';
8
+ export declare abstract class AbstractStorageStore<T extends BTPStorageRecord> {
9
+ protected connection: unknown;
10
+ protected entityName?: string;
11
+ constructor({ connection, entityName }: StorageStoreOptions);
12
+ abstract getById(computedId: string): Promise<T | undefined>;
13
+ abstract create(record: Omit<T, 'id'>, computedId?: string): Promise<T>;
14
+ abstract update(computedId: string, patch: Partial<T>): Promise<T>;
15
+ abstract delete(computedId: string): Promise<void>;
16
+ }
@@ -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
+ class AbstractStorageStore {
9
+ connection;
10
+ entityName;
11
+ constructor({ connection, entityName }) {
12
+ this.connection = connection, this.entityName = entityName;
13
+ }
14
+ }
15
+ export {
16
+ AbstractStorageStore
17
+ };
@@ -0,0 +1,29 @@
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 { BTPIdentityRecord, StorageStoreOptions, IdentityPubKeyRecord } from '../storage/types.js';
8
+ import { JsonStorageStore } from '../storage/JsonStorageStore.js';
9
+ import { AbstractIdentityStore } from './AbstractIdentityStore.js';
10
+ /**
11
+ * JSON-based TrustStore for self-hosted environments.
12
+ * Uses a Map internally for fast lookup and persists trust records to a single JSON file.
13
+ * Supports multi-tenant BTPS inboxes by indexing records by to Identity + from Identity.
14
+ */
15
+ export declare class JsonIdentityStore extends JsonStorageStore<BTPIdentityRecord> implements AbstractIdentityStore<BTPIdentityRecord> {
16
+ constructor(options: StorageStoreOptions);
17
+ /**
18
+ * Creates a new identity record. Fails if one already exists.
19
+ * @param computedId - The record id the server computes (`computeId(identity)`); computed from `record.identity` when not given.
20
+ */
21
+ create(record: Omit<BTPIdentityRecord, 'id'>, computedId?: string): Promise<BTPIdentityRecord>;
22
+ /**
23
+ * Returns the public key for a given identity and selector.
24
+ * @param computedId - The record id the server computes (`computeId(identity)`), used as given.
25
+ * @param selector - The selector to get the public key for.
26
+ * @returns The public key for the given identity and selector.
27
+ */
28
+ getPublicKeyRecord(computedId: string, selector?: string): Promise<IdentityPubKeyRecord | undefined>;
29
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+
8
+ import { BTPErrorException } from "../error/index.js";
9
+ import { JsonStorageStore } from "../storage/JsonStorageStore.js";
10
+ import { computeId } from "../utils/index.js";
11
+ class JsonIdentityStore 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 ?? computeId(record.identity);
22
+ if (await this.getById(id))
23
+ throw new BTPErrorException({
24
+ code: "INVALID_CONFIG",
25
+ message: `Record already exists for ${record.identity}`
26
+ });
27
+ const newRecord = { id, ...record };
28
+ return this.recordMap.set(id, newRecord), this.dirty = !0, this.writeDebounced(), newRecord;
29
+ }
30
+ async getPublicKeyRecord(computedId, selector) {
31
+ const record = await super.getById(computedId);
32
+ if (!record) return;
33
+ const pointer = selector ?? record.currentSelector;
34
+ return record.publicKeys.find((key) => key.selector === pointer);
35
+ }
36
+ }
37
+ export {
38
+ JsonIdentityStore
39
+ };
@@ -0,0 +1,59 @@
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 './AbstractStorageStore.js';
8
+ import { BTPStorageRecord, StorageStoreOptions } from './types.js';
9
+ /**
10
+ * JSON-based StorageStore for self-hosted environments.
11
+ * Uses a Map internally for fast lookup and persists storage records to a single JSON file.
12
+ * Supports multi-tenant BTPS inboxes by indexing records by to Identity + from Identity.
13
+ */
14
+ export declare class JsonStorageStore<T extends BTPStorageRecord> extends AbstractStorageStore<T> {
15
+ protected recordMap: Map<string, BTPStorageRecord>;
16
+ protected dirty: boolean;
17
+ protected filePath: string;
18
+ protected hasEntity: boolean;
19
+ protected writeDebounced: () => void;
20
+ protected lastChangedMtime: number;
21
+ protected loaded: boolean;
22
+ constructor(options: StorageStoreOptions);
23
+ /**
24
+ * checks and reloads if the file has changed externally or manually
25
+ */
26
+ protected reloadIfChanged(): Promise<void>;
27
+ /**
28
+ * Initializes in-memory store from disk. If file is missing, creates a new one.
29
+ */
30
+ protected init(): Promise<void>;
31
+ /**
32
+ * Atomically writes the in-memory storage records to disk using a lock.
33
+ */
34
+ protected writeToFile(): Promise<void>;
35
+ /**
36
+ * Retrieves a record by its ID.
37
+ */
38
+ getById(computedId: string): Promise<T | undefined>;
39
+ /**
40
+ * Creates a new storage record. Fails if one already exists for identity.
41
+ */
42
+ create(record: Omit<T, 'id'>, identity: string): Promise<T>;
43
+ /**
44
+ * Updates an existing storage record by merging with the patch.
45
+ */
46
+ update(computedId: string, patch: Partial<T>): Promise<T>;
47
+ /**
48
+ * Deletes a storage record for a given identity.
49
+ */
50
+ delete(computedId: string): Promise<void>;
51
+ /**
52
+ * Forces immediate disk flush of storage records.
53
+ */
54
+ flushNow(): Promise<void>;
55
+ /**
56
+ * Flushes and reloads storage records from disk.
57
+ */
58
+ flushAndReload(): Promise<void>;
59
+ }
@@ -0,0 +1,110 @@
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 fs from "fs/promises";
9
+ import { existsSync } from "fs";
10
+ import { lock } from "proper-lockfile";
11
+ import debounce from "lodash/debounce.js";
12
+ import isEmpty from "lodash/isEmpty.js";
13
+ import { AbstractStorageStore } from "./AbstractStorageStore.js";
14
+ import { BTPErrorException } from "../error/index.js";
15
+ import { computeId } from "../utils/index.js";
16
+ class JsonStorageStore extends AbstractStorageStore {
17
+ recordMap = new Map();
18
+ dirty = !1;
19
+ filePath;
20
+ hasEntity = !1;
21
+ writeDebounced;
22
+ lastChangedMtime = 0;
23
+
24
+ loaded = !1;
25
+ constructor(options) {
26
+ if (super(options), typeof options.connection != "string")
27
+ throw new BTPErrorException({
28
+ code: "INVALID_CONFIG",
29
+ message: "JSON StorageStore expects a file path as connection"
30
+ });
31
+ this.filePath = options.connection, this.hasEntity = !isEmpty(this.entityName), this.writeDebounced = debounce(() => this.writeToFile(), 1e3), process.on("SIGINT", async () => {
32
+ await this.writeToFile(), process.exit();
33
+ }), process.on("SIGTERM", async () => {
34
+ await this.writeToFile(), process.exit();
35
+ });
36
+ }
37
+ async reloadIfChanged() {
38
+ const mtime = (await fs.stat(this.filePath)).mtimeMs;
39
+ mtime !== this.lastChangedMtime && (await this.flushAndReload(), this.lastChangedMtime = mtime);
40
+ }
41
+ async init() {
42
+ if (!existsSync(this.filePath)) {
43
+ const empty = this.hasEntity ? { [this.entityName]: [] } : [];
44
+ await fs.writeFile(this.filePath, JSON.stringify(empty, null, 2), "utf8");
45
+ }
46
+ const raw = JSON.parse(await fs.readFile(this.filePath, "utf8")), records = this.hasEntity ? raw?.[this.entityName] || [] : raw;
47
+ this.recordMap.clear();
48
+ for (const r of records) {
49
+ const key = r.id;
50
+ this.recordMap.set(key, r);
51
+ }
52
+ this.loaded = !0;
53
+ }
54
+ async writeToFile() {
55
+ if (!this.dirty) return;
56
+ this.dirty = !1;
57
+ let release;
58
+ const tmpPath = this.filePath + ".tmp";
59
+ try {
60
+ release = await lock(this.filePath, {
61
+ retries: { retries: 5, factor: 1.5, minTimeout: 100, maxTimeout: 1e3 },
62
+ stale: 5e3
63
+ });
64
+ const records = [...this.recordMap.values()], contents = this.hasEntity ? { [this.entityName]: records } : records;
65
+ await fs.writeFile(tmpPath, JSON.stringify(contents, null, 2), "utf8"), await fs.rename(tmpPath, this.filePath), this.lastChangedMtime = (await fs.stat(this.filePath)).mtimeMs;
66
+ } finally {
67
+ release && await release();
68
+ }
69
+ }
70
+ async getById(computedId) {
71
+ return this.loaded || await this.init(), await this.reloadIfChanged(), this.recordMap.get(computedId);
72
+ }
73
+ async create(record, identity) {
74
+ if ("id" in record)
75
+ throw new BTPErrorException({
76
+ code: "INVALID_CONFIG",
77
+ message: "Record passed to create() must not include an id"
78
+ });
79
+ const id = computeId(identity);
80
+ if (await this.getById(id))
81
+ throw new BTPErrorException({
82
+ code: "INVALID_CONFIG",
83
+ message: `Record already exists for ${identity}`
84
+ });
85
+ const newRecord = { id, ...record };
86
+ return this.recordMap.set(id, newRecord), this.dirty = !0, this.writeDebounced(), newRecord;
87
+ }
88
+ async update(computedId, patch) {
89
+ const record = await this.getById(computedId);
90
+ if (!record)
91
+ throw new BTPErrorException({
92
+ code: "INVALID_CONFIG",
93
+ message: `No record found for ${computedId}`
94
+ });
95
+ const updated = { ...record, ...patch };
96
+ return this.recordMap.set(computedId, updated), this.dirty = !0, this.writeDebounced(), updated;
97
+ }
98
+ async delete(computedId) {
99
+ this.loaded || await this.init(), this.recordMap.delete(computedId) && (this.dirty = !0, this.writeDebounced());
100
+ }
101
+ async flushNow() {
102
+ await this.writeToFile();
103
+ }
104
+ async flushAndReload() {
105
+ await this.writeToFile(), this.recordMap.clear(), await this.init();
106
+ }
107
+ }
108
+ export {
109
+ JsonStorageStore
110
+ };
@@ -0,0 +1,11 @@
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 { AbstractStorageStore } from './AbstractStorageStore.js';
8
+ export { AbstractIdentityStore } from './AbstractIdentityStore.js';
9
+ export { JsonStorageStore } from './JsonStorageStore.js';
10
+ export { JsonIdentityStore } from './JsonIdentityStore.js';
11
+ export * from './types.js';
@@ -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
+
8
+ import { AbstractStorageStore } from "./AbstractStorageStore.js";
9
+ import { AbstractIdentityStore } from "./AbstractIdentityStore.js";
10
+ import { JsonStorageStore } from "./JsonStorageStore.js";
11
+ import { JsonIdentityStore } from "./JsonIdentityStore.js";
12
+ export * from "./types.js";
13
+ export {
14
+ AbstractIdentityStore,
15
+ AbstractStorageStore,
16
+ JsonIdentityStore,
17
+ JsonStorageStore
18
+ };
@@ -0,0 +1,28 @@
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 BTPStorageRecord {
8
+ id: string;
9
+ createdAt: string;
10
+ updatedAt?: string;
11
+ metadata?: Record<string, unknown>;
12
+ }
13
+ export interface BTPIdentityRecord extends BTPStorageRecord {
14
+ identity: string;
15
+ currentSelector: string;
16
+ publicKeys: IdentityPubKeyRecord[];
17
+ }
18
+ export type IdentityPubKeyRecord = {
19
+ selector: string;
20
+ publicKey: string;
21
+ keyType: 'rsa';
22
+ version: string;
23
+ createdAt: string;
24
+ };
25
+ export interface StorageStoreOptions {
26
+ connection: unknown;
27
+ entityName?: string;
28
+ }
@@ -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,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 { default as JsonTrustStore } from './storage/JsonTrustStore.js';
8
+ export { AbstractTrustStore } from './storage/AbstractTrustStore.js';
9
+ export * from './types.js';
10
+ export * from './trustUtils.js';
@@ -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;