@smythos/sre 1.5.1 → 1.5.4

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 (193) hide show
  1. package/LICENSE +18 -0
  2. package/dist/index.js +22329 -4
  3. package/dist/index.js.map +1 -1
  4. package/dist/types/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.d.ts +2 -2
  5. package/dist/types/subsystems/IO/VectorDB.service/embed/BaseEmbedding.d.ts +11 -7
  6. package/dist/types/types/VectorDB.types.d.ts +13 -11
  7. package/package.json +102 -127
  8. package/src/Components/APICall/APICall.class.ts +155 -0
  9. package/src/Components/APICall/AccessTokenManager.ts +130 -0
  10. package/src/Components/APICall/ArrayBufferResponse.helper.ts +58 -0
  11. package/src/Components/APICall/OAuth.helper.ts +294 -0
  12. package/src/Components/APICall/mimeTypeCategories.ts +46 -0
  13. package/src/Components/APICall/parseData.ts +167 -0
  14. package/src/Components/APICall/parseHeaders.ts +41 -0
  15. package/src/Components/APICall/parseProxy.ts +68 -0
  16. package/src/Components/APICall/parseUrl.ts +91 -0
  17. package/src/Components/APIEndpoint.class.ts +234 -0
  18. package/src/Components/APIOutput.class.ts +58 -0
  19. package/src/Components/AgentPlugin.class.ts +102 -0
  20. package/src/Components/Async.class.ts +155 -0
  21. package/src/Components/Await.class.ts +90 -0
  22. package/src/Components/Classifier.class.ts +158 -0
  23. package/src/Components/Component.class.ts +94 -0
  24. package/src/Components/ComponentHost.class.ts +38 -0
  25. package/src/Components/DataSourceCleaner.class.ts +92 -0
  26. package/src/Components/DataSourceIndexer.class.ts +181 -0
  27. package/src/Components/DataSourceLookup.class.ts +141 -0
  28. package/src/Components/FEncDec.class.ts +29 -0
  29. package/src/Components/FHash.class.ts +33 -0
  30. package/src/Components/FSign.class.ts +80 -0
  31. package/src/Components/FSleep.class.ts +25 -0
  32. package/src/Components/FTimestamp.class.ts +25 -0
  33. package/src/Components/FileStore.class.ts +75 -0
  34. package/src/Components/ForEach.class.ts +97 -0
  35. package/src/Components/GPTPlugin.class.ts +70 -0
  36. package/src/Components/GenAILLM.class.ts +395 -0
  37. package/src/Components/HuggingFace.class.ts +314 -0
  38. package/src/Components/Image/imageSettings.config.ts +70 -0
  39. package/src/Components/ImageGenerator.class.ts +407 -0
  40. package/src/Components/JSONFilter.class.ts +54 -0
  41. package/src/Components/LLMAssistant.class.ts +213 -0
  42. package/src/Components/LogicAND.class.ts +28 -0
  43. package/src/Components/LogicAtLeast.class.ts +85 -0
  44. package/src/Components/LogicAtMost.class.ts +86 -0
  45. package/src/Components/LogicOR.class.ts +29 -0
  46. package/src/Components/LogicXOR.class.ts +34 -0
  47. package/src/Components/MCPClient.class.ts +112 -0
  48. package/src/Components/PromptGenerator.class.ts +122 -0
  49. package/src/Components/ScrapflyWebScrape.class.ts +159 -0
  50. package/src/Components/TavilyWebSearch.class.ts +98 -0
  51. package/src/Components/index.ts +77 -0
  52. package/src/Core/AgentProcess.helper.ts +240 -0
  53. package/src/Core/Connector.class.ts +123 -0
  54. package/src/Core/ConnectorsService.ts +192 -0
  55. package/src/Core/DummyConnector.ts +49 -0
  56. package/src/Core/HookService.ts +105 -0
  57. package/src/Core/SmythRuntime.class.ts +292 -0
  58. package/src/Core/SystemEvents.ts +15 -0
  59. package/src/Core/boot.ts +55 -0
  60. package/src/config.ts +15 -0
  61. package/src/constants.ts +125 -0
  62. package/src/data/hugging-face.params.json +580 -0
  63. package/src/helpers/BinaryInput.helper.ts +324 -0
  64. package/src/helpers/Conversation.helper.ts +1094 -0
  65. package/src/helpers/JsonContent.helper.ts +97 -0
  66. package/src/helpers/LocalCache.helper.ts +97 -0
  67. package/src/helpers/Log.helper.ts +234 -0
  68. package/src/helpers/OpenApiParser.helper.ts +150 -0
  69. package/src/helpers/S3Cache.helper.ts +129 -0
  70. package/src/helpers/SmythURI.helper.ts +5 -0
  71. package/src/helpers/TemplateString.helper.ts +243 -0
  72. package/src/helpers/TypeChecker.helper.ts +329 -0
  73. package/src/index.ts +179 -0
  74. package/src/index.ts.bak +179 -0
  75. package/src/subsystems/AgentManager/Agent.class.ts +1108 -0
  76. package/src/subsystems/AgentManager/Agent.helper.ts +3 -0
  77. package/src/subsystems/AgentManager/AgentData.service/AgentDataConnector.ts +230 -0
  78. package/src/subsystems/AgentManager/AgentData.service/connectors/CLIAgentDataConnector.class.ts +66 -0
  79. package/src/subsystems/AgentManager/AgentData.service/connectors/LocalAgentDataConnector.class.ts +142 -0
  80. package/src/subsystems/AgentManager/AgentData.service/connectors/NullAgentData.class.ts +39 -0
  81. package/src/subsystems/AgentManager/AgentData.service/index.ts +18 -0
  82. package/src/subsystems/AgentManager/AgentLogger.class.ts +297 -0
  83. package/src/subsystems/AgentManager/AgentRequest.class.ts +51 -0
  84. package/src/subsystems/AgentManager/AgentRuntime.class.ts +559 -0
  85. package/src/subsystems/AgentManager/AgentSSE.class.ts +101 -0
  86. package/src/subsystems/AgentManager/AgentSettings.class.ts +52 -0
  87. package/src/subsystems/AgentManager/Component.service/ComponentConnector.ts +32 -0
  88. package/src/subsystems/AgentManager/Component.service/connectors/LocalComponentConnector.class.ts +59 -0
  89. package/src/subsystems/AgentManager/Component.service/index.ts +11 -0
  90. package/src/subsystems/AgentManager/EmbodimentSettings.class.ts +47 -0
  91. package/src/subsystems/AgentManager/ForkedAgent.class.ts +153 -0
  92. package/src/subsystems/AgentManager/OSResourceMonitor.ts +77 -0
  93. package/src/subsystems/ComputeManager/Code.service/CodeConnector.ts +99 -0
  94. package/src/subsystems/ComputeManager/Code.service/connectors/AWSLambdaCode.class.ts +63 -0
  95. package/src/subsystems/ComputeManager/Code.service/index.ts +11 -0
  96. package/src/subsystems/IO/CLI.service/CLIConnector.ts +47 -0
  97. package/src/subsystems/IO/CLI.service/index.ts +9 -0
  98. package/src/subsystems/IO/Log.service/LogConnector.ts +32 -0
  99. package/src/subsystems/IO/Log.service/connectors/ConsoleLog.class.ts +28 -0
  100. package/src/subsystems/IO/Log.service/index.ts +13 -0
  101. package/src/subsystems/IO/NKV.service/NKVConnector.ts +41 -0
  102. package/src/subsystems/IO/NKV.service/connectors/NKVRAM.class.ts +204 -0
  103. package/src/subsystems/IO/NKV.service/connectors/NKVRedis.class.ts +182 -0
  104. package/src/subsystems/IO/NKV.service/index.ts +12 -0
  105. package/src/subsystems/IO/Router.service/RouterConnector.ts +21 -0
  106. package/src/subsystems/IO/Router.service/connectors/ExpressRouter.class.ts +48 -0
  107. package/src/subsystems/IO/Router.service/connectors/NullRouter.class.ts +40 -0
  108. package/src/subsystems/IO/Router.service/index.ts +11 -0
  109. package/src/subsystems/IO/Storage.service/SmythFS.class.ts +472 -0
  110. package/src/subsystems/IO/Storage.service/StorageConnector.ts +66 -0
  111. package/src/subsystems/IO/Storage.service/connectors/LocalStorage.class.ts +305 -0
  112. package/src/subsystems/IO/Storage.service/connectors/S3Storage.class.ts +418 -0
  113. package/src/subsystems/IO/Storage.service/index.ts +13 -0
  114. package/src/subsystems/IO/VectorDB.service/VectorDBConnector.ts +108 -0
  115. package/src/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.ts +454 -0
  116. package/src/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.ts +384 -0
  117. package/src/subsystems/IO/VectorDB.service/connectors/RAMVecrtorDB.class.ts +421 -0
  118. package/src/subsystems/IO/VectorDB.service/embed/BaseEmbedding.ts +107 -0
  119. package/src/subsystems/IO/VectorDB.service/embed/OpenAIEmbedding.ts +109 -0
  120. package/src/subsystems/IO/VectorDB.service/embed/index.ts +21 -0
  121. package/src/subsystems/IO/VectorDB.service/index.ts +14 -0
  122. package/src/subsystems/LLMManager/LLM.helper.ts +221 -0
  123. package/src/subsystems/LLMManager/LLM.inference.ts +335 -0
  124. package/src/subsystems/LLMManager/LLM.service/LLMConnector.ts +375 -0
  125. package/src/subsystems/LLMManager/LLM.service/LLMCredentials.helper.ts +145 -0
  126. package/src/subsystems/LLMManager/LLM.service/connectors/Anthropic.class.ts +632 -0
  127. package/src/subsystems/LLMManager/LLM.service/connectors/Bedrock.class.ts +405 -0
  128. package/src/subsystems/LLMManager/LLM.service/connectors/Echo.class.ts +81 -0
  129. package/src/subsystems/LLMManager/LLM.service/connectors/GoogleAI.class.ts +689 -0
  130. package/src/subsystems/LLMManager/LLM.service/connectors/Groq.class.ts +257 -0
  131. package/src/subsystems/LLMManager/LLM.service/connectors/OpenAI.class.ts +848 -0
  132. package/src/subsystems/LLMManager/LLM.service/connectors/Perplexity.class.ts +255 -0
  133. package/src/subsystems/LLMManager/LLM.service/connectors/VertexAI.class.ts +193 -0
  134. package/src/subsystems/LLMManager/LLM.service/index.ts +43 -0
  135. package/src/subsystems/LLMManager/ModelsProvider.service/ModelsProviderConnector.ts +281 -0
  136. package/src/subsystems/LLMManager/ModelsProvider.service/connectors/SmythModelsProvider.class.ts +229 -0
  137. package/src/subsystems/LLMManager/ModelsProvider.service/index.ts +11 -0
  138. package/src/subsystems/LLMManager/custom-models.ts +854 -0
  139. package/src/subsystems/LLMManager/models.ts +2539 -0
  140. package/src/subsystems/LLMManager/paramMappings.ts +69 -0
  141. package/src/subsystems/MemoryManager/Cache.service/CacheConnector.ts +86 -0
  142. package/src/subsystems/MemoryManager/Cache.service/connectors/LocalStorageCache.class.ts +297 -0
  143. package/src/subsystems/MemoryManager/Cache.service/connectors/RAMCache.class.ts +201 -0
  144. package/src/subsystems/MemoryManager/Cache.service/connectors/RedisCache.class.ts +252 -0
  145. package/src/subsystems/MemoryManager/Cache.service/connectors/S3Cache.class.ts +373 -0
  146. package/src/subsystems/MemoryManager/Cache.service/index.ts +15 -0
  147. package/src/subsystems/MemoryManager/LLMCache.ts +72 -0
  148. package/src/subsystems/MemoryManager/LLMContext.ts +125 -0
  149. package/src/subsystems/MemoryManager/RuntimeContext.ts +249 -0
  150. package/src/subsystems/Security/AccessControl/ACL.class.ts +208 -0
  151. package/src/subsystems/Security/AccessControl/AccessCandidate.class.ts +76 -0
  152. package/src/subsystems/Security/AccessControl/AccessRequest.class.ts +52 -0
  153. package/src/subsystems/Security/Account.service/AccountConnector.ts +41 -0
  154. package/src/subsystems/Security/Account.service/connectors/AWSAccount.class.ts +76 -0
  155. package/src/subsystems/Security/Account.service/connectors/DummyAccount.class.ts +130 -0
  156. package/src/subsystems/Security/Account.service/connectors/JSONFileAccount.class.ts +159 -0
  157. package/src/subsystems/Security/Account.service/index.ts +14 -0
  158. package/src/subsystems/Security/Credentials.helper.ts +62 -0
  159. package/src/subsystems/Security/ManagedVault.service/ManagedVaultConnector.ts +34 -0
  160. package/src/subsystems/Security/ManagedVault.service/connectors/NullManagedVault.class.ts +57 -0
  161. package/src/subsystems/Security/ManagedVault.service/connectors/SecretManagerManagedVault.ts +154 -0
  162. package/src/subsystems/Security/ManagedVault.service/index.ts +12 -0
  163. package/src/subsystems/Security/SecureConnector.class.ts +110 -0
  164. package/src/subsystems/Security/Vault.service/Vault.helper.ts +30 -0
  165. package/src/subsystems/Security/Vault.service/VaultConnector.ts +26 -0
  166. package/src/subsystems/Security/Vault.service/connectors/HashicorpVault.class.ts +46 -0
  167. package/src/subsystems/Security/Vault.service/connectors/JSONFileVault.class.ts +166 -0
  168. package/src/subsystems/Security/Vault.service/connectors/NullVault.class.ts +54 -0
  169. package/src/subsystems/Security/Vault.service/connectors/SecretsManager.class.ts +140 -0
  170. package/src/subsystems/Security/Vault.service/index.ts +12 -0
  171. package/src/types/ACL.types.ts +104 -0
  172. package/src/types/AWS.types.ts +9 -0
  173. package/src/types/Agent.types.ts +61 -0
  174. package/src/types/AgentLogger.types.ts +17 -0
  175. package/src/types/Cache.types.ts +1 -0
  176. package/src/types/Common.types.ts +3 -0
  177. package/src/types/LLM.types.ts +419 -0
  178. package/src/types/Redis.types.ts +8 -0
  179. package/src/types/SRE.types.ts +64 -0
  180. package/src/types/Security.types.ts +18 -0
  181. package/src/types/Storage.types.ts +5 -0
  182. package/src/types/VectorDB.types.ts +86 -0
  183. package/src/utils/base64.utils.ts +275 -0
  184. package/src/utils/cli.utils.ts +68 -0
  185. package/src/utils/data.utils.ts +263 -0
  186. package/src/utils/date-time.utils.ts +22 -0
  187. package/src/utils/general.utils.ts +238 -0
  188. package/src/utils/index.ts +12 -0
  189. package/src/utils/numbers.utils.ts +13 -0
  190. package/src/utils/oauth.utils.ts +35 -0
  191. package/src/utils/string.utils.ts +414 -0
  192. package/src/utils/url.utils.ts +19 -0
  193. package/src/utils/validation.utils.ts +74 -0
@@ -0,0 +1,472 @@
1
+ import { ConnectorService } from '@sre/Core/ConnectorsService';
2
+ import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
3
+ import { ACL } from '@sre/Security/AccessControl/ACL.class';
4
+ import { DEFAULT_TEAM_ID, IAccessCandidate, TAccessLevel, TAccessRole } from '@sre/types/ACL.types';
5
+ import { StorageData, StorageMetadata } from '@sre/types/Storage.types';
6
+ import { getMimeType } from '@sre/utils';
7
+ import mime from 'mime';
8
+ import { Readable } from 'stream';
9
+ import { StorageConnector } from './StorageConnector';
10
+ import { SmythRuntime } from '@sre/Core/SmythRuntime.class';
11
+ import { CacheConnector } from '@sre/MemoryManager/Cache.service/CacheConnector';
12
+ import crypto from 'crypto';
13
+ import { JSONContentHelper } from '@sre/helpers/JsonContent.helper';
14
+ import { SystemEvents } from '@sre/Core/SystemEvents';
15
+
16
+ export type TSmythFSURI = {
17
+ hash: string;
18
+ team: string;
19
+ path: string;
20
+ };
21
+
22
+ // SystemEvents.on('SRE:Booted', () => {
23
+ // const router = ConnectorService.getRouterConnector();
24
+ // if (router && router?.get instanceof Function) {
25
+ // router.get('/_temp/:uid', SmythFS.Instance.serveTempContent.bind(SmythFS.Instance));
26
+ // router.get('/storage/:file_id', SmythFS.Instance.serveResource.bind(SmythFS.Instance));
27
+ // }
28
+ // });
29
+
30
+ export class SmythFS {
31
+ private hash: string; // Store the instance hash for URL generation
32
+
33
+ static instances: any = {};
34
+
35
+ // Centralized hash generation to ensure consistency
36
+ private static generateInstanceHash(storageName: string, cacheName: string): string {
37
+ const instanceProps = `${storageName}:${cacheName}`;
38
+ return crypto.createHash('sha256').update(instanceProps).digest('hex').substring(0, 6);
39
+ }
40
+
41
+ // Default singleton instance (most common use case)
42
+ public static get Instance(): SmythFS {
43
+ return SmythFS.getInstance(); // Uses default empty string providers
44
+ }
45
+
46
+ // Multiton pattern - get instance based on storage and cache provider combination
47
+ public static getInstance(storageProvider: string | StorageConnector = '', cacheProvider: string | CacheConnector = ''): SmythFS {
48
+ // First get the actual connector names to calculate the correct hash
49
+ const storage = storageProvider instanceof StorageConnector ? storageProvider : ConnectorService.getStorageConnector(storageProvider);
50
+ const cache = cacheProvider instanceof CacheConnector ? cacheProvider : ConnectorService.getCacheConnector(cacheProvider);
51
+ const hash = SmythFS.generateInstanceHash(storage.name, cache.name);
52
+
53
+ if (SmythFS.instances[hash]) {
54
+ return SmythFS.instances[hash];
55
+ }
56
+
57
+ const instance = new SmythFS(storage, cache);
58
+
59
+ //register routes
60
+ const router = ConnectorService.getRouterConnector();
61
+ if (router && router?.get instanceof Function) {
62
+ router.get(`/_temp/${hash}/:uid`, instance.serveTempContent.bind(instance));
63
+ router.get(`/storage/${hash}/:file_id`, instance.serveResource.bind(instance));
64
+ }
65
+
66
+ SmythFS.instances[hash] = instance;
67
+ return instance;
68
+ }
69
+
70
+ private constructor(private storage: StorageConnector, private cache: CacheConnector) {
71
+ //SmythFS cannot be used without SRE
72
+ if (!ConnectorService.ready) {
73
+ throw new Error('SRE not available');
74
+ }
75
+
76
+ // Use centralized hash generation method
77
+ this.hash = SmythFS.generateInstanceHash(this.storage.name, this.cache.name);
78
+ }
79
+
80
+ // public getStoragePath(uri: string) {
81
+ // const smythURI = this.URIParser(uri);
82
+ // if (!smythURI) throw new Error('Invalid Resource URI');
83
+ // return `teams/${smythURI.team}${smythURI.path}`;
84
+ // }
85
+
86
+ public getBaseUri(candidate: IAccessCandidate) {
87
+ const uri = `smythfs://${candidate.id}.${candidate.role}`;
88
+
89
+ return uri;
90
+ }
91
+
92
+ /**
93
+ * Reads a resource from smyth file system
94
+ * @param uri smythfs:// uri
95
+ * @param candidate
96
+ * @returns
97
+ */
98
+ public async read(uri: string, candidate?: IAccessCandidate): Promise<Buffer> {
99
+ const smythURI = await this.URIParser(uri);
100
+ if (!smythURI) throw new Error('Invalid Resource URI');
101
+ candidate = candidate || smythURI.defaultCandidate; //fallback to default candidate if not provided
102
+
103
+ const accountConnector = ConnectorService.getAccountConnector();
104
+ const isMember = await accountConnector.isTeamMember(smythURI.team, candidate);
105
+ if (!isMember) throw new Error('Access Denied');
106
+
107
+ const resourceId = `teams/${smythURI.team}${smythURI.path}`;
108
+
109
+ const _candidate = candidate instanceof AccessCandidate ? candidate : new AccessCandidate(candidate);
110
+
111
+ const data = await this.storage.requester(_candidate).read(resourceId);
112
+
113
+ return data ? this.toBuffer(data) : null;
114
+ }
115
+
116
+ public async write(uri: string, data: any, candidate?: IAccessCandidate, metadata?: StorageMetadata, ttl?: number) {
117
+ const smythURI = await this.URIParser(uri);
118
+ if (!smythURI) throw new Error('Invalid Resource URI');
119
+ candidate = candidate || smythURI.defaultCandidate; //fallback to default candidate if not provided
120
+
121
+ const accountConnector = ConnectorService.getAccountConnector();
122
+ const isMember = await accountConnector.isTeamMember(smythURI.team, candidate);
123
+ if (!isMember) throw new Error('Access Denied');
124
+
125
+ const resourceId = `teams/${smythURI.team}${smythURI.path}`;
126
+ //when we write a file, it does not exist we need to explicitly provide a resource team in order to have access rights set properly
127
+
128
+ const _candidate = candidate instanceof AccessCandidate ? candidate : new AccessCandidate(candidate);
129
+
130
+ let acl: ACL;
131
+
132
+ //give team read access if this is a team resource and not the default team
133
+ //because the default team is a fallback used when no team is specified or account connector is not available
134
+ //in that case we need to only allow the creator to access the resource
135
+ if (smythURI.team && smythURI.team !== DEFAULT_TEAM_ID) {
136
+ acl = new ACL()
137
+ //.addAccess(candidate.role, candidate.id, TAccessLevel.Owner) // creator is owner
138
+ .addAccess(TAccessRole.Team, smythURI.team, TAccessLevel.Read).ACL as ACL; // team has read access
139
+ }
140
+
141
+ if (!metadata) metadata = {};
142
+ if (!metadata?.ContentType) {
143
+ metadata.ContentType = await getMimeType(data);
144
+ if (!metadata.ContentType) {
145
+ const ext: any = uri.split('.').pop();
146
+ if (ext) {
147
+ metadata.ContentType = mime.getType(ext) || 'application/octet-stream';
148
+ }
149
+ }
150
+ }
151
+ await this.storage.requester(_candidate).write(resourceId, data, acl, metadata);
152
+
153
+ if (ttl) {
154
+ await this.storage.requester(_candidate).expire(resourceId, ttl);
155
+ }
156
+ }
157
+
158
+ public async delete(uri: string, candidate?: IAccessCandidate) {
159
+ const smythURI = await this.URIParser(uri);
160
+ if (!smythURI) throw new Error('Invalid Resource URI');
161
+ candidate = candidate || smythURI.defaultCandidate; //fallback to default candidate if not provided
162
+
163
+ const accountConnector = ConnectorService.getAccountConnector();
164
+ const isMember = await accountConnector.isTeamMember(smythURI.team, candidate);
165
+ if (!isMember) throw new Error('Access Denied');
166
+
167
+ const resourceId = `teams/${smythURI.team}${smythURI.path}`;
168
+
169
+ const _candidate = candidate instanceof AccessCandidate ? candidate : new AccessCandidate(candidate);
170
+
171
+ await this.storage.requester(_candidate).delete(resourceId);
172
+ }
173
+
174
+ //TODO: should we require access token here ?
175
+ public async exists(uri: string, candidate?: IAccessCandidate) {
176
+ const smythURI = await this.URIParser(uri);
177
+ if (!smythURI) throw new Error('Invalid Resource URI');
178
+ candidate = candidate || smythURI.defaultCandidate; //fallback to default candidate if not provided
179
+
180
+ const accountConnector = ConnectorService.getAccountConnector();
181
+ const isMember = await accountConnector.isTeamMember(smythURI.team, candidate);
182
+ if (!isMember) throw new Error('Access Denied');
183
+
184
+ const resourceId = `teams/${smythURI.team}${smythURI.path}`;
185
+
186
+ //in order to get a consistent access check in case of inexisting resource, we need to explicitly set a default resource team
187
+ const _candidate = candidate instanceof AccessCandidate ? candidate : new AccessCandidate(candidate);
188
+
189
+ return await this.storage.requester(_candidate).exists(resourceId);
190
+ }
191
+
192
+ //#region Temp URL (mainly used for returning agent output to user for temporary access)
193
+ public async genTempUrl(uri: string, candidate?: IAccessCandidate, ttlSeconds: number = 3600) {
194
+ const smythURI = await this.URIParser(uri);
195
+ if (!smythURI) throw new Error('Invalid Resource URI');
196
+ candidate = candidate || smythURI.defaultCandidate; //fallback to default candidate if not provided
197
+
198
+ const accountConnector = ConnectorService.getAccountConnector();
199
+ const isMember = await accountConnector.isTeamMember(smythURI.team, candidate);
200
+ if (!isMember) throw new Error('Access Denied');
201
+
202
+ const exists = await this.exists(uri, candidate);
203
+ if (!exists) throw new Error('Resource does not exist');
204
+
205
+ const _candidate = candidate instanceof AccessCandidate ? candidate : new AccessCandidate(candidate);
206
+
207
+ const resourceId = `teams/${smythURI.team}${smythURI.path}`;
208
+ const resourceMetadata = await this.storage.requester(_candidate).getMetadata(resourceId);
209
+
210
+ const uid = crypto.randomUUID();
211
+ const tempUserCandidate = AccessCandidate.user(`system:${uid}`);
212
+
213
+ await this.cache.requester(tempUserCandidate).set(
214
+ `pub_url:${uid}`,
215
+ JSON.stringify({
216
+ accessCandidate: _candidate,
217
+ uri,
218
+ contentType: resourceMetadata?.ContentType,
219
+ }),
220
+ undefined,
221
+ undefined,
222
+ ttlSeconds
223
+ ); // 1 hour
224
+
225
+ const baseUrl = ConnectorService.getRouterConnector().baseUrl;
226
+ return `${baseUrl}/_temp/${this.hash}/${uid}`;
227
+ }
228
+
229
+ public async destroyTempUrl(url: string, { delResource }: { delResource: boolean } = { delResource: false }) {
230
+ // Parse URL with new format: /_temp/{hash}/{uid}
231
+ const tempPath = url.split('/_temp/')[1];
232
+ if (!tempPath) throw new Error('Invalid Temp URL format');
233
+
234
+ const uid = tempPath.split('/')[1]?.split('?')[0]; // get uid and remove query params
235
+ if (!uid) throw new Error('Invalid Temp URL format');
236
+
237
+ let cacheVal = await this.cache.requester(AccessCandidate.user(`system:${uid}`)).get(`pub_url:${uid}`);
238
+ if (!cacheVal) throw new Error('Invalid Temp URL');
239
+ cacheVal = JSONContentHelper.create(cacheVal).tryParse();
240
+ await this.cache.requester(AccessCandidate.user(`system:${uid}`)).delete(`pub_url:${uid}`);
241
+ if (delResource) {
242
+ await this.delete(cacheVal.uri, AccessCandidate.clone(cacheVal.accessCandidate));
243
+ }
244
+ }
245
+
246
+ public async serveTempContent(req: any, res: any) {
247
+ try {
248
+ const { uid } = req.params;
249
+ let cacheVal = await this.cache.requester(AccessCandidate.user(`system:${uid}`)).get(`pub_url:${uid}`);
250
+ if (!cacheVal) {
251
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
252
+ res.end('Invalid Temp URL');
253
+ return;
254
+ }
255
+ cacheVal = JSONContentHelper.create(cacheVal).tryParse();
256
+ const content = await this.read(cacheVal.uri, AccessCandidate.clone(cacheVal.accessCandidate));
257
+
258
+ const contentBuffer = Buffer.isBuffer(content) ? content : Buffer.from(content, 'binary');
259
+
260
+ const contentType = cacheVal.contentType || 'application/octet-stream';
261
+
262
+ res.writeHead(200, {
263
+ 'Content-Type': contentType,
264
+ 'Content-Disposition': 'inline',
265
+ 'Content-Length': contentBuffer.length,
266
+ });
267
+
268
+ res.end(contentBuffer);
269
+ } catch (error) {
270
+ console.error('Error serving temp content:', error);
271
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
272
+ res.end('Internal Server Error');
273
+ }
274
+ }
275
+ //#endregion
276
+
277
+ //#region Resource Serving
278
+
279
+ /**
280
+ * Generates a public url for the resource
281
+ * @param uri
282
+ * @param candidate
283
+ * @returns
284
+ */
285
+ public async genResourceUrl(uri: string, candidate?: IAccessCandidate) {
286
+ const smythURI = await this.URIParser(uri);
287
+ if (!smythURI) throw new Error('Invalid Resource URI');
288
+ candidate = candidate || smythURI.defaultCandidate; //fallback to default candidate if not provided
289
+
290
+ const accountConnector = ConnectorService.getAccountConnector();
291
+ const isMember = await accountConnector.isTeamMember(smythURI.team, candidate);
292
+ if (!isMember) throw new Error('Access Denied');
293
+
294
+ const exists = await this.exists(uri, candidate);
295
+ if (!exists) throw new Error('Resource does not exist');
296
+
297
+ const _candidate = candidate instanceof AccessCandidate ? candidate : new AccessCandidate(candidate);
298
+ if (_candidate.role !== TAccessRole.Agent) {
299
+ throw new Error('Only agents can generate resource urls');
300
+ }
301
+ const agentId = _candidate.id;
302
+
303
+ const resourceId = `teams/${smythURI.team}${smythURI.path}`;
304
+ const resourceMetadata = await this.storage.requester(_candidate).getMetadata(resourceId);
305
+
306
+ const uid = crypto.randomUUID(); // maybe instead of a random uuid, u can use the resource
307
+ const tempUserCandidate = AccessCandidate.user(`system:${uid}`);
308
+
309
+ await this.cache.requester(tempUserCandidate).set(
310
+ `storage_url:${uid}`,
311
+ JSON.stringify({
312
+ accessCandidate: _candidate,
313
+ uri,
314
+ contentType: resourceMetadata?.ContentType,
315
+ }),
316
+ undefined,
317
+ undefined
318
+ // 3600 // 1 hour
319
+ );
320
+
321
+ const contentType = resourceMetadata?.ContentType;
322
+ const ext = contentType ? mime.getExtension(contentType) : undefined;
323
+
324
+ // get the agent domain
325
+ const agentDataConnector = ConnectorService.getAgentDataConnector();
326
+ const baseUrl = ConnectorService.getRouterConnector().baseUrl;
327
+ const domain = agentDataConnector.getAgentConfig(agentId)?.agentStageDomain
328
+ ? `https://${agentDataConnector.getAgentConfig(agentId).agentStageDomain}`
329
+ : baseUrl;
330
+
331
+ return `${domain}/storage/${this.hash}/${uid}${ext ? `.${ext}` : ''}`;
332
+ }
333
+ public async destroyResourceUrl(url: string, { delResource }: { delResource: boolean } = { delResource: false }) {}
334
+ public async serveResource(req: any, res: any) {
335
+ try {
336
+ const { file_id } = req.params;
337
+ const [uid, extention] = file_id.split('.');
338
+ let cacheVal = await this.cache.requester(AccessCandidate.user(`system:${uid}`)).get(`storage_url:${uid}`);
339
+ if (!cacheVal) {
340
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
341
+ res.end('Invalid Resource URL');
342
+ return;
343
+ }
344
+ cacheVal = JSONContentHelper.create(cacheVal).tryParse();
345
+ const content = await this.read(cacheVal.uri, AccessCandidate.clone(cacheVal.accessCandidate));
346
+
347
+ const contentBuffer = Buffer.isBuffer(content) ? content : Buffer.from(content, 'binary');
348
+
349
+ const contentType = cacheVal.contentType || 'application/octet-stream';
350
+
351
+ res.writeHead(200, {
352
+ 'Content-Type': contentType,
353
+ 'Content-Disposition': 'inline',
354
+ 'Content-Length': contentBuffer.length,
355
+ });
356
+
357
+ res.end(contentBuffer);
358
+ } catch (error) {
359
+ console.error('Error serving storage resource content:', error);
360
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
361
+ res.end('Internal Server Error');
362
+ }
363
+ }
364
+ //#endregion
365
+
366
+ private async URIParser(uri: string) {
367
+ const parts = uri.split('://');
368
+ if (parts.length !== 2) return undefined;
369
+ if (parts[0].toLowerCase() !== 'smythfs') return undefined;
370
+ const parsed = this.CaseSensitiveURL(`http://${parts[1]}`);
371
+ const tld = parsed.hostname.split('.').pop();
372
+ if (tld !== 'team' && tld !== 'user' && tld !== 'agent' && tld !== 'smyth') throw new Error('Invalid Resource URI');
373
+ let team = tld === 'team' ? parsed.hostname.replace(`.${tld}`, '') : undefined;
374
+ const user = tld === 'user' ? parsed.hostname.replace(`.${tld}`, '') : undefined;
375
+ const agent = tld === 'agent' ? parsed.hostname.replace(`.${tld}`, '') : undefined;
376
+ const smyth = tld === 'smyth' ? parsed.hostname.replace(`.${tld}`, '') : undefined;
377
+
378
+ let basePath = '';
379
+ if (!team) {
380
+ let candidate: IAccessCandidate;
381
+ if (user) {
382
+ candidate = AccessCandidate.user(user);
383
+ basePath = '/' + user;
384
+ } else if (agent) {
385
+ candidate = AccessCandidate.agent(agent);
386
+ basePath = '/' + agent;
387
+ }
388
+
389
+ if (candidate) {
390
+ team = await ConnectorService.getAccountConnector().getCandidateTeam(candidate);
391
+ }
392
+ }
393
+
394
+ // create a default candidate based on the uri
395
+ let defaultCandidate: IAccessCandidate;
396
+
397
+ if (team) {
398
+ defaultCandidate = AccessCandidate.team(team);
399
+ } else if (user) {
400
+ defaultCandidate = AccessCandidate.user(user);
401
+ } else if (agent) {
402
+ defaultCandidate = AccessCandidate.agent(agent);
403
+ }
404
+
405
+ return {
406
+ hash: parsed.hash,
407
+ team,
408
+ user,
409
+ agent,
410
+ smyth,
411
+ defaultCandidate,
412
+ path: basePath + parsed.pathname,
413
+ };
414
+ }
415
+
416
+ private CaseSensitiveURL(urlString: string) {
417
+ // First, extract the original hostname for case preservation
418
+ const parts = urlString.split('://');
419
+ if (parts.length !== 2) return null;
420
+
421
+ const afterProtocol = parts[1];
422
+ const hostnameEnd = Math.min(
423
+ ...[afterProtocol.indexOf('/'), afterProtocol.indexOf('?'), afterProtocol.indexOf('#'), afterProtocol.length].filter((i) => i >= 0)
424
+ );
425
+
426
+ const originalHostnamePart = afterProtocol.substring(0, hostnameEnd);
427
+ const [originalHostname, originalPort] = originalHostnamePart.split(':');
428
+
429
+ // Use URL constructor for robust parsing of everything else
430
+ const parsed = new URL(urlString);
431
+
432
+ // Explicitly copy URL properties since they're not enumerable
433
+ return {
434
+ protocol: parsed.protocol,
435
+ hostname: originalHostname, // Case-sensitive hostname
436
+ port: parsed.port,
437
+ pathname: parsed.pathname,
438
+ search: parsed.search,
439
+ searchParams: parsed.searchParams,
440
+ hash: parsed.hash,
441
+ href: parsed.href,
442
+ origin: parsed.origin,
443
+ host: originalHostname + (parsed.port ? `:${parsed.port}` : ''),
444
+ originalPort: originalPort || null,
445
+ };
446
+ }
447
+
448
+ private async toBuffer(data: StorageData): Promise<Buffer> {
449
+ if (Buffer.isBuffer(data)) {
450
+ return data;
451
+ } else if (typeof data === 'string') {
452
+ return Buffer.from(data, 'utf-8');
453
+ } else if (data instanceof Uint8Array) {
454
+ return Buffer.from(data);
455
+ } else if (data instanceof Readable) {
456
+ return new Promise<Buffer>((resolve, reject) => {
457
+ const chunks: Buffer[] = [];
458
+ data.on('data', (chunk) => {
459
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
460
+ });
461
+ data.on('end', () => {
462
+ resolve(Buffer.concat(chunks));
463
+ });
464
+ data.on('error', (err) => {
465
+ reject(err);
466
+ });
467
+ });
468
+ } else {
469
+ throw new Error('Unsupported data type');
470
+ }
471
+ }
472
+ }
@@ -0,0 +1,66 @@
1
+ import { ACL } from '@sre/Security/AccessControl/ACL.class';
2
+ import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
3
+ import { AccessRequest } from '@sre/Security/AccessControl/AccessRequest.class';
4
+ import { SecureConnector } from '@sre/Security/SecureConnector.class';
5
+ import { IAccessCandidate, IACL } from '@sre/types/ACL.types';
6
+ import { StorageData, StorageMetadata } from '@sre/types/Storage.types';
7
+
8
+ export interface IStorageRequest {
9
+ read(resourceId: string): Promise<StorageData>;
10
+ write(resourceId: string, value: StorageData, acl?: IACL, metadata?: StorageMetadata): Promise<void>;
11
+ delete(resourceId: string): Promise<void>;
12
+ exists(resourceId: string): Promise<boolean>;
13
+ getMetadata(resourceId: string): Promise<StorageMetadata | undefined>;
14
+ setMetadata(resourceId: string, metadata: StorageMetadata): Promise<void>;
15
+ getACL(resourceId: string): Promise<ACL | undefined>;
16
+ setACL(resourceId: string, acl: IACL): Promise<void>;
17
+ expire(resourceId: string, ttl: number): Promise<void>;
18
+ }
19
+
20
+ export abstract class StorageConnector extends SecureConnector {
21
+ public abstract getResourceACL(resourceId: string, candidate: IAccessCandidate): Promise<ACL>;
22
+
23
+ protected abstract read(acRequest: AccessRequest, resourceId: string): Promise<StorageData>;
24
+ protected abstract write(acRequest: AccessRequest, resourceId: string, value: StorageData, acl?: IACL, metadata?: StorageMetadata): Promise<void>;
25
+ protected abstract delete(acRequest: AccessRequest, resourceId: string): Promise<void>;
26
+ protected abstract exists(acRequest: AccessRequest, resourceId: string): Promise<boolean>;
27
+
28
+ protected abstract getMetadata(acRequest: AccessRequest, resourceId: string): Promise<StorageMetadata | undefined>;
29
+ protected abstract setMetadata(acRequest: AccessRequest, resourceId: string, metadata: StorageMetadata): Promise<void>;
30
+
31
+ protected abstract getACL(acRequest: AccessRequest, resourceId: string): Promise<ACL | undefined>;
32
+ protected abstract setACL(acRequest: AccessRequest, resourceId: string, acl: IACL): Promise<void>;
33
+ protected abstract expire(acRequest: AccessRequest, resourceId: string, ttl: number): Promise<void>;
34
+
35
+ public requester(candidate: AccessCandidate): IStorageRequest {
36
+ return {
37
+ write: async (resourceId: string, value: StorageData, acl?: IACL, metadata?: StorageMetadata) => {
38
+ return await this.write(candidate.writeRequest, resourceId, value, acl, metadata);
39
+ },
40
+ read: async (resourceId: string) => {
41
+ return await this.read(candidate.readRequest, resourceId);
42
+ },
43
+ delete: async (resourceId: string) => {
44
+ await this.delete(candidate.readRequest, resourceId);
45
+ },
46
+ exists: async (resourceId: string) => {
47
+ return await this.exists(candidate.readRequest, resourceId);
48
+ },
49
+ getMetadata: async (resourceId: string) => {
50
+ return await this.getMetadata(candidate.readRequest, resourceId);
51
+ },
52
+ setMetadata: async (resourceId: string, metadata: StorageMetadata) => {
53
+ await this.setMetadata(candidate.writeRequest, resourceId, metadata);
54
+ },
55
+ getACL: async (resourceId: string) => {
56
+ return await this.getACL(candidate.readRequest, resourceId);
57
+ },
58
+ setACL: async (resourceId: string, acl: IACL) => {
59
+ return await this.setACL(candidate.writeRequest, resourceId, acl);
60
+ },
61
+ expire: async (resourceId: string, ttl: number) => {
62
+ return await this.expire(candidate.writeRequest, resourceId, ttl);
63
+ },
64
+ } as IStorageRequest;
65
+ }
66
+ }