nolo-cli 0.1.29 → 0.1.31

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 (329) hide show
  1. package/agent-runtime/agentRecordConfig.ts +0 -2
  2. package/agent-runtime/hostAdapter.ts +0 -1
  3. package/agent-runtime/hostRuntimeCapabilities.ts +7 -0
  4. package/agent-runtime/hostRuntimeConfig.ts +86 -0
  5. package/agent-runtime/index.ts +13 -0
  6. package/agent-runtime/localToolPolicy.ts +13 -6
  7. package/agent-runtime/localWorkspaceTools.ts +333 -30
  8. package/agent-runtime/platformChatProvider.ts +4 -1
  9. package/agent-runtime/runtimeToolPolicy.ts +32 -47
  10. package/agent-runtime/shellCommandPolicy.ts +117 -0
  11. package/agent-runtime/toolGate.ts +38 -0
  12. package/agentCreateCustomCommands.ts +9 -4
  13. package/agentDialogsCommands.ts +4 -3
  14. package/agentDoctorCommands.ts +3 -3
  15. package/agentListCommands.ts +3 -3
  16. package/agentMachineCommands.ts +6 -6
  17. package/agentPullCommand.ts +4 -12
  18. package/agentRecordCommands.ts +5 -3
  19. package/agentRecordHelpers.ts +42 -23
  20. package/agentRunCommand.ts +2 -6
  21. package/agentRunParsing.ts +18 -5
  22. package/agentRuntimeLocal.ts +10 -0
  23. package/agentUnpublishCommands.ts +3 -2
  24. package/ai/agent/agentRunDialogLineage.ts +56 -0
  25. package/ai/agent/agentSlice.ts +45 -10
  26. package/ai/agent/avatarUtils.ts +1 -1
  27. package/ai/agent/buildSystemPrompt.ts +1 -2
  28. package/ai/agent/cliExecutor.ts +330 -19
  29. package/ai/agent/createAgentSchema.ts +22 -0
  30. package/ai/agent/hooks/fetchPublicAgents.ts +14 -39
  31. package/ai/agent/hooks/usePublicAgents.ts +90 -192
  32. package/ai/agent/publicAgentCatalog.ts +359 -0
  33. package/ai/agent/publicAgentIdentity.ts +76 -0
  34. package/ai/agent/server/fetchPublicAgents.ts +21 -46
  35. package/ai/agent/serverOrigin.ts +7 -0
  36. package/ai/agent/streamAgentChatTurn.ts +23 -21
  37. package/ai/agent/streamAgentChatTurnUtils.ts +292 -6
  38. package/ai/agent/types.ts +2 -0
  39. package/ai/agent/web/agentDisplayUtils.ts +171 -0
  40. package/ai/agent/web/useAgentModelAvatarComponent.ts +32 -0
  41. package/ai/ai.locale.ts +8 -0
  42. package/ai/chat/sendOpenAICompletionsRequest.native.ts +15 -0
  43. package/ai/chat/sendOpenAICompletionsRequest.ts +93 -1
  44. package/ai/chat/sendOpenAIResponseRequest.ts +86 -9
  45. package/ai/chat/updateTotalUsage.ts +7 -0
  46. package/ai/llm/deepinfra.ts +30 -15
  47. package/ai/llm/mistral.ts +3 -4
  48. package/ai/llm/providers.ts +2 -0
  49. package/ai/llm/types.ts +15 -0
  50. package/ai/memory/capture.ts +3 -3
  51. package/ai/memory/consolidate.ts +2 -2
  52. package/ai/memory/delete.ts +4 -3
  53. package/ai/memory/query.ts +3 -3
  54. package/ai/memory/remember.ts +2 -2
  55. package/ai/memory/store.ts +3 -3
  56. package/ai/memory/storeShared.ts +3 -2
  57. package/ai/policy/commercialMultiplier.ts +16 -0
  58. package/ai/token/billingAdminAuditEvent.ts +68 -0
  59. package/ai/token/billingAdminAuditEventWriter.ts +41 -0
  60. package/ai/token/billingAnomaly.ts +90 -0
  61. package/ai/token/billingAnomalyLifecycle.ts +54 -0
  62. package/ai/token/billingAnomalyLifecycleWriter.ts +44 -0
  63. package/ai/token/billingAnomalyWriter.ts +41 -0
  64. package/ai/token/calculatePrice.ts +3 -2
  65. package/ai/token/deepinfraReconciliation.ts +153 -0
  66. package/ai/token/deepinfraRequestIdQuery.ts +92 -0
  67. package/ai/token/externalToolCost.ts +54 -41
  68. package/ai/token/missingUsageEstimate.ts +12 -3
  69. package/ai/token/normalizeUsage.ts +45 -5
  70. package/ai/token/openaiReconciliation.ts +188 -0
  71. package/ai/token/providerBillableEvent.ts +84 -0
  72. package/ai/token/providerBillableEventWriter.ts +36 -0
  73. package/ai/token/providerBillingAnomalyDrilldown.ts +308 -0
  74. package/ai/token/providerBillingDrilldown.ts +361 -0
  75. package/ai/token/providerBillingHealthReport.ts +366 -0
  76. package/ai/token/providerCall.ts +144 -0
  77. package/ai/token/providerCallSweeper.ts +168 -0
  78. package/ai/token/providerCallWriter.ts +33 -0
  79. package/ai/token/providerCredential.ts +89 -0
  80. package/ai/token/providerCredentialAnomaly.ts +154 -0
  81. package/ai/token/providerCredentialLifecycle.ts +59 -0
  82. package/ai/token/providerCredentialLifecycleWriter.ts +44 -0
  83. package/ai/token/providerCredentialRegistry.ts +83 -0
  84. package/ai/token/providerCredentialRegistryCommand.ts +97 -0
  85. package/ai/token/providerCredentialRegistryList.ts +124 -0
  86. package/ai/token/providerCredentialRegistryResolver.ts +150 -0
  87. package/ai/token/providerCredentialRegistryWriter.ts +41 -0
  88. package/ai/token/providerCredentialRotationCommand.ts +102 -0
  89. package/ai/token/providerCredentialRuntime.ts +56 -0
  90. package/ai/token/providerDispatchIntent.ts +67 -0
  91. package/ai/token/providerDispatchIntentWriter.ts +36 -0
  92. package/ai/token/providerGateway.ts +260 -0
  93. package/ai/token/providerReconciliation.ts +148 -0
  94. package/ai/token/providerReconciliationLocal.ts +97 -0
  95. package/ai/token/providerReconciliationRunner.ts +165 -0
  96. package/ai/token/providerReconciliationWriter.ts +41 -0
  97. package/ai/token/ratingResult.ts +202 -0
  98. package/ai/token/ratingResultWriter.ts +33 -0
  99. package/ai/token/serverDialogProjection.ts +5 -3
  100. package/ai/token/serverTokenWriter.ts +11 -3
  101. package/ai/token/types.ts +10 -0
  102. package/ai/tools/agent/callAgentTool.ts +3 -4
  103. package/ai/tools/agent/presets/appBuilderPreset.ts +5 -7
  104. package/ai/tools/agent/runStreamingAgentTool.ts +1 -2
  105. package/ai/tools/agent/streamParallelAgentsTool.ts +2 -3
  106. package/ai/tools/readXPostTool.ts +1 -5
  107. package/app/admin/adminPages.ts +9 -0
  108. package/app/i18n/i18n.config.ts +5 -0
  109. package/app/i18n/translations/pricing.locale.ts +397 -0
  110. package/app/utils/desktopAgentRuntimeStatusClient.ts +5 -4
  111. package/app/utils/desktopAgentRuntimeTurnClient.ts +4 -1
  112. package/app/utils/imageUtils.ts +64 -34
  113. package/auth/adminPermissions.ts +18 -0
  114. package/auth/authSlice.ts +26 -12
  115. package/auth/hooks/useFetchUsers.ts +3 -0
  116. package/auth/routes.ts +46 -0
  117. package/auth/server/accessActivity.ts +4 -3
  118. package/auth/server/adminPermissions.ts +43 -0
  119. package/auth/server/adminUsageReport.ts +375 -0
  120. package/auth/server/billingAnomalies.ts +235 -0
  121. package/auth/server/billingUsageReport.ts +41 -2
  122. package/auth/server/creatorEarningCreditConversion.ts +10 -2
  123. package/auth/server/deduct.ts +14 -7
  124. package/auth/server/delete.ts +10 -2
  125. package/auth/server/disable.ts +4 -3
  126. package/auth/server/emailAutomation.ts +7 -5
  127. package/auth/server/emailDbConfig.ts +4 -2
  128. package/auth/server/emailDelivery.ts +24 -20
  129. package/auth/server/emailDeliveryGuards.ts +10 -7
  130. package/auth/server/emailPreferences.ts +6 -4
  131. package/auth/server/emailReport.ts +6 -4
  132. package/auth/server/emailRuntimeConfig.ts +3 -3
  133. package/auth/server/emailScenarioNotifications.ts +9 -8
  134. package/auth/server/enable.ts +4 -3
  135. package/auth/server/getRechargeHistory.ts +3 -2
  136. package/auth/server/getUser.ts +3 -2
  137. package/auth/server/gptProAccess.ts +44 -0
  138. package/auth/server/inviteReward.ts +10 -7
  139. package/auth/server/listusers.ts +6 -4
  140. package/auth/server/login.ts +2 -2
  141. package/auth/server/productEntitlements.ts +7 -4
  142. package/auth/server/productPurchase.ts +10 -2
  143. package/auth/server/providerBillingDrilldown.ts +47 -0
  144. package/auth/server/providerBillingHealth.ts +71 -0
  145. package/auth/server/providerCredentials.ts +136 -0
  146. package/auth/server/recharge.ts +14 -8
  147. package/auth/server/revokeSessions.ts +4 -3
  148. package/auth/server/route.ts +77 -0
  149. package/auth/server/sendEmail.ts +5 -4
  150. package/auth/server/signup.ts +10 -3
  151. package/auth/server/token.ts +53 -55
  152. package/auth/server/tokenUsageBilling.ts +18 -7
  153. package/auth/server/usageManagementAccess.ts +43 -0
  154. package/auth/server/usageReport.ts +59 -0
  155. package/auth/types.ts +12 -0
  156. package/auth/utils.ts +24 -22
  157. package/authCommands.ts +36 -2
  158. package/buildPublish.ts +3 -1
  159. package/buildPublishArtifactAssembly.ts +62 -1
  160. package/buildPublishImportAnalysis.ts +21 -16
  161. package/chat/dialog/dialogLaunchScope.ts +32 -0
  162. package/chat/dialog/objectAssistantRegistry.ts +2 -2
  163. package/chat/dialog/useCreateDialog.ts +1 -1
  164. package/chat/hooks/useChatInput.ts +41 -10
  165. package/chat/messages/messageSlice.ts +5 -1
  166. package/chat/messages/pendingAttachmentParts.ts +28 -2
  167. package/chat/messages/sendFirstMessage.ts +76 -79
  168. package/chat/messages/types.ts +9 -0
  169. package/chat/messages/web/streamingMarkdownModel.ts +41 -0
  170. package/chat/messages/web/useStreamingReveal.ts +91 -0
  171. package/chat/web/messageInputAgentUi.ts +94 -6
  172. package/cliEnvHelpers.ts +68 -13
  173. package/cliRuntimeDoctorReport.ts +193 -0
  174. package/client/agentConfigResolver.test.ts +0 -2
  175. package/client/agentRun.test.ts +171 -10
  176. package/client/agentRun.ts +44 -637
  177. package/client/agentRunInput.ts +10 -0
  178. package/client/agentRunLocalExecutor.ts +179 -0
  179. package/client/agentRunServerTransport.ts +394 -0
  180. package/client/agentRunTaskRunRecorder.ts +176 -0
  181. package/client/localRuntimeAdapter.test.ts +236 -9
  182. package/client/localRuntimeAdapter.ts +221 -23
  183. package/client/localToolPolicy.test.ts +28 -4
  184. package/connector-experimental/daemonLauncher.ts +38 -4
  185. package/connectorRunArtifact.ts +34 -10
  186. package/connectorWebSocketTarget.ts +40 -15
  187. package/core/builtinAgents.ts +155 -11
  188. package/create/space/contentLabels.ts +1 -1
  189. package/create/space/contentTypeMeta.ts +3 -2
  190. package/create/space/sidebarVisibleTypes.ts +27 -0
  191. package/create/space/space.locale.ts +76 -4
  192. package/database/actions/agentReadResolution.ts +2 -8
  193. package/database/actions/read.ts +11 -9
  194. package/database/actions/readAndWait.ts +10 -5
  195. package/database/server/agentDelegation.ts +3 -2
  196. package/database/server/authorityStoreConformance.ts +209 -0
  197. package/database/server/authorityStoreTypes.ts +31 -0
  198. package/database/server/coreDataProxy.ts +1 -1
  199. package/database/server/dataHandlers.ts +13 -5
  200. package/database/server/db.ts +15 -34
  201. package/database/server/delete.ts +88 -71
  202. package/database/server/emailRepository.ts +11 -9
  203. package/database/server/fileService.ts +2 -1
  204. package/database/server/legacyServerDb.ts +58 -0
  205. package/database/server/levelAuthorityStore.ts +75 -0
  206. package/database/server/memoryAuthorityStore.ts +133 -0
  207. package/database/server/patch.ts +13 -12
  208. package/database/server/query.ts +3 -2
  209. package/database/server/read.ts +33 -30
  210. package/database/server/resourceAccess.ts +7 -5
  211. package/database/server/serverStoreFactory.ts +124 -0
  212. package/database/server/spaceMemberAuthority.ts +3 -2
  213. package/database/server/storeBatchCompat.ts +37 -0
  214. package/database/server/testAuthorityStore.ts +76 -0
  215. package/database/server/write.ts +29 -27
  216. package/dialogReadCommands.ts +2 -1
  217. package/dialogStatusCommands.ts +2 -1
  218. package/integrations/anthropic/anthropicModels.ts +12 -12
  219. package/integrations/deepseek/models.ts +67 -67
  220. package/integrations/google/models.ts +111 -53
  221. package/integrations/openai/models.ts +22 -22
  222. package/integrations/xai/models.ts +1 -1
  223. package/localRuntimeDb.ts +39 -2
  224. package/machineCommandPrompts.ts +2 -0
  225. package/machineCommands.ts +193 -62
  226. package/machineStatusCommands.ts +4 -12
  227. package/machineWsRunDispatch.ts +80 -15
  228. package/machineWsSession.ts +46 -2
  229. package/noloReadBridgePrompt.ts +16 -0
  230. package/package.json +114 -21
  231. package/pageCreateCommands.ts +2 -2
  232. package/pageDeleteCommands.ts +3 -3
  233. package/pageReadCommands.ts +3 -3
  234. package/pageUpdateCommands.ts +3 -3
  235. package/render/layout/mainLayoutViewMode.ts +25 -0
  236. package/render/page/server/createPage.ts +3 -1
  237. package/render/page/server/handleCreatePage.ts +2 -11
  238. package/runtimeDoctorCommands.ts +18 -69
  239. package/server/api/methods.ts +34 -12
  240. package/server/api/tableHandlers.ts +6 -3
  241. package/server/authenticateToken.ts +47 -2
  242. package/server/billingLedgerRoutes.ts +15 -0
  243. package/server/buildManifest.ts +54 -0
  244. package/server/coreReadiness.ts +34 -25
  245. package/server/coreRuntime.ts +15 -10
  246. package/server/handlers/activityStatsHandler.ts +5 -2
  247. package/server/handlers/agentEmailRegistrationE2EHandler.ts +25 -23
  248. package/server/handlers/agentRun/agentLookup.ts +1 -7
  249. package/server/handlers/agentRun/autonomousRuntime.ts +11 -10
  250. package/server/handlers/agentRun/builtinAgents.ts +12 -88
  251. package/server/handlers/agentRun/continueDialogContext.ts +15 -3
  252. package/server/handlers/agentRun/{inheritedDialogPrompt.ts → conversationReference.ts} +3 -3
  253. package/server/handlers/agentRun/dialogLookup.ts +4 -3
  254. package/server/handlers/agentRun/index.ts +864 -404
  255. package/server/handlers/agentRun/localRuntimeBootstrap.ts +17 -1
  256. package/server/handlers/agentRun/loop.ts +920 -508
  257. package/server/handlers/agentRun/machineConnector.ts +56 -8
  258. package/server/handlers/agentRun/machineRunAudit.ts +3 -2
  259. package/server/handlers/agentRun/modelUsageToolHandlers.ts +13 -10
  260. package/server/handlers/agentRun/requestContext.ts +12 -8
  261. package/server/handlers/agentRun/runtimeExecutionContext.ts +15 -3
  262. package/server/handlers/agentRun/runtimePreparation.ts +26 -24
  263. package/server/handlers/agentRun/runtimeRouting.ts +25 -40
  264. package/server/handlers/agentRun/runtimeSystemMessages.ts +65 -0
  265. package/server/handlers/agentRun/saveDialog.ts +97 -87
  266. package/server/handlers/agentRun/taskRunToolHandler.ts +9 -7
  267. package/server/handlers/agentRun/toolExecutor.ts +42 -78
  268. package/server/handlers/agentRun/types.ts +2 -1
  269. package/server/handlers/appDeployStatusStore.ts +17 -10
  270. package/server/handlers/appDomainHandler.ts +21 -15
  271. package/server/handlers/appLegacyInfraCleanup.ts +5 -2
  272. package/server/handlers/appSandboxHandler.ts +29 -8
  273. package/server/handlers/appSpaceAccess.ts +15 -8
  274. package/server/handlers/chatHandler.ts +22 -2
  275. package/server/handlers/chatUpstreamRetry.ts +225 -2
  276. package/server/handlers/connector/connectorConnectionRegistry.ts +55 -7
  277. package/server/handlers/connector/connectorWebSocket.ts +14 -10
  278. package/server/handlers/desktopAgentRuntimeAdapter.ts +4 -4
  279. package/server/handlers/desktopAgentRuntimeHostCapabilities.ts +25 -0
  280. package/server/handlers/desktopAgentRuntimeReadiness.ts +62 -0
  281. package/server/handlers/desktopAgentRuntimeStatusHandler.ts +38 -30
  282. package/server/handlers/desktopAgentRuntimeTurnHandler.ts +7 -3
  283. package/server/handlers/desktopAgentRuntimeTurnService.ts +39 -45
  284. package/server/handlers/desktopLlamaRuntimeHandler.ts +85 -51
  285. package/server/handlers/desktopUpdaterHandler.ts +132 -24
  286. package/server/handlers/favoriteHandlers.ts +8 -2
  287. package/server/handlers/getDialogBillingHandler.ts +4 -3
  288. package/server/handlers/getTransactionsHandler.ts +5 -2
  289. package/server/handlers/machines/machineBinding.ts +1 -0
  290. package/server/handlers/machines/machineHandlers.ts +0 -14
  291. package/server/handlers/machines/machineInstallAssets.ts +4 -2
  292. package/server/handlers/notificationEmitter.ts +5 -3
  293. package/server/handlers/notificationsHandler.ts +5 -2
  294. package/server/handlers/providerCallsRecentHandler.ts +234 -0
  295. package/server/handlers/providerReconciliationRunHandler.ts +180 -0
  296. package/server/handlers/providerRequestIdsHandler.ts +105 -0
  297. package/server/handlers/tableAccess.ts +6 -2
  298. package/server/handlers/tableToolHandlers.ts +28 -14
  299. package/server/handlers/userSecretsHandler.ts +17 -6
  300. package/server/handlers/versionHandler.ts +9 -4
  301. package/server/handlers/versionStore.ts +18 -10
  302. package/server/html/ssrPreload.ts +5 -3
  303. package/server/payments/crypto/cryptoUsdcBasePaymentProvider.ts +11 -8
  304. package/server/payments/crypto/cryptoUsdcBaseScanner.ts +12 -7
  305. package/server/payments/crypto/cryptoUsdtTronPaymentProvider.ts +11 -8
  306. package/server/payments/crypto/cryptoUsdtTronScanner.ts +9 -7
  307. package/server/payments/waffo/waffoPaymentProvider.ts +12 -9
  308. package/server/runtimeRole.ts +15 -0
  309. package/server/scheduler/scheduledTaskRuntime.ts +4 -2
  310. package/server/scheduler/schedulerService.ts +2 -2
  311. package/server/taskRunBridgeRoutes.ts +8 -5
  312. package/share/server/fetchCommunityShares.ts +1 -1
  313. package/share/server/helpers.ts +19 -17
  314. package/share/server/importShare.ts +9 -13
  315. package/share/server/listCommunityShares.ts +4 -4
  316. package/share/server/purchaseDoc.ts +8 -16
  317. package/share/server/readCommunityShareCover.ts +3 -2
  318. package/share/server/readSharedTable.ts +14 -13
  319. package/share/server/tableReplication.ts +42 -39
  320. package/spaceAttachCommands.ts +135 -0
  321. package/spaceCategoryCommands.ts +6 -6
  322. package/spaceCommands.ts +3 -3
  323. package/spaceDeleteCommands.ts +2 -2
  324. package/spaceInternalCommandEntries.ts +2 -0
  325. package/spaceReadCommands.ts +3 -3
  326. package/tableMetaCommands.ts +2 -2
  327. package/taskRunCommand.ts +11 -0
  328. package/ai/agent/runtimeServerBase.ts +0 -37
  329. package/server/handlers/desktopAgentRuntimeHostFacts.ts +0 -40
@@ -0,0 +1,105 @@
1
+ import {
2
+ collectProviderRequestIds,
3
+ type DeepInfraRequestIdStore,
4
+ } from "../../ai/token/deepinfraRequestIdQuery";
5
+
6
+ const JSON_HEADERS = {
7
+ "content-type": "application/json; charset=utf-8",
8
+ };
9
+
10
+ type ProviderRequestIdsEnv = NodeJS.ProcessEnv & {
11
+ BILLING_LEDGER_AUDIT_SECRET?: string;
12
+ };
13
+
14
+ const json = (body: unknown, status = 200) =>
15
+ new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
16
+
17
+ const parseOptionalTimestamp = (value: string | null) => {
18
+ if (!value) return null;
19
+ const trimmed = value.trim();
20
+ if (!trimmed) return null;
21
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
22
+ const parsed = Date.parse(trimmed);
23
+ if (!Number.isFinite(parsed)) {
24
+ throw new Error(`invalid timestamp: ${value}`);
25
+ }
26
+ return parsed;
27
+ };
28
+
29
+ const parseLimit = (value: string | null) => {
30
+ const parsed = Number(value);
31
+ if (!Number.isFinite(parsed)) return 5000;
32
+ return Math.min(Math.max(Math.floor(parsed), 1), 10_000);
33
+ };
34
+
35
+ const resolveDefaultStore = async (): Promise<DeepInfraRequestIdStore> => {
36
+ const dbModule = await import("../../database/server/db");
37
+ return dbModule.default as DeepInfraRequestIdStore;
38
+ };
39
+
40
+ export function createProviderRequestIdsHandler({
41
+ store,
42
+ env = process.env,
43
+ nowMs,
44
+ }: {
45
+ store?: DeepInfraRequestIdStore;
46
+ env?: Partial<ProviderRequestIdsEnv>;
47
+ nowMs?: number;
48
+ } = {}) {
49
+ return async function handleProviderRequestIds(req: Request) {
50
+ const expectedSecret = String(env.BILLING_LEDGER_AUDIT_SECRET || "").trim();
51
+ if (!expectedSecret) {
52
+ return new Response("Not Found", { status: 404 });
53
+ }
54
+
55
+ const providedSecret =
56
+ req.headers.get("x-billing-ledger-audit-secret")?.trim() || "";
57
+ if (providedSecret !== expectedSecret) {
58
+ return json({ success: false, error: "Unauthorized" }, 401);
59
+ }
60
+
61
+ try {
62
+ const url = new URL(req.url);
63
+ const provider = url.searchParams.get("provider")?.trim();
64
+ if (!provider) throw new Error("provider is required");
65
+ const now = nowMs ?? Date.now();
66
+ const untilMs = parseOptionalTimestamp(url.searchParams.get("until")) ?? now;
67
+ const sinceMs =
68
+ parseOptionalTimestamp(url.searchParams.get("since")) ?? untilMs - 3600_000;
69
+ const limit = parseLimit(url.searchParams.get("limit"));
70
+ const result = await collectProviderRequestIds({
71
+ store: store ?? (await resolveDefaultStore()),
72
+ provider,
73
+ bucketStart: new Date(sinceMs).toISOString(),
74
+ bucketEnd: new Date(untilMs).toISOString(),
75
+ });
76
+ const requestIds = result.requestIds.slice(0, limit);
77
+ const responseIds = result.responseIds.slice(0, limit);
78
+ return json({
79
+ success: true,
80
+ report: {
81
+ provider,
82
+ sinceMs,
83
+ untilMs,
84
+ requestIds,
85
+ responseIds,
86
+ scannedTokenRecords: result.scannedTokenRecords,
87
+ matchedTokenRecords: result.matchedTokenRecords,
88
+ truncated:
89
+ result.requestIds.length > requestIds.length ||
90
+ result.responseIds.length > responseIds.length,
91
+ },
92
+ });
93
+ } catch (error) {
94
+ return json(
95
+ {
96
+ success: false,
97
+ error: error instanceof Error ? error.message : String(error),
98
+ },
99
+ 400
100
+ );
101
+ }
102
+ };
103
+ }
104
+
105
+ export const handleProviderRequestIds = createProviderRequestIdsHandler();
@@ -1,8 +1,10 @@
1
1
  import { metaKey } from "../../database/keys";
2
- import serverDb from "../../database/server/db";
2
+ import { getServerAuthorityStore } from "../../database/server/db";
3
3
  import type { TableMeta } from "../../render/table/types";
4
4
  import { hasSpaceRole } from "./appSpaceAccess";
5
5
 
6
+ const getTableAccessStore = () => getServerAuthorityStore();
7
+
6
8
  export async function canReadTableRows(params: {
7
9
  userId: string | null | undefined;
8
10
  tenantId: string;
@@ -15,7 +17,9 @@ export async function canReadTableRows(params: {
15
17
 
16
18
  const tableMeta =
17
19
  params.tableMeta ??
18
- ((await serverDb.get(metaKey(tenantId, tableId)).catch(() => null)) as TableMeta | null);
20
+ ((await getTableAccessStore()
21
+ .get(metaKey(tenantId, tableId))
22
+ .catch(() => null)) as TableMeta | null);
19
23
  const spaceId = typeof tableMeta?.spaceId === "string" ? tableMeta.spaceId.trim() : "";
20
24
  if (!spaceId) return false;
21
25
 
@@ -1,8 +1,11 @@
1
- import serverDb, { ensureServerDbOpen } from "../../database/server/db";
1
+ import {
2
+ ensureServerDbOpen,
3
+ getServerAuthorityStore,
4
+ } from "../../database/server/db";
2
5
  import { metaKey, rowKey } from "../../database/keys";
3
6
  import { ulid } from "../../database/utils/ulid";
4
7
  import { DataType } from "../../create/types";
5
- import { handleToken } from "../../auth/server/token";
8
+ import { readUserFromRequest } from "../../auth/server/token";
6
9
  import {
7
10
  applyRowFilters,
8
11
  formatKnownColumns,
@@ -13,6 +16,27 @@ import {
13
16
  import type { TableColumn, TableMeta } from "../../render/table/types";
14
17
  import { assertCanReadTableRows } from "./tableAccess";
15
18
 
19
+ const getTableToolStore = () => getServerAuthorityStore();
20
+ const serverDb = {
21
+ get<T = any>(key: string) {
22
+ return getTableToolStore().get<T>(key);
23
+ },
24
+ put(key: string, value: unknown) {
25
+ return getTableToolStore().put(key, value);
26
+ },
27
+ del(key: string) {
28
+ return getTableToolStore().del(key);
29
+ },
30
+ iterator(options?: {
31
+ gte?: string;
32
+ lte?: string;
33
+ lt?: string;
34
+ reverse?: boolean;
35
+ }) {
36
+ return getTableToolStore().iterator(options);
37
+ },
38
+ };
39
+
16
40
  const CORS_HEADERS = {
17
41
  "Access-Control-Allow-Origin": "*",
18
42
  "Access-Control-Allow-Methods": "POST, OPTIONS",
@@ -43,12 +67,7 @@ function jsonResponse(body: unknown, status = 200) {
43
67
  }
44
68
 
45
69
  async function getAuthedUserId(req: Request): Promise<string> {
46
- const authReq: any = {
47
- headers: {
48
- get: (name: string) => req.headers.get(name),
49
- },
50
- };
51
- const user = await handleToken(authReq, {});
70
+ const user = await readUserFromRequest(req);
52
71
  const userId = user?.userId;
53
72
  if (!userId) {
54
73
  throw new Error("Unauthorized: userId not found");
@@ -60,12 +79,7 @@ async function getOptionalAuthedUserId(req: Request): Promise<string | null> {
60
79
  const authHeader = req.headers.get("Authorization");
61
80
  if (!authHeader) return null;
62
81
 
63
- const authReq: any = {
64
- headers: {
65
- get: (name: string) => req.headers.get(name),
66
- },
67
- };
68
- const user = await handleToken(authReq, {});
82
+ const user = await readUserFromRequest(req);
69
83
  const userId = user?.userId;
70
84
  return typeof userId === "string" && userId ? userId : null;
71
85
  }
@@ -11,7 +11,7 @@
11
11
  // - 前端展示时做掩码处理(前4后4,中间替换为 ****)。
12
12
 
13
13
  import { authenticateRequest, CORS_HEADERS_AUTH } from "../../auth/utils";
14
- import serverDb from "../../database/server/db";
14
+ import { getServerAuthorityStore } from "../../database/server/db";
15
15
 
16
16
  const SECRETS_KEY_PREFIX = "user-secrets-";
17
17
  const ENC_PREFIX = "enc:v1:";
@@ -81,11 +81,23 @@ function secretsKey(userId: string): string {
81
81
 
82
82
  type EncryptedSecretsMap = Record<string, string>; // values 可能是 enc:v1:... 或历史明文
83
83
 
84
+ const getUserSecretsStore = () => getServerAuthorityStore();
85
+
86
+ function isSecretsNotFoundError(error: unknown): boolean {
87
+ const candidate = error as { code?: string; notFound?: boolean; message?: string } | null;
88
+ return (
89
+ candidate?.code === "LEVEL_NOT_FOUND" ||
90
+ candidate?.notFound === true ||
91
+ candidate?.message === "NotFound"
92
+ );
93
+ }
94
+
84
95
  async function loadRawSecrets(userId: string): Promise<EncryptedSecretsMap> {
96
+ const store = getUserSecretsStore();
85
97
  try {
86
- return (await serverDb.get(secretsKey(userId))) as EncryptedSecretsMap ?? {};
98
+ return ((await store.get(secretsKey(userId))) as EncryptedSecretsMap) ?? {};
87
99
  } catch (e: any) {
88
- if (e.code === "LEVEL_NOT_FOUND") return {};
100
+ if (isSecretsNotFoundError(e)) return {};
89
101
  throw e;
90
102
  }
91
103
  }
@@ -167,7 +179,7 @@ export async function handleSetUserSecret(req: Request): Promise<Response> {
167
179
 
168
180
  const raw = await loadRawSecrets(auth.userId);
169
181
  raw[key] = await encryptValue(value); // 加密后存储
170
- await serverDb.put(secretsKey(auth.userId), raw);
182
+ await getUserSecretsStore().put(secretsKey(auth.userId), raw);
171
183
 
172
184
  return jsonOk({ success: true, key, masked: maskValue(value) });
173
185
  }
@@ -194,7 +206,7 @@ export async function handleDeleteUserSecret(req: Request): Promise<Response> {
194
206
  if (!(key in raw)) return jsonError(404, `密钥 "${key}" 不存在`, "NOT_FOUND");
195
207
 
196
208
  delete raw[key];
197
- await serverDb.put(secretsKey(auth.userId), raw);
209
+ await getUserSecretsStore().put(secretsKey(auth.userId), raw);
198
210
 
199
211
  return jsonOk({ success: true, deleted: key });
200
212
  }
@@ -207,4 +219,3 @@ export async function getUserSecret(userId: string, key: string): Promise<string
207
219
  const secrets = await loadSecrets(userId);
208
220
  return secrets[key] ?? null;
209
221
  }
210
-
@@ -20,7 +20,7 @@ import {
20
20
  type VersionEntityType,
21
21
  } from "./versionStore";
22
22
  import { saveAppCode, getAppRecord } from "./appSandboxHandler";
23
- import serverDb from "../../database/server/db";
23
+ import { getServerAuthorityStore } from "../../database/server/db";
24
24
 
25
25
  const jsonOk = (data: any) =>
26
26
  new Response(JSON.stringify(data), {
@@ -36,6 +36,8 @@ const jsonError = (status: number, message: string, code?: string) =>
36
36
 
37
37
  const VALID_TYPES: VersionEntityType[] = ["app", "doc", "agent"];
38
38
 
39
+ const getVersionHandlerStore = () => getServerAuthorityStore();
40
+
39
41
  async function getAuthUserId(req: Request): Promise<string | Response> {
40
42
  const tokenPayload = await authenticateRequest(req);
41
43
  if (!tokenPayload?.userId) return jsonError(401, "未登录", "UNAUTHORIZED");
@@ -49,13 +51,14 @@ async function checkOwnership(
49
51
  type: VersionEntityType,
50
52
  entityId: string
51
53
  ): Promise<Response | null> {
54
+ const store = getVersionHandlerStore();
52
55
  if (type === "app") {
53
56
  const record = await getAppRecord(entityId);
54
57
  if (!record) return jsonError(404, "应用不存在", "NOT_FOUND");
55
58
  if (record.userId !== userId) return jsonError(403, "无权限", "FORBIDDEN");
56
59
  } else if (type === "agent") {
57
60
  const agentKey = `agent-${userId}-${entityId}`;
58
- const agentRecord = await serverDb.get(agentKey).catch(() => null);
61
+ const agentRecord = await store.get(agentKey).catch(() => null);
59
62
  if (!agentRecord) return jsonError(404, "Agent 不存在或无权限", "NOT_FOUND");
60
63
  }
61
64
  // doc: 前端自己知道 entityId,只要登录即可
@@ -184,16 +187,18 @@ export async function handleVersionRestore(req: Request): Promise<Response> {
184
187
  }
185
188
 
186
189
  if (type === "agent") {
190
+ const store = getVersionHandlerStore();
187
191
  const agentKey = `agent-${userId}-${entityId}`;
188
192
  const restored = { ...record.snapshot, updatedAt: Date.now() };
189
- await serverDb.put(agentKey, restored);
193
+ await store.put(agentKey, restored);
190
194
  saveVersion(type, entityId, restored, { createdBy: userId, label: restoreLabel }).catch(() => {});
191
195
  return jsonOk({ success: true, message: `Agent 已恢复到版本 ${versionId}` });
192
196
  }
193
197
 
194
198
  if (type === "doc") {
199
+ const store = getVersionHandlerStore();
195
200
  const restored = { ...record.snapshot, updatedAt: Date.now() };
196
- await serverDb.put(entityId, restored);
201
+ await store.put(entityId, restored);
197
202
  saveVersion(type, entityId, restored, { createdBy: userId, label: restoreLabel }).catch(() => {});
198
203
  return jsonOk({ success: true, message: `文档已恢复到版本 ${versionId}` });
199
204
  }
@@ -5,13 +5,15 @@
5
5
  // 扫描某实体的所有版本: prefix range version-{type}-{entityId}-
6
6
  // entityType: "app" | "doc" | "agent"
7
7
 
8
- import serverDb from "../../database/server/db";
8
+ import { getServerAuthorityStore } from "../../database/server/db";
9
9
  import { ulid } from "ulid";
10
10
 
11
11
  export type VersionEntityType = "app" | "doc" | "agent";
12
12
 
13
13
  export const VERSION_PREFIX = "version-";
14
14
 
15
+ const getVersionStore = () => getServerAuthorityStore();
16
+
15
17
  export function versionKey(type: VersionEntityType, entityId: string, versionId: string) {
16
18
  return `${VERSION_PREFIX}${type}-${entityId}-${versionId}`;
17
19
  }
@@ -50,6 +52,7 @@ export async function saveVersion(
50
52
  createdAt?: number;
51
53
  }
52
54
  ): Promise<string> {
55
+ const store = getVersionStore();
53
56
  const versionId = opts.versionId ?? ulid();
54
57
  const record: VersionRecord = {
55
58
  versionId,
@@ -62,7 +65,7 @@ export async function saveVersion(
62
65
  snapshot,
63
66
  };
64
67
 
65
- await serverDb.put(versionKey(type, entityId, versionId), record);
68
+ await store.put(versionKey(type, entityId, versionId), record);
66
69
  pruneVersions(type, entityId).catch(() => {});
67
70
  return versionId;
68
71
  }
@@ -72,10 +75,11 @@ export async function listVersions(
72
75
  type: VersionEntityType,
73
76
  entityId: string
74
77
  ): Promise<Omit<VersionRecord, "snapshot">[]> {
78
+ const store = getVersionStore();
75
79
  const prefix = versionRangePrefix(type, entityId);
76
80
  const results: Omit<VersionRecord, "snapshot">[] = [];
77
81
 
78
- for await (const [, value] of serverDb.iterator({
82
+ for await (const [, value] of store.iterator({
79
83
  gte: prefix,
80
84
  lte: prefix + "\xff",
81
85
  reverse: true,
@@ -94,8 +98,9 @@ export async function getVersion(
94
98
  entityId: string,
95
99
  versionId: string
96
100
  ): Promise<VersionRecord | null> {
101
+ const store = getVersionStore();
97
102
  try {
98
- return (await serverDb.get(versionKey(type, entityId, versionId))) as VersionRecord;
103
+ return (await store.get(versionKey(type, entityId, versionId))) as VersionRecord;
99
104
  } catch {
100
105
  return null;
101
106
  }
@@ -106,10 +111,11 @@ export async function pruneVersions(
106
111
  type: VersionEntityType,
107
112
  entityId: string
108
113
  ): Promise<void> {
114
+ const store = getVersionStore();
109
115
  const prefix = versionRangePrefix(type, entityId);
110
116
  const allEntries: { key: string; pinned: boolean }[] = [];
111
117
 
112
- for await (const [key, value] of serverDb.iterator({
118
+ for await (const [key, value] of store.iterator({
113
119
  gte: prefix,
114
120
  lte: prefix + "\xff",
115
121
  })) {
@@ -120,7 +126,7 @@ export async function pruneVersions(
120
126
  if (unpinned.length <= MAX_UNPINNED_VERSIONS) return;
121
127
 
122
128
  const toDelete = unpinned.slice(0, unpinned.length - MAX_UNPINNED_VERSIONS);
123
- await Promise.all(toDelete.map((e) => serverDb.del(e.key)));
129
+ await Promise.all(toDelete.map((e) => store.del(e.key)));
124
130
  }
125
131
 
126
132
  // ── Pin / Unpin 版本 ──────────────────────────────────────────
@@ -130,6 +136,7 @@ export async function pinVersion(
130
136
  versionId: string,
131
137
  pinned: boolean
132
138
  ): Promise<{ ok: boolean; reason?: string }> {
139
+ const store = getVersionStore();
133
140
  const record = await getVersion(type, entityId, versionId);
134
141
  if (!record) return { ok: false, reason: "NOT_FOUND" };
135
142
 
@@ -142,7 +149,7 @@ export async function pinVersion(
142
149
  }
143
150
  }
144
151
 
145
- await serverDb.put(versionKey(type, entityId, versionId), { ...record, pinned });
152
+ await store.put(versionKey(type, entityId, versionId), { ...record, pinned });
146
153
  return { ok: true };
147
154
  }
148
155
 
@@ -152,7 +159,7 @@ export async function deleteVersion(
152
159
  entityId: string,
153
160
  versionId: string
154
161
  ): Promise<void> {
155
- await serverDb.del(versionKey(type, entityId, versionId));
162
+ await getVersionStore().del(versionKey(type, entityId, versionId));
156
163
  }
157
164
 
158
165
  // ── 删除实体所有版本(级联清理,entity 删除时调用)──────────
@@ -160,10 +167,11 @@ export async function deleteVersionsForEntity(
160
167
  type: VersionEntityType,
161
168
  entityId: string
162
169
  ): Promise<void> {
170
+ const store = getVersionStore();
163
171
  const prefix = versionRangePrefix(type, entityId);
164
172
  const keys: string[] = [];
165
173
 
166
- for await (const [key] of serverDb.iterator({
174
+ for await (const [key] of store.iterator({
167
175
  gte: prefix,
168
176
  lte: prefix + "\xff",
169
177
  keys: true,
@@ -172,5 +180,5 @@ export async function deleteVersionsForEntity(
172
180
  keys.push(key as string);
173
181
  }
174
182
 
175
- await Promise.all(keys.map((k) => serverDb.del(k)));
183
+ await Promise.all(keys.map((k) => store.del(k)));
176
184
  }
@@ -1,9 +1,9 @@
1
1
  // packages/server/html/ssrPreload.ts
2
2
  // 职责:根据当前请求路径预取 SSR 数据,并返回页面级 SEO 覆盖信息。
3
3
 
4
- import { createAppStore } from "../../app/store";
5
- import serverDb, { ensureServerDbOpen } from "../../database/server/db";
6
- import { upsertSSREntity } from "../../database/dbSlice";
4
+ import { createAppStore } from "../../app/store";
5
+ import { ensureServerDbOpen, getServerAuthorityStore } from "../../database/server/db";
6
+ import { upsertSSREntity } from "../../database/dbSlice";
7
7
  import { fetchPublicAgents } from "../../ai/agent/server/fetchPublicAgents";
8
8
  import { setSSRPublicAgents } from "../../ai/agent/agentSlice";
9
9
  import { fetchCommunityShares } from "../../share/server/fetchCommunityShares";
@@ -15,6 +15,8 @@ import { DESKTOP_RELEASE_MANIFEST_DB_KEY } from "../../app/constants/desktopRele
15
15
  import { readDesktopReleaseManifest } from "./desktopReleaseManifest.server";
16
16
  import { noloAgentId } from "../../core/init";
17
17
 
18
+ const serverDb = getServerAuthorityStore();
19
+
18
20
  const HOME_PUBLIC_AGENTS_CACHE_TTL_MS = 15 * 1000;
19
21
  let cachedHomePublicAgents:
20
22
  | {
@@ -1,8 +1,7 @@
1
1
  import { CORS_HEADERS_AUTH } from "../../../auth/utils";
2
- import { handleToken } from "../../../auth/server/token";
2
+ import { readUserFromRequest } from "../../../auth/server/token";
3
3
  import { isProduction } from "../../../app/utils/env";
4
- import serverDb from "../../../database/server/db";
5
- import { createResponse } from "../../createResponse";
4
+ import { getServerAuthorityStore } from "../../../database/server/db";
6
5
  import type { PaymentProvider } from "../paymentProvider";
7
6
  import {
8
7
  assignCryptoUsdcBaseAddress,
@@ -29,7 +28,9 @@ const jsonError = (
29
28
  details?: unknown
30
29
  ) => jsonResponse({ error: { message, code, details } }, status);
31
30
 
32
- const readDb = async (key: string) => serverDb.get(key).catch(() => null);
31
+ const getCryptoUsdcBaseStore = () => getServerAuthorityStore();
32
+
33
+ const readDb = async (key: string) => getCryptoUsdcBaseStore().get(key).catch(() => null);
33
34
 
34
35
  export const handleCryptoUsdcBaseConfig = async () => {
35
36
  const config = getCryptoUsdcBaseConfig();
@@ -66,16 +67,18 @@ export const handleCreateCryptoUsdcBaseOrder = async (req: Request) => {
66
67
  );
67
68
  }
68
69
 
69
- const authResult = await handleToken(req, createResponse());
70
- if (authResult instanceof Response) return authResult;
71
- const userId = String(authResult.userId || "");
70
+ const authResult = await readUserFromRequest(req);
71
+ const userId = String(authResult?.userId || "");
72
+ if (!userId) {
73
+ return jsonError(401, "Authentication required.", "AUTH_REQUIRED");
74
+ }
72
75
 
73
76
  const assignment = await assignCryptoUsdcBaseAddress({
74
77
  userId,
75
78
  addressPool: config.depositAddresses,
76
79
  get: readDb,
77
80
  put: async (key, value) => {
78
- await serverDb.put(key, value);
81
+ await getCryptoUsdcBaseStore().put(key, value);
79
82
  },
80
83
  });
81
84
  if (!assignment.ok) {
@@ -1,5 +1,5 @@
1
1
  import { rechargeUserBalance } from "../../../auth/server/recharge";
2
- import serverDb from "../../../database/server/db";
2
+ import { getServerAuthorityStore } from "../../../database/server/db";
3
3
  import {
4
4
  getCryptoUsdcBaseConfig,
5
5
  parseUsdcUnitsToCredits,
@@ -171,6 +171,8 @@ const processedEventKey = (eventId: string) =>
171
171
  `crypto-usdc-base-event-${eventId}`;
172
172
  const checkpointKey = "crypto-usdc-base-checkpoint";
173
173
 
174
+ const getCryptoUsdcBaseScannerStore = () => getServerAuthorityStore();
175
+
174
176
  const rpcCall = async <T>(
175
177
  rpcUrl: string,
176
178
  method: string,
@@ -190,7 +192,7 @@ const rpcCall = async <T>(
190
192
 
191
193
  const getAssignedDepositAddresses = async () => {
192
194
  const assignments: DepositAddressAssignment[] = [];
193
- const iter = serverDb.iterator({
195
+ const iter = getCryptoUsdcBaseScannerStore().iterator({
194
196
  gte: "crypto-usdc-base-address-",
195
197
  lt: "crypto-usdc-base-address-\xff",
196
198
  });
@@ -218,7 +220,7 @@ export const scanCryptoUsdcBaseDeposits = async () => {
218
220
  const toBlock = currentBlock - config.confirmations;
219
221
  if (toBlock <= 0) return { configured: true, fromBlock: null, toBlock, ...emptyStats() };
220
222
 
221
- const checkpoint = (await serverDb.get(checkpointKey).catch(() => null)) as
223
+ const checkpoint = (await getCryptoUsdcBaseScannerStore().get(checkpointKey).catch(() => null)) as
222
224
  | { lastScannedBlock?: number }
223
225
  | null;
224
226
  const fromBlock = checkpoint
@@ -245,13 +247,13 @@ export const scanCryptoUsdcBaseDeposits = async () => {
245
247
  logs,
246
248
  config,
247
249
  loadAssignmentByAddress: async (address) =>
248
- ((await serverDb.get(addressAssignmentKey(address)).catch(() => null)) as
250
+ ((await getCryptoUsdcBaseScannerStore().get(addressAssignmentKey(address)).catch(() => null)) as
249
251
  | DepositAddressAssignment
250
252
  | null),
251
253
  hasProcessedEvent: async (eventId) =>
252
- Boolean(await serverDb.get(processedEventKey(eventId)).catch(() => null)),
254
+ Boolean(await getCryptoUsdcBaseScannerStore().get(processedEventKey(eventId)).catch(() => null)),
253
255
  recordProcessedEvent: async (event) => {
254
- await serverDb.put(processedEventKey(event.eventId), event);
256
+ await getCryptoUsdcBaseScannerStore().put(processedEventKey(event.eventId), event);
255
257
  },
256
258
  creditUser: async (event) =>
257
259
  rechargeUserBalance(
@@ -262,6 +264,9 @@ export const scanCryptoUsdcBaseDeposits = async () => {
262
264
  ),
263
265
  });
264
266
 
265
- await serverDb.put(checkpointKey, { lastScannedBlock: toBlock, updatedAt: Date.now() });
267
+ await getCryptoUsdcBaseScannerStore().put(checkpointKey, {
268
+ lastScannedBlock: toBlock,
269
+ updatedAt: Date.now(),
270
+ });
266
271
  return { configured: true, fromBlock, toBlock, ...stats };
267
272
  };
@@ -1,8 +1,7 @@
1
1
  import { CORS_HEADERS_AUTH } from "../../../auth/utils";
2
- import { handleToken } from "../../../auth/server/token";
2
+ import { readUserFromRequest } from "../../../auth/server/token";
3
3
  import { isProduction } from "../../../app/utils/env";
4
- import serverDb from "../../../database/server/db";
5
- import { createResponse } from "../../createResponse";
4
+ import { getServerAuthorityStore } from "../../../database/server/db";
6
5
  import type { PaymentProvider } from "../paymentProvider";
7
6
  import {
8
7
  assignCryptoUsdtTronAddress,
@@ -29,7 +28,9 @@ const jsonError = (
29
28
  details?: unknown
30
29
  ) => jsonResponse({ error: { message, code, details } }, status);
31
30
 
32
- const readDb = async (key: string) => serverDb.get(key).catch(() => null);
31
+ const getCryptoUsdtTronStore = () => getServerAuthorityStore();
32
+
33
+ const readDb = async (key: string) => getCryptoUsdtTronStore().get(key).catch(() => null);
33
34
 
34
35
  export const handleCryptoUsdtTronConfig = async () => {
35
36
  const config = getCryptoUsdtTronConfig();
@@ -65,16 +66,18 @@ export const handleCreateCryptoUsdtTronOrder = async (req: Request) => {
65
66
  );
66
67
  }
67
68
 
68
- const authResult = await handleToken(req, createResponse());
69
- if (authResult instanceof Response) return authResult;
70
- const userId = String(authResult.userId || "");
69
+ const authResult = await readUserFromRequest(req);
70
+ const userId = String(authResult?.userId || "");
71
+ if (!userId) {
72
+ return jsonError(401, "Authentication required.", "AUTH_REQUIRED");
73
+ }
71
74
 
72
75
  const assignment = await assignCryptoUsdtTronAddress({
73
76
  userId,
74
77
  addressPool: config.depositAddresses,
75
78
  get: readDb,
76
79
  put: async (key, value) => {
77
- await serverDb.put(key, value);
80
+ await getCryptoUsdtTronStore().put(key, value);
78
81
  },
79
82
  });
80
83
  if (!assignment.ok) {
@@ -1,5 +1,5 @@
1
1
  import { rechargeUserBalance } from "../../../auth/server/recharge";
2
- import serverDb from "../../../database/server/db";
2
+ import { getServerAuthorityStore } from "../../../database/server/db";
3
3
  import {
4
4
  getCryptoUsdtTronConfig,
5
5
  parseUsdtUnitsToCredits,
@@ -98,6 +98,8 @@ const processedEventKey = (eventId: string) =>
98
98
  `crypto-usdt-tron-event-${eventId}`;
99
99
  const checkpointKey = "crypto-usdt-tron-checkpoint";
100
100
 
101
+ const getCryptoUsdtTronScannerStore = () => getServerAuthorityStore();
102
+
101
103
  const getTransferContract = (transfer: TronTransferEvent) =>
102
104
  transfer.contract_address || transfer.token_info?.address || "";
103
105
 
@@ -186,7 +188,7 @@ export const processCryptoUsdtTronEvents = async (
186
188
 
187
189
  const getAssignedDepositAddresses = async () => {
188
190
  const assignments: DepositAddressAssignment[] = [];
189
- const iter = serverDb.iterator({
191
+ const iter = getCryptoUsdtTronScannerStore().iterator({
190
192
  gte: "crypto-usdt-tron-address-",
191
193
  lt: "crypto-usdt-tron-address-\xff",
192
194
  });
@@ -233,7 +235,7 @@ export const scanCryptoUsdtTronDeposits = async () => {
233
235
  };
234
236
  }
235
237
 
236
- const checkpoint = (await serverDb.get(checkpointKey).catch(() => null)) as
238
+ const checkpoint = (await getCryptoUsdtTronScannerStore().get(checkpointKey).catch(() => null)) as
237
239
  | { lastScannedTimestamp?: number }
238
240
  | null;
239
241
  const fromTimestamp = checkpoint
@@ -275,13 +277,13 @@ export const scanCryptoUsdtTronDeposits = async () => {
275
277
  events,
276
278
  config,
277
279
  loadAssignmentByAddress: async (address) =>
278
- ((await serverDb.get(addressAssignmentKey(address)).catch(() => null)) as
280
+ ((await getCryptoUsdtTronScannerStore().get(addressAssignmentKey(address)).catch(() => null)) as
279
281
  | DepositAddressAssignment
280
282
  | null),
281
283
  hasProcessedEvent: async (eventId) =>
282
- Boolean(await serverDb.get(processedEventKey(eventId)).catch(() => null)),
284
+ Boolean(await getCryptoUsdtTronScannerStore().get(processedEventKey(eventId)).catch(() => null)),
283
285
  recordProcessedEvent: async (event) => {
284
- await serverDb.put(processedEventKey(event.eventId), event);
286
+ await getCryptoUsdtTronScannerStore().put(processedEventKey(event.eventId), event);
285
287
  },
286
288
  creditUser: async (event) =>
287
289
  rechargeUserBalance(
@@ -305,7 +307,7 @@ export const scanCryptoUsdtTronDeposits = async () => {
305
307
  } while (fingerprint);
306
308
  }
307
309
 
308
- await serverDb.put(checkpointKey, {
310
+ await getCryptoUsdtTronScannerStore().put(checkpointKey, {
309
311
  lastScannedTimestamp: toTimestamp,
310
312
  updatedAt: Date.now(),
311
313
  });