@bsv/overlay-express 2.4.2 → 2.4.9

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 (135) hide show
  1. package/LICENSE.txt +57 -27
  2. package/README.md +141 -56
  3. package/dist/cjs/mod.d.ts +11 -0
  4. package/dist/cjs/mod.d.ts.map +1 -0
  5. package/dist/cjs/mod.js.map +1 -1
  6. package/dist/cjs/package.json +26 -13
  7. package/dist/cjs/src/ArcadeProvider.d.ts +37 -0
  8. package/dist/cjs/src/ArcadeProvider.d.ts.map +1 -0
  9. package/dist/cjs/src/ArcadeProvider.js.map +1 -1
  10. package/dist/cjs/src/BanAwareDiscoveryStorage.d.ts +36 -0
  11. package/dist/cjs/src/BanAwareDiscoveryStorage.d.ts.map +1 -0
  12. package/dist/cjs/src/BanAwareDiscoveryStorage.js +5 -4
  13. package/dist/cjs/src/BanAwareDiscoveryStorage.js.map +1 -1
  14. package/dist/cjs/src/BanAwareLookupWrapper.d.ts +31 -0
  15. package/dist/cjs/src/BanAwareLookupWrapper.d.ts.map +1 -0
  16. package/dist/cjs/src/BanAwareLookupWrapper.js +3 -2
  17. package/dist/cjs/src/BanAwareLookupWrapper.js.map +1 -1
  18. package/dist/cjs/src/BanAwareTopicManager.d.ts +28 -0
  19. package/dist/cjs/src/BanAwareTopicManager.d.ts.map +1 -0
  20. package/dist/cjs/src/BanAwareTopicManager.js +3 -2
  21. package/dist/cjs/src/BanAwareTopicManager.js.map +1 -1
  22. package/dist/cjs/src/BanService.d.ts +81 -0
  23. package/dist/cjs/src/BanService.d.ts.map +1 -0
  24. package/dist/cjs/src/BanService.js.map +1 -1
  25. package/dist/cjs/src/ChaintracksProvider.d.ts +29 -0
  26. package/dist/cjs/src/ChaintracksProvider.d.ts.map +1 -0
  27. package/dist/cjs/src/ChaintracksProvider.js +1 -1
  28. package/dist/cjs/src/ChaintracksProvider.js.map +1 -1
  29. package/dist/cjs/src/JanitorService.d.ts +128 -0
  30. package/dist/cjs/src/JanitorService.d.ts.map +1 -0
  31. package/dist/cjs/src/JanitorService.js +108 -37
  32. package/dist/cjs/src/JanitorService.js.map +1 -1
  33. package/dist/cjs/src/OverlayExpress.d.ts +466 -0
  34. package/dist/cjs/src/OverlayExpress.d.ts.map +1 -0
  35. package/dist/cjs/src/OverlayExpress.js +307 -148
  36. package/dist/cjs/src/OverlayExpress.js.map +1 -1
  37. package/dist/cjs/src/OverlayMonitor.d.ts +197 -0
  38. package/dist/cjs/src/OverlayMonitor.d.ts.map +1 -0
  39. package/dist/cjs/src/OverlayMonitor.js +6 -4
  40. package/dist/cjs/src/OverlayMonitor.js.map +1 -1
  41. package/dist/cjs/src/ProviderChainBroadcaster.d.ts +18 -0
  42. package/dist/cjs/src/ProviderChainBroadcaster.d.ts.map +1 -0
  43. package/dist/cjs/src/ProviderChainBroadcaster.js +7 -3
  44. package/dist/cjs/src/ProviderChainBroadcaster.js.map +1 -1
  45. package/dist/cjs/src/ReorgStream.d.ts +74 -0
  46. package/dist/cjs/src/ReorgStream.d.ts.map +1 -0
  47. package/dist/cjs/src/ReorgStream.js +14 -6
  48. package/dist/cjs/src/ReorgStream.js.map +1 -1
  49. package/dist/cjs/src/generalGuide.md.d.ts +3 -0
  50. package/dist/cjs/src/generalGuide.md.d.ts.map +1 -0
  51. package/dist/cjs/src/generalGuide.md.js.map +1 -1
  52. package/dist/cjs/src/makeUserInterface.d.ts +22 -0
  53. package/dist/cjs/src/makeUserInterface.d.ts.map +1 -0
  54. package/dist/cjs/src/makeUserInterface.js +4 -4
  55. package/dist/cjs/src/makeUserInterface.js.map +1 -1
  56. package/dist/cjs/src/security/edgePolicy.d.ts +57 -0
  57. package/dist/cjs/src/security/edgePolicy.d.ts.map +1 -0
  58. package/dist/cjs/src/security/edgePolicy.js +379 -0
  59. package/dist/cjs/src/security/edgePolicy.js.map +1 -0
  60. package/dist/esm/mod.js.map +1 -1
  61. package/dist/esm/src/ArcadeProvider.js.map +1 -1
  62. package/dist/esm/src/BanAwareDiscoveryStorage.js +5 -4
  63. package/dist/esm/src/BanAwareDiscoveryStorage.js.map +1 -1
  64. package/dist/esm/src/BanAwareLookupWrapper.js +3 -2
  65. package/dist/esm/src/BanAwareLookupWrapper.js.map +1 -1
  66. package/dist/esm/src/BanAwareTopicManager.js +3 -2
  67. package/dist/esm/src/BanAwareTopicManager.js.map +1 -1
  68. package/dist/esm/src/ChaintracksProvider.js +1 -1
  69. package/dist/esm/src/ChaintracksProvider.js.map +1 -1
  70. package/dist/esm/src/JanitorService.js +84 -8
  71. package/dist/esm/src/JanitorService.js.map +1 -1
  72. package/dist/esm/src/OverlayExpress.js +290 -134
  73. package/dist/esm/src/OverlayExpress.js.map +1 -1
  74. package/dist/esm/src/ProviderChainBroadcaster.js +7 -3
  75. package/dist/esm/src/ProviderChainBroadcaster.js.map +1 -1
  76. package/dist/esm/src/ReorgStream.js +14 -6
  77. package/dist/esm/src/ReorgStream.js.map +1 -1
  78. package/dist/esm/src/makeUserInterface.js +3 -4
  79. package/dist/esm/src/makeUserInterface.js.map +1 -1
  80. package/dist/esm/src/security/edgePolicy.js +377 -0
  81. package/dist/esm/src/security/edgePolicy.js.map +1 -0
  82. package/dist/types/mod.d.ts +1 -1
  83. package/dist/types/mod.d.ts.map +1 -1
  84. package/dist/types/src/ArcadeProvider.d.ts.map +1 -1
  85. package/dist/types/src/BanAwareDiscoveryStorage.d.ts.map +1 -1
  86. package/dist/types/src/BanAwareLookupWrapper.d.ts.map +1 -1
  87. package/dist/types/src/BanAwareTopicManager.d.ts.map +1 -1
  88. package/dist/types/src/BanService.d.ts.map +1 -1
  89. package/dist/types/src/ChaintracksProvider.d.ts.map +1 -1
  90. package/dist/types/src/JanitorService.d.ts +14 -1
  91. package/dist/types/src/JanitorService.d.ts.map +1 -1
  92. package/dist/types/src/OverlayExpress.d.ts +48 -2
  93. package/dist/types/src/OverlayExpress.d.ts.map +1 -1
  94. package/dist/types/src/OverlayMonitor.d.ts.map +1 -1
  95. package/dist/types/src/ProviderChainBroadcaster.d.ts.map +1 -1
  96. package/dist/types/src/ReorgStream.d.ts.map +1 -1
  97. package/dist/types/src/generalGuide.md.d.ts +1 -1
  98. package/dist/types/src/generalGuide.md.d.ts.map +1 -1
  99. package/dist/types/src/makeUserInterface.d.ts +1 -2
  100. package/dist/types/src/makeUserInterface.d.ts.map +1 -1
  101. package/dist/types/src/security/edgePolicy.d.ts +57 -0
  102. package/dist/types/src/security/edgePolicy.d.ts.map +1 -0
  103. package/package.json +47 -25
  104. package/dist/cjs/tsconfig.cjs.tsbuildinfo +0 -1
  105. package/dist/esm/tsconfig.esm.tsbuildinfo +0 -1
  106. package/dist/types/tsconfig.types.tsbuildinfo +0 -1
  107. package/mod.ts +0 -47
  108. package/src/ArcadeProvider.ts +0 -232
  109. package/src/BanAwareDiscoveryStorage.ts +0 -91
  110. package/src/BanAwareLookupWrapper.ts +0 -95
  111. package/src/BanAwareTopicManager.ts +0 -87
  112. package/src/BanService.ts +0 -154
  113. package/src/ChaintracksProvider.ts +0 -79
  114. package/src/JanitorService.ts +0 -423
  115. package/src/OverlayExpress.ts +0 -2479
  116. package/src/OverlayMonitor.ts +0 -817
  117. package/src/ProviderChainBroadcaster.ts +0 -108
  118. package/src/ReorgStream.ts +0 -221
  119. package/src/__tests__/BanAwareDiscoveryStorage.test.ts +0 -131
  120. package/src/__tests__/BanAwareLookupWrapper.test.ts +0 -255
  121. package/src/__tests__/BanAwareTopicManager.test.ts +0 -132
  122. package/src/__tests__/BanService.test.ts +0 -310
  123. package/src/__tests__/InMemoryMigrationSource.test.ts +0 -11
  124. package/src/__tests__/JanitorService.test.ts +0 -941
  125. package/src/__tests__/OverlayExpress.test.ts +0 -1300
  126. package/src/__tests__/OverlayMonitor.test.ts +0 -255
  127. package/src/__tests__/OverlayProviders.live.test.ts +0 -43
  128. package/src/__tests__/OverlayProviders.test.ts +0 -123
  129. package/src/__tests__/README.md +0 -105
  130. package/src/__tests__/ReorgStream.test.ts +0 -66
  131. package/src/__tests__/makeUserInterface.test.ts +0 -193
  132. package/src/__tests__/setup.ts +0 -36
  133. package/src/auth-express-middleware.d.ts +0 -16
  134. package/src/generalGuide.md.ts +0 -74
  135. package/src/makeUserInterface.ts +0 -1224
@@ -1,14 +1,14 @@
1
1
  import express from 'express';
2
2
  import bodyParser from 'body-parser';
3
- import { Engine, KnexStorage, KnexStorageMigrations } from '@bsv/overlay';
3
+ import { Engine, KnexStorage, KnexStorageMigrations, serializeErrorForLog, serializeLogValue } from '@bsv/overlay';
4
4
  import { ARC, MerklePath, WhatsOnChain, HTTPSOverlayBroadcastFacilitator, DEFAULT_TESTNET_SLAP_TRACKERS, DEFAULT_SLAP_TRACKERS, Utils, Beef, Transaction, PrivateKey, KeyDeriver } from '@bsv/sdk';
5
5
  import Knex from 'knex';
6
6
  import { MongoClient } from 'mongodb';
7
7
  import makeUserInterface from './makeUserInterface.js';
8
8
  import * as DiscoveryServices from '@bsv/overlay-discovery-services';
9
9
  import chalk from 'chalk';
10
- import util from 'node:util';
11
10
  import { v4 as uuidv4 } from 'uuid';
11
+ import { createHash, timingSafeEqual } from 'node:crypto';
12
12
  import { JanitorService } from './JanitorService.js';
13
13
  import { BanService } from './BanService.js';
14
14
  import { BanAwareLookupWrapper } from './BanAwareLookupWrapper.js';
@@ -20,6 +20,7 @@ import { createAuthMiddleware } from '@bsv/auth-express-middleware';
20
20
  import { ArcadeProvider, isTerminalArcStatus } from './ArcadeProvider.js';
21
21
  import { ProviderChainBroadcaster } from './ProviderChainBroadcaster.js';
22
22
  import { ChaintracksProvider } from './ChaintracksProvider.js';
23
+ import { bodyParserErrorHandler, concurrencyLimit, configureHttpServer, corsPolicy, readBodyLimitBytes, securityHeaders } from './security/edgePolicy.js';
23
24
  /**
24
25
  * In-memory migration source for Knex migrations.
25
26
  * Allows running migrations defined in code rather than files.
@@ -34,7 +35,7 @@ class InMemoryMigrationSource {
34
35
  * @param loadExtensions - Array of file extensions to filter by (not used here)
35
36
  * @returns Promise resolving to the array of migrations
36
37
  */
37
- async getMigrations(loadExtensions) {
38
+ async getMigrations(_loadExtensions) {
38
39
  return this.migrations;
39
40
  }
40
41
  /**
@@ -54,13 +55,33 @@ class InMemoryMigrationSource {
54
55
  return await Promise.resolve(migration);
55
56
  }
56
57
  }
58
+ class PublicRequestError extends Error {
59
+ constructor(message) {
60
+ super(message);
61
+ this.name = 'PublicRequestError';
62
+ }
63
+ }
64
+ function publicErrorMessage(error, fallback = 'Request could not be processed') {
65
+ return error instanceof PublicRequestError ? error.message : fallback;
66
+ }
67
+ function secretMatches(provided, expected) {
68
+ const providedDigest = createHash('sha256').update(provided, 'utf8').digest();
69
+ const expectedDigest = createHash('sha256').update(expected, 'utf8').digest();
70
+ return timingSafeEqual(providedDigest, expectedDigest);
71
+ }
57
72
  function parseTopicsHeader(header) {
58
73
  const value = header.trim();
59
- const parsed = value.startsWith('[')
60
- ? JSON.parse(value)
61
- : value.split(',').map(topic => topic.trim());
74
+ let parsed;
75
+ try {
76
+ parsed = value.startsWith('[')
77
+ ? JSON.parse(value)
78
+ : value.split(',').map(topic => topic.trim());
79
+ }
80
+ catch {
81
+ throw new PublicRequestError('Invalid x-topics header: expected a comma-separated list or JSON string array');
82
+ }
62
83
  if (!Array.isArray(parsed) || parsed.some(topic => typeof topic !== 'string' || topic.length === 0)) {
63
- throw new TypeError('Invalid x-topics header: expected a comma-separated list or JSON string array');
84
+ throw new PublicRequestError('Invalid x-topics header: expected a comma-separated list or JSON string array');
64
85
  }
65
86
  return parsed;
66
87
  }
@@ -151,7 +172,8 @@ export default class OverlayExpress {
151
172
  janitorConfig = {
152
173
  requestTimeoutMs: 10000, // 10 seconds
153
174
  hostDownRevokeScore: 3,
154
- autoBanOnRemoval: true
175
+ autoBanOnRemoval: true,
176
+ allowPrivateHosts: false
155
177
  };
156
178
  // Ban service for persistent domain/outpoint blocking
157
179
  banService;
@@ -159,6 +181,8 @@ export default class OverlayExpress {
159
181
  adminIdentityKey;
160
182
  // Server-side wallet (WalletInterface) used for BSV mutual authentication
161
183
  serverWallet;
184
+ // Optional shared store for BSV mutual-auth sessions.
185
+ authSessionManager;
162
186
  // Server start time for uptime tracking
163
187
  startTime;
164
188
  // Health endpoint configuration
@@ -170,6 +194,26 @@ export default class OverlayExpress {
170
194
  healthChecks = [];
171
195
  // Lifecycle marker for readiness/liveness reporting
172
196
  isListening = false;
197
+ // Active HTTP server, retained so timeout policy is observable and the
198
+ // process can add graceful-close handling without replacing app.listen().
199
+ server;
200
+ closePromise;
201
+ edgePolicyConfig = {
202
+ environmentPrefix: 'OVERLAY',
203
+ jsonBodyLimitBytes: 8 * 1024 * 1024,
204
+ binaryBodyLimitBytes: 64 * 1024 * 1024,
205
+ maxConcurrentRequests: 200,
206
+ http: {
207
+ requestTimeoutMs: 2 * 60 * 1000,
208
+ headersTimeoutMs: 15_000,
209
+ keepAliveTimeoutMs: 5_000,
210
+ socketTimeoutMs: 2 * 60 * 1000,
211
+ maxRequestsPerSocket: 1_000
212
+ },
213
+ securityHeaders: {
214
+ contentSecurityPolicy: "default-src 'none'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; img-src 'self' data: https://bsvblockchain.org; connect-src 'self' https:; font-src 'self' https://cdn.jsdelivr.net; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
215
+ }
216
+ };
173
217
  /**
174
218
  * Constructs an instance of OverlayExpress.
175
219
  * @param name - The name of the service
@@ -214,6 +258,7 @@ export default class OverlayExpress {
214
258
  * - requestTimeoutMs: Timeout for health check requests (default: 10000ms)
215
259
  * - hostDownRevokeScore: Number of consecutive failures before deleting output (default: 3)
216
260
  * - autoBanOnRemoval: Whether to auto-ban domains when removed by janitor (default: true)
261
+ * - allowPrivateHosts: Permit private/HTTP targets for isolated local development (default: false)
217
262
  */
218
263
  configureJanitor(config) {
219
264
  this.janitorConfig = {
@@ -232,6 +277,30 @@ export default class OverlayExpress {
232
277
  };
233
278
  this.logger.log(chalk.blue('Health reporting has been configured.'));
234
279
  }
280
+ /**
281
+ * Configures explicit browser origins and bounded request/resource policy.
282
+ * Public cross-origin access is the default; pass allowedOrigins or set
283
+ * OVERLAY_CORS_MODE=allowlist to restrict browser callers.
284
+ */
285
+ configureEdgePolicy(config) {
286
+ const { http, securityHeaders: headerConfig, ...topLevel } = config;
287
+ const definedTopLevel = Object.fromEntries(Object.entries(topLevel).filter(([, value]) => value !== undefined));
288
+ const definedHttp = Object.fromEntries(Object.entries(http ?? {}).filter(([, value]) => value !== undefined));
289
+ const definedHeaders = Object.fromEntries(Object.entries(headerConfig ?? {}).filter(([, value]) => value !== undefined));
290
+ this.edgePolicyConfig = {
291
+ ...this.edgePolicyConfig,
292
+ ...definedTopLevel,
293
+ http: {
294
+ ...this.edgePolicyConfig.http,
295
+ ...definedHttp
296
+ },
297
+ securityHeaders: {
298
+ ...this.edgePolicyConfig.securityHeaders,
299
+ ...definedHeaders
300
+ }
301
+ };
302
+ this.logger.log(chalk.blue('HTTP edge policy has been configured.'));
303
+ }
235
304
  /**
236
305
  * Registers an application-specific health check.
237
306
  */
@@ -255,6 +324,15 @@ export default class OverlayExpress {
255
324
  this.adminIdentityKey = identityKey;
256
325
  this.logger.log(chalk.blue('Admin identity key has been configured.'));
257
326
  }
327
+ /**
328
+ * Configures BRC-103 session storage for the administrative mutual-auth
329
+ * middleware. Horizontally scaled services should supply a shared
330
+ * AsyncSessionManager rather than use the default process-local store.
331
+ */
332
+ configureAuthSessionManager(sessionManager) {
333
+ this.authSessionManager = sessionManager;
334
+ this.logger.log(chalk.blue('BSV authentication session manager has been configured.'));
335
+ }
258
336
  /**
259
337
  * Configures the logger to be used by the server.
260
338
  * @param logger - A logger object (e.g., console)
@@ -760,7 +838,8 @@ export default class OverlayExpress {
760
838
  requestTimeoutMs: this.janitorConfig.requestTimeoutMs,
761
839
  hostDownRevokeScore: this.janitorConfig.hostDownRevokeScore,
762
840
  banService: this.banService,
763
- autoBanOnRemoval: this.janitorConfig.autoBanOnRemoval
841
+ autoBanOnRemoval: this.janitorConfig.autoBanOnRemoval,
842
+ allowPrivateHosts: this.janitorConfig.allowPrivateHosts
764
843
  });
765
844
  }
766
845
  /** Ban a domain and remove all its SHIP/SLAP records from MongoDB. */
@@ -829,11 +908,12 @@ export default class OverlayExpress {
829
908
  }
830
909
  async runHealthCheck(definition) {
831
910
  const startedAt = Date.now();
911
+ let timeout;
832
912
  try {
833
913
  const result = ((await Promise.race([
834
914
  Promise.resolve(definition.handler()),
835
915
  new Promise((_, reject) => {
836
- setTimeout(() => reject(new Error(`Timed out after ${this.healthConfig.timeoutMs}ms`)), this.healthConfig.timeoutMs);
916
+ timeout = setTimeout(() => reject(new Error(`Timed out after ${this.healthConfig.timeoutMs}ms`)), this.healthConfig.timeoutMs);
837
917
  })
838
918
  ])) ?? {});
839
919
  return {
@@ -847,15 +927,24 @@ export default class OverlayExpress {
847
927
  };
848
928
  }
849
929
  catch (error) {
930
+ this.logger.error({
931
+ operation: 'overlay.health_check',
932
+ check: definition.name,
933
+ error
934
+ });
850
935
  return {
851
936
  name: definition.name,
852
937
  scope: definition.scope,
853
938
  critical: definition.critical,
854
939
  status: 'error',
855
- message: error instanceof Error ? error.message : 'Unknown health-check error',
940
+ message: 'Health check failed',
856
941
  durationMs: Date.now() - startedAt
857
942
  };
858
943
  }
944
+ finally {
945
+ if (timeout !== undefined)
946
+ clearTimeout(timeout);
947
+ }
859
948
  }
860
949
  async collectHealthReport(mode) {
861
950
  const definitions = [
@@ -967,7 +1056,11 @@ export default class OverlayExpress {
967
1056
  },
968
1057
  checks: this.healthConfig.includeDetails
969
1058
  ? checks
970
- : checks.map(({ details, ...check }) => check),
1059
+ : checks.map(check => {
1060
+ const publicCheck = { ...check };
1061
+ delete publicCheck.details;
1062
+ return publicCheck;
1063
+ }),
971
1064
  context
972
1065
  };
973
1066
  return report;
@@ -975,20 +1068,83 @@ export default class OverlayExpress {
975
1068
  /**
976
1069
  * Renders a request or response body for verbose logging, truncating overly long payloads.
977
1070
  */
978
- formatBodyForLog(body, tooLongLabel, okPrefix) {
979
- let bodyString;
980
- if (typeof body === 'object') {
981
- bodyString = JSON.stringify(body, null, 2);
1071
+ formatBodyForLog(body, okPrefix) {
1072
+ if (Buffer.isBuffer(body)) {
1073
+ return chalk.green(`${okPrefix} binary body (${serializeLogValue(body.byteLength)} bytes)`);
982
1074
  }
983
- else if (Buffer.isBuffer(body)) {
984
- bodyString = body.toString('utf8');
1075
+ if (typeof body === 'string') {
1076
+ return chalk.green(`${okPrefix} string body (${serializeLogValue(Buffer.byteLength(body, 'utf8'))} bytes)`);
985
1077
  }
986
- else {
987
- bodyString = String(body);
1078
+ if (body != null && typeof body === 'object') {
1079
+ const keys = Array.isArray(body) ? body.length : Object.keys(body).length;
1080
+ return chalk.green(`${okPrefix} structured body (${serializeLogValue(keys)} top-level item(s))`);
1081
+ }
1082
+ return chalk.green(`${okPrefix} type=${serializeLogValue(typeof body)}`);
1083
+ }
1084
+ redactHeadersForLog(headers) {
1085
+ const sensitiveHeader = /authorization|cookie|token|secret|payment|signature|nonce/i;
1086
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [
1087
+ name,
1088
+ sensitiveHeader.test(name) ? '[REDACTED]' : value
1089
+ ]));
1090
+ }
1091
+ arcCallbackRequestToken(req) {
1092
+ const authorization = req.headers.authorization;
1093
+ const headerToken = Array.isArray(authorization) ? authorization[0] : authorization;
1094
+ if (typeof headerToken === 'string' && headerToken.startsWith('Bearer ')) {
1095
+ return headerToken.slice('Bearer '.length);
1096
+ }
1097
+ return headerToken;
1098
+ }
1099
+ arcCallbackAuthorized(req) {
1100
+ if (typeof this.arcCallbackToken !== 'string' || this.arcCallbackToken.length === 0) {
1101
+ return true;
1102
+ }
1103
+ const callbackHeader = req.headers['x-callback-token'];
1104
+ const callbackToken = Array.isArray(callbackHeader) ? callbackHeader[0] : callbackHeader;
1105
+ return (this.arcCallbackRequestToken(req) === this.arcCallbackToken ||
1106
+ callbackToken === this.arcCallbackToken);
1107
+ }
1108
+ async processArcIngest(engine, req, res) {
1109
+ if (!this.arcCallbackAuthorized(req)) {
1110
+ return res.status(401).json({ status: 'error', message: 'Unauthorized callback' });
1111
+ }
1112
+ const { txid, merklePath: merklePathHex, blockHeight, txStatus, extraInfo, competingTxs, topic } = req.body;
1113
+ if (typeof txid !== 'string' || txid === '') {
1114
+ throw new PublicRequestError('Provider callback is missing txid');
1115
+ }
1116
+ if (isTerminalArcStatus(txStatus, extraInfo)) {
1117
+ const report = await engine.evictAppliedTransaction(txid, {
1118
+ topic: typeof topic === 'string' ? topic : undefined,
1119
+ reason: `${txStatus ?? ''} ${extraInfo ?? ''}`.trim()
1120
+ });
1121
+ this.logger.warn({
1122
+ operation: 'overlay.provider_callback',
1123
+ outcome: 'terminal_evicted',
1124
+ txid,
1125
+ txStatus,
1126
+ competingTxs,
1127
+ report
1128
+ });
1129
+ return res.status(200).json({
1130
+ status: 'success',
1131
+ message: 'Terminal transaction status processed',
1132
+ data: { ...report, txStatus, competingTxs }
1133
+ });
1134
+ }
1135
+ if (typeof merklePathHex !== 'string' || merklePathHex === '') {
1136
+ return res
1137
+ .status(202)
1138
+ .json({ status: 'success', message: 'Transaction status received without proof' });
988
1139
  }
989
- return bodyString.length > 280
990
- ? chalk.yellow(`(${tooLongLabel}, length: ${String(bodyString.length)} characters)`)
991
- : chalk.green(`${okPrefix}\n${bodyString}`);
1140
+ await engine.handleNewMerkleProof(txid, MerklePath.fromHex(merklePathHex), blockHeight);
1141
+ this.logger.log({
1142
+ operation: 'overlay.provider_callback',
1143
+ outcome: 'proof_ingested',
1144
+ txid,
1145
+ blockHeight
1146
+ });
1147
+ return res.status(200).json({ status: 'success', message: 'Transaction status updated' });
992
1148
  }
993
1149
  /**
994
1150
  * Installs middleware that verbosely logs incoming requests and outgoing responses.
@@ -997,13 +1153,11 @@ export default class OverlayExpress {
997
1153
  this.app.use((req, res, next) => {
998
1154
  const startTime = Date.now();
999
1155
  // Log incoming request details
1000
- this.logger.log(chalk.magenta.bold(`Incoming Request: ${String(req.method)} ${String(req.originalUrl)}`));
1001
- // Pretty-print headers
1002
- this.logger.log(chalk.cyan('Headers:'));
1003
- this.logger.log(util.inspect(req.headers, { colors: true, depth: null }));
1156
+ this.logger.log(chalk.magenta.bold(`Incoming Request: method=${serializeLogValue(req.method)} url=${serializeLogValue(req.originalUrl)}`));
1157
+ this.logger.log(chalk.cyan(`Headers: ${serializeLogValue(this.redactHeadersForLog(req.headers))}`));
1004
1158
  // Handle request body
1005
1159
  if (req.body != null && Object.keys(req.body).length > 0) {
1006
- this.logger.log(this.formatBodyForLog(req.body, 'Body too long to display', 'Request Body:'));
1160
+ this.logger.log(this.formatBodyForLog(req.body, 'Request Body:'));
1007
1161
  }
1008
1162
  // Intercept the res.send method to log responses
1009
1163
  const originalSend = res.send;
@@ -1015,12 +1169,11 @@ export default class OverlayExpress {
1015
1169
  // Log outgoing response details after the response is finished
1016
1170
  res.on('finish', () => {
1017
1171
  const duration = Date.now() - startTime;
1018
- this.logger.log(chalk.magenta.bold(`Outgoing Response: ${String(req.method)} ${String(req.originalUrl)} - Status: ${String(res.statusCode)} - Duration: ${String(duration)}ms`));
1019
- this.logger.log(chalk.cyan('Response Headers:'));
1020
- this.logger.log(util.inspect(res.getHeaders(), { colors: true, depth: null }));
1172
+ this.logger.log(chalk.magenta.bold(`Outgoing Response: method=${serializeLogValue(req.method)} url=${serializeLogValue(req.originalUrl)} status=${serializeLogValue(res.statusCode)} durationMs=${serializeLogValue(duration)}`));
1173
+ this.logger.log(chalk.cyan(`Response Headers: ${serializeLogValue(this.redactHeadersForLog(res.getHeaders()))}`));
1021
1174
  // Handle response body
1022
1175
  if (responseBody != null) {
1023
- this.logger.log(this.formatBodyForLog(responseBody, 'Response body too long to display', 'Response Body:'));
1176
+ this.logger.log(this.formatBodyForLog(responseBody, 'Response Body:'));
1024
1177
  }
1025
1178
  });
1026
1179
  next();
@@ -1034,25 +1187,30 @@ export default class OverlayExpress {
1034
1187
  const engine = this.ensureEngine();
1035
1188
  const knex = this.ensureKnex();
1036
1189
  this.startTime = new Date();
1037
- this.app.use(bodyParser.json({ limit: '1gb', type: 'application/json' }));
1038
- this.app.use(bodyParser.raw({ limit: '1gb', type: 'application/octet-stream' }));
1190
+ const edgePolicy = this.edgePolicyConfig;
1191
+ this.app.disable('x-powered-by');
1192
+ this.app.use(securityHeaders({
1193
+ environmentPrefix: edgePolicy.environmentPrefix,
1194
+ ...edgePolicy.securityHeaders
1195
+ }));
1196
+ this.app.use(corsPolicy({
1197
+ environmentPrefix: edgePolicy.environmentPrefix,
1198
+ allowedOrigins: edgePolicy.allowedOrigins,
1199
+ methods: ['GET', 'POST', 'OPTIONS']
1200
+ }));
1201
+ this.app.use(concurrencyLimit(edgePolicy.environmentPrefix, edgePolicy.maxConcurrentRequests));
1202
+ this.app.use(bodyParser.json({
1203
+ limit: readBodyLimitBytes(`${edgePolicy.environmentPrefix}_JSON`, edgePolicy.jsonBodyLimitBytes),
1204
+ type: 'application/json'
1205
+ }));
1206
+ this.app.use(bodyParser.raw({
1207
+ limit: readBodyLimitBytes(`${edgePolicy.environmentPrefix}_BINARY`, edgePolicy.binaryBodyLimitBytes),
1208
+ type: 'application/octet-stream'
1209
+ }));
1210
+ this.app.use(bodyParserErrorHandler);
1039
1211
  if (this.verboseRequestLogging) {
1040
1212
  this.setupVerboseRequestLogging();
1041
1213
  }
1042
- // Enable CORS
1043
- this.app.use((req, res, next) => {
1044
- res.header('Access-Control-Allow-Origin', '*');
1045
- res.header('Access-Control-Allow-Headers', '*');
1046
- res.header('Access-Control-Allow-Methods', '*');
1047
- res.header('Access-Control-Expose-Headers', '*');
1048
- res.header('Access-Control-Allow-Private-Network', 'true');
1049
- if (req.method === 'OPTIONS') {
1050
- res.sendStatus(200);
1051
- }
1052
- else {
1053
- next();
1054
- }
1055
- });
1056
1214
  // Serve a static documentation site or user interface
1057
1215
  this.app.get('/', (req, res) => {
1058
1216
  res.set('content-type', 'text/html');
@@ -1068,9 +1226,10 @@ export default class OverlayExpress {
1068
1226
  const report = await this.collectHealthReport('live');
1069
1227
  return res.status(report.live ? 200 : 503).json(report);
1070
1228
  })().catch((error) => {
1229
+ this.logger.error({ operation: 'overlay.health_live', error });
1071
1230
  res.status(500).json({
1072
1231
  status: 'error',
1073
- message: error instanceof Error ? error.message : 'Unexpected error'
1232
+ message: 'Health report unavailable'
1074
1233
  });
1075
1234
  });
1076
1235
  });
@@ -1080,9 +1239,10 @@ export default class OverlayExpress {
1080
1239
  const report = await this.collectHealthReport('ready');
1081
1240
  return res.status(report.ready ? 200 : 503).json(report);
1082
1241
  })().catch((error) => {
1242
+ this.logger.error({ operation: 'overlay.health_ready', error });
1083
1243
  res.status(500).json({
1084
1244
  status: 'error',
1085
- message: error instanceof Error ? error.message : 'Unexpected error'
1245
+ message: 'Health report unavailable'
1086
1246
  });
1087
1247
  });
1088
1248
  });
@@ -1092,9 +1252,10 @@ export default class OverlayExpress {
1092
1252
  const report = await this.collectHealthReport('full');
1093
1253
  return res.status(report.ready ? 200 : 503).json(report);
1094
1254
  })().catch((error) => {
1255
+ this.logger.error({ operation: 'overlay.health_full', error });
1095
1256
  res.status(500).json({
1096
1257
  status: 'error',
1097
- message: error instanceof Error ? error.message : 'Unexpected error'
1258
+ message: 'Health report unavailable'
1098
1259
  });
1099
1260
  });
1100
1261
  });
@@ -1109,7 +1270,7 @@ export default class OverlayExpress {
1109
1270
  catch (error) {
1110
1271
  return res.status(400).json({
1111
1272
  status: 'error',
1112
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1273
+ message: publicErrorMessage(error)
1113
1274
  });
1114
1275
  }
1115
1276
  })().catch(() => {
@@ -1129,7 +1290,7 @@ export default class OverlayExpress {
1129
1290
  catch (error) {
1130
1291
  return res.status(400).json({
1131
1292
  status: 'error',
1132
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1293
+ message: publicErrorMessage(error)
1133
1294
  });
1134
1295
  }
1135
1296
  })().catch(() => {
@@ -1152,7 +1313,7 @@ export default class OverlayExpress {
1152
1313
  catch (error) {
1153
1314
  return res.status(400).json({
1154
1315
  status: 'error',
1155
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1316
+ message: publicErrorMessage(error)
1156
1317
  });
1157
1318
  }
1158
1319
  })().catch(() => {
@@ -1174,7 +1335,7 @@ export default class OverlayExpress {
1174
1335
  catch (error) {
1175
1336
  return res.status(400).json({
1176
1337
  status: 'error',
1177
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1338
+ message: publicErrorMessage(error)
1178
1339
  });
1179
1340
  }
1180
1341
  })().catch(() => {
@@ -1193,12 +1354,12 @@ export default class OverlayExpress {
1193
1354
  const topicsHeader = req.headers['x-topics'];
1194
1355
  const includesOffChain = req.headers['x-includes-off-chain-values'] === 'true';
1195
1356
  if (typeof topicsHeader !== 'string') {
1196
- throw new TypeError('Missing x-topics header');
1357
+ throw new PublicRequestError('Missing x-topics header');
1197
1358
  }
1198
1359
  const topics = parseTopicsHeader(topicsHeader);
1199
1360
  const body = req.body;
1200
1361
  if (body == null || typeof body[Symbol.iterator] !== 'function' || body.length === 0) {
1201
- throw new TypeError('Missing or empty BEEF body');
1362
+ throw new PublicRequestError('Missing or empty BEEF body');
1202
1363
  }
1203
1364
  let offChainValues;
1204
1365
  let beef = Array.from(body);
@@ -1224,10 +1385,10 @@ export default class OverlayExpress {
1224
1385
  }
1225
1386
  }
1226
1387
  catch (error) {
1227
- console.error(chalk.red('Error in /submit:'), error);
1388
+ this.logger.error(chalk.red(`Error in /submit: error=${serializeErrorForLog(error)}`));
1228
1389
  return res.status(400).json({
1229
1390
  status: 'error',
1230
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1391
+ message: publicErrorMessage(error)
1231
1392
  });
1232
1393
  }
1233
1394
  })().catch(() => {
@@ -1286,10 +1447,10 @@ export default class OverlayExpress {
1286
1447
  return res.status(200).send(Buffer.from(writer.toArray()));
1287
1448
  }
1288
1449
  catch (error) {
1289
- console.error(chalk.red('Error in /lookup:'), error);
1450
+ this.logger.error(chalk.red(`Error in /lookup: error=${serializeErrorForLog(error)}`));
1290
1451
  return res.status(400).json({
1291
1452
  status: 'error',
1292
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1453
+ message: publicErrorMessage(error)
1293
1454
  });
1294
1455
  }
1295
1456
  })().catch(() => {
@@ -1306,63 +1467,13 @@ export default class OverlayExpress {
1306
1467
  ;
1307
1468
  (async () => {
1308
1469
  try {
1309
- if (typeof this.arcCallbackToken === 'string' && this.arcCallbackToken.length > 0) {
1310
- const authorization = req.headers.authorization;
1311
- const headerToken = Array.isArray(authorization) ? authorization[0] : authorization;
1312
- const xCallbackToken = req.headers['x-callback-token'];
1313
- const callbackToken = Array.isArray(xCallbackToken) ? xCallbackToken[0] : xCallbackToken;
1314
- const bearerToken = typeof headerToken === 'string' && headerToken.startsWith('Bearer ')
1315
- ? headerToken.slice('Bearer '.length)
1316
- : headerToken;
1317
- if (bearerToken !== this.arcCallbackToken && callbackToken !== this.arcCallbackToken) {
1318
- return res.status(401).json({ status: 'error', message: 'Unauthorized callback' });
1319
- }
1320
- }
1321
- const { txid, merklePath: merklePathHex, blockHeight, txStatus, extraInfo, competingTxs, topic } = req.body;
1322
- if (typeof txid !== 'string' || txid === '') {
1323
- throw new TypeError('Provider callback is missing txid');
1324
- }
1325
- if (isTerminalArcStatus(txStatus, extraInfo)) {
1326
- const report = await engine.evictAppliedTransaction(txid, {
1327
- topic: typeof topic === 'string' ? topic : undefined,
1328
- reason: `${txStatus ?? ''} ${extraInfo ?? ''}`.trim()
1329
- });
1330
- this.logger.warn({
1331
- operation: 'overlay.provider_callback',
1332
- outcome: 'terminal_evicted',
1333
- txid,
1334
- txStatus,
1335
- competingTxs,
1336
- report
1337
- });
1338
- return res.status(200).json({
1339
- status: 'success',
1340
- message: 'Terminal transaction status processed',
1341
- data: {
1342
- ...report,
1343
- txStatus,
1344
- competingTxs
1345
- }
1346
- });
1347
- }
1348
- if (typeof merklePathHex !== 'string' || merklePathHex === '') {
1349
- return res.status(202).json({ status: 'success', message: 'Transaction status received without proof' });
1350
- }
1351
- const merklePath = MerklePath.fromHex(merklePathHex);
1352
- await engine.handleNewMerkleProof(txid, merklePath, blockHeight);
1353
- this.logger.log({
1354
- operation: 'overlay.provider_callback',
1355
- outcome: 'proof_ingested',
1356
- txid,
1357
- blockHeight
1358
- });
1359
- return res.status(200).json({ status: 'success', message: 'Transaction status updated' });
1470
+ return await this.processArcIngest(engine, req, res);
1360
1471
  }
1361
1472
  catch (error) {
1362
- console.error(chalk.red('Error in /arc-ingest:'), error);
1473
+ this.logger.error(chalk.red(`Error in /arc-ingest: error=${serializeErrorForLog(error)}`));
1363
1474
  return res.status(400).json({
1364
1475
  status: 'error',
1365
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1476
+ message: publicErrorMessage(error)
1366
1477
  });
1367
1478
  }
1368
1479
  })().catch(() => {
@@ -1390,7 +1501,7 @@ export default class OverlayExpress {
1390
1501
  console.error(chalk.red('Error in /requestSyncResponse:'), error);
1391
1502
  return res.status(400).json({
1392
1503
  status: 'error',
1393
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1504
+ message: publicErrorMessage(error)
1394
1505
  });
1395
1506
  }
1396
1507
  })().catch(() => {
@@ -1412,7 +1523,7 @@ export default class OverlayExpress {
1412
1523
  console.error(chalk.red('Error in /requestForeignGASPNode:'), error);
1413
1524
  return res.status(400).json({
1414
1525
  status: 'error',
1415
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1526
+ message: publicErrorMessage(error)
1416
1527
  });
1417
1528
  }
1418
1529
  })().catch(() => {
@@ -1431,7 +1542,7 @@ export default class OverlayExpress {
1431
1542
  const readBasmTopic = (req) => {
1432
1543
  const header = req.headers['x-bsv-topic'];
1433
1544
  if (typeof header !== 'string' || header.length === 0) {
1434
- throw new TypeError('Missing x-bsv-topic header');
1545
+ throw new PublicRequestError('Missing x-bsv-topic header');
1435
1546
  }
1436
1547
  return header;
1437
1548
  };
@@ -1453,7 +1564,7 @@ export default class OverlayExpress {
1453
1564
  console.error(chalk.red(`Error in ${path}:`), error);
1454
1565
  return res.status(400).json({
1455
1566
  status: 'error',
1456
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1567
+ message: publicErrorMessage(error)
1457
1568
  });
1458
1569
  }
1459
1570
  })().catch(() => {
@@ -1463,7 +1574,7 @@ export default class OverlayExpress {
1463
1574
  };
1464
1575
  const requireTxids = (value) => {
1465
1576
  if (!Array.isArray(value) || !value.every(txid => typeof txid === 'string')) {
1466
- throw new TypeError('txids must be an array of strings');
1577
+ throw new PublicRequestError('txids must be an array of strings');
1467
1578
  }
1468
1579
  return value;
1469
1580
  };
@@ -1496,6 +1607,7 @@ export default class OverlayExpress {
1496
1607
  if (this.serverWallet !== undefined) {
1497
1608
  const bsvAuth = createAuthMiddleware({
1498
1609
  wallet: this.serverWallet,
1610
+ sessionManager: this.authSessionManager,
1499
1611
  allowUnauthenticated: true
1500
1612
  });
1501
1613
  this.app.use(bsvAuth);
@@ -1522,7 +1634,7 @@ export default class OverlayExpress {
1522
1634
  const authHeader = req.headers.authorization;
1523
1635
  if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {
1524
1636
  const token = authHeader.substring('Bearer '.length);
1525
- if (token === this.adminToken) {
1637
+ if (secretMatches(token, this.adminToken)) {
1526
1638
  next();
1527
1639
  return;
1528
1640
  }
@@ -1579,7 +1691,7 @@ export default class OverlayExpress {
1579
1691
  catch (error) {
1580
1692
  return res.status(400).json({
1581
1693
  status: 'error',
1582
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1694
+ message: publicErrorMessage(error)
1583
1695
  });
1584
1696
  }
1585
1697
  })().catch(() => {
@@ -1622,7 +1734,7 @@ export default class OverlayExpress {
1622
1734
  catch (error) {
1623
1735
  return res.status(400).json({
1624
1736
  status: 'error',
1625
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1737
+ message: publicErrorMessage(error)
1626
1738
  });
1627
1739
  }
1628
1740
  })().catch(() => {
@@ -1665,7 +1777,7 @@ export default class OverlayExpress {
1665
1777
  catch (error) {
1666
1778
  return res.status(400).json({
1667
1779
  status: 'error',
1668
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1780
+ message: publicErrorMessage(error)
1669
1781
  });
1670
1782
  }
1671
1783
  })().catch(() => {
@@ -1690,7 +1802,7 @@ export default class OverlayExpress {
1690
1802
  catch (error) {
1691
1803
  return res.status(400).json({
1692
1804
  status: 'error',
1693
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1805
+ message: publicErrorMessage(error)
1694
1806
  });
1695
1807
  }
1696
1808
  })().catch(() => {
@@ -1722,7 +1834,7 @@ export default class OverlayExpress {
1722
1834
  catch (error) {
1723
1835
  return res.status(400).json({
1724
1836
  status: 'error',
1725
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1837
+ message: publicErrorMessage(error)
1726
1838
  });
1727
1839
  }
1728
1840
  })().catch(() => {
@@ -1752,7 +1864,7 @@ export default class OverlayExpress {
1752
1864
  catch (error) {
1753
1865
  return res.status(400).json({
1754
1866
  status: 'error',
1755
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1867
+ message: publicErrorMessage(error)
1756
1868
  });
1757
1869
  }
1758
1870
  })().catch(() => {
@@ -1777,7 +1889,7 @@ export default class OverlayExpress {
1777
1889
  catch (error) {
1778
1890
  return res.status(400).json({
1779
1891
  status: 'error',
1780
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1892
+ message: publicErrorMessage(error)
1781
1893
  });
1782
1894
  }
1783
1895
  })().catch(() => {
@@ -1819,7 +1931,7 @@ export default class OverlayExpress {
1819
1931
  catch (error) {
1820
1932
  return res.status(400).json({
1821
1933
  status: 'error',
1822
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1934
+ message: publicErrorMessage(error)
1823
1935
  });
1824
1936
  }
1825
1937
  })().catch(() => {
@@ -1840,7 +1952,7 @@ export default class OverlayExpress {
1840
1952
  console.error(chalk.red('Error in /admin/syncAdvertisements:'), error);
1841
1953
  return res.status(400).json({
1842
1954
  status: 'error',
1843
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1955
+ message: publicErrorMessage(error)
1844
1956
  });
1845
1957
  }
1846
1958
  })().catch(() => {
@@ -1864,7 +1976,7 @@ export default class OverlayExpress {
1864
1976
  console.error(chalk.red('Error in /admin/startGASPSync:'), error);
1865
1977
  return res.status(400).json({
1866
1978
  status: 'error',
1867
- message: error instanceof Error ? error.message : 'An unknown error occurred'
1979
+ message: publicErrorMessage(error)
1868
1980
  });
1869
1981
  }
1870
1982
  })().catch(() => {
@@ -1948,7 +2060,7 @@ export default class OverlayExpress {
1948
2060
  console.error(chalk.red('Error in /admin/evictOutpoint:'), error);
1949
2061
  return res.status(400).json({
1950
2062
  status: 'error',
1951
- message: error instanceof Error ? error.message : 'An unknown error occurred'
2063
+ message: publicErrorMessage(error)
1952
2064
  });
1953
2065
  }
1954
2066
  })().catch(() => {
@@ -1973,7 +2085,7 @@ export default class OverlayExpress {
1973
2085
  console.error(chalk.red('Error in /admin/janitor:'), error);
1974
2086
  return res.status(400).json({
1975
2087
  status: 'error',
1976
- message: error instanceof Error ? error.message : 'An unknown error occurred'
2088
+ message: publicErrorMessage(error)
1977
2089
  });
1978
2090
  }
1979
2091
  })().catch(() => {
@@ -1991,7 +2103,7 @@ export default class OverlayExpress {
1991
2103
  this.logger.log(chalk.green('Knex migrations run'), result);
1992
2104
  // 404 handler for all other routes
1993
2105
  this.app.use((req, res) => {
1994
- this.logger.log(chalk.red('404 Not Found:'), req.url);
2106
+ this.logger.log(chalk.red(`404 Not Found: url=${serializeLogValue(req.url)}`));
1995
2107
  res.status(404).json({
1996
2108
  status: 'error',
1997
2109
  code: 'ERR_ROUTE_NOT_FOUND',
@@ -2000,10 +2112,54 @@ export default class OverlayExpress {
2000
2112
  });
2001
2113
  await this.runStartupSync();
2002
2114
  // Start listening on the configured port
2003
- this.app.listen(this.port, () => {
2115
+ this.server = this.app.listen(this.port, () => {
2004
2116
  this.isListening = true;
2005
2117
  this.logger.log(chalk.green.bold(`${this.name} is ready and listening on local port ${this.port}`));
2006
2118
  });
2119
+ configureHttpServer(this.server, edgePolicy.environmentPrefix, edgePolicy.http);
2120
+ }
2121
+ /**
2122
+ * Stops new HTTP work, background synchronization, and database clients.
2123
+ *
2124
+ * The operation is idempotent so multiple signal handlers or embedding
2125
+ * runtimes can share shutdown ownership safely.
2126
+ */
2127
+ async close() {
2128
+ this.closePromise ??= this.closeResources();
2129
+ await this.closePromise;
2130
+ }
2131
+ async closeResources() {
2132
+ this.isListening = false;
2133
+ if (this.basmBlockPollTimer !== undefined) {
2134
+ clearInterval(this.basmBlockPollTimer);
2135
+ this.basmBlockPollTimer = undefined;
2136
+ }
2137
+ if (this.unprovenMaintenanceTimer !== undefined) {
2138
+ clearInterval(this.unprovenMaintenanceTimer);
2139
+ this.unprovenMaintenanceTimer = undefined;
2140
+ }
2141
+ this.reorgAdapter?.stop();
2142
+ this.reorgAdapter = undefined;
2143
+ const server = this.server;
2144
+ this.server = undefined;
2145
+ const closeServer = server === undefined
2146
+ ? Promise.resolve()
2147
+ : new Promise((resolve, reject) => {
2148
+ server.close(error => {
2149
+ if (error !== undefined)
2150
+ reject(error);
2151
+ else
2152
+ resolve();
2153
+ });
2154
+ });
2155
+ await closeServer;
2156
+ await Promise.all([
2157
+ this.knex?.destroy() ?? Promise.resolve(),
2158
+ this.mongoClient?.close() ?? Promise.resolve()
2159
+ ]);
2160
+ this.knex = undefined;
2161
+ this.mongoClient = undefined;
2162
+ this.mongoDb = undefined;
2007
2163
  }
2008
2164
  /**
2009
2165
  * Runs the post-listen startup work: advertiser init, advertisement sync,