@conduitplatform/module-tools 0.17.0-alpha.6 → 0.17.0-alpha.8

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.
package/dist/index.d.cts CHANGED
@@ -163,6 +163,7 @@ declare abstract class ManagedModule<T> extends ConduitServiceModule {
163
163
  private _pendingConfigUpdates;
164
164
  private _processingConfig;
165
165
  protected constructor(moduleName: string, peerManifestRoot?: string);
166
+ protected get configInitialized(): boolean;
166
167
  get name(): string;
167
168
  get address(): string;
168
169
  start(): Promise<void>;
@@ -484,9 +485,26 @@ interface ImportModelAdapter {
484
485
  */
485
486
  declare function importModel(adapter: ImportModelAdapter, records: Record<string, unknown>[], options?: SanitizeForExportOptions): Promise<ImportResultEntry>;
486
487
 
488
+ declare const convictConfigParser: (config: Indexable) => Indexable;
489
+
490
+ declare function containsRedactedMarker(value: unknown): boolean;
491
+ declare function redactSensitiveConfig<T>(config: T, schema?: unknown): T;
492
+ declare function restoreRedactedSecrets<T>(incoming: T, current: T, schema?: unknown): T;
493
+
494
+ declare function stableConfigJson(value: unknown): string;
495
+ declare function storedConfigsEquivalent(left: unknown, right: unknown): boolean;
496
+ declare function reconcileStoredModuleConfig<T>(args: {
497
+ stored: T;
498
+ migrated: T;
499
+ configureOverride: (config: T) => Promise<T>;
500
+ }): Promise<{
501
+ config: T;
502
+ persisted: boolean;
503
+ }>;
504
+
487
505
  declare class ModuleError extends GrpcError {
488
506
  debugLogInfo?: string;
489
507
  constructor(errorDefinition: ModuleErrorDefinition, debugLogInfo?: string);
490
508
  }
491
509
 
492
- export { ConduitActiveSchema, ConduitBoolean, ConduitDate, ConduitJson, ConduitNumber, ConduitObjectId, type ConduitPackageJson, type ConduitPeerWatchEntry, type ConduitPeersManifest, ConduitRelation, type ConduitService, ConduitServiceModule, ConduitString, ConfigController, DEFAULT_STRIP_FIELDS, type ExportModelAdapter, type ExportResult, type ExportableResource, GrpcServer, type ImportModelAdapter, type ImportResult, type ImportResultEntry, ManagedModule, ModuleError, ModuleLifecycleStage, type RequestHandlers, RouteBuilder, type RouterRequestHandler, type RouterRequestHandlerCallback, RoutingManager, type SanitizeForExportOptions, type SocketEventHandler, type SocketRequestHandler, type SocketRequestHandlerCallback, type SocketRequestHandlers, addServiceToServer, createParsedRouterRequest, createServer, exportModel, importModel, initializeSdk, linearBackoffTimeout, linearBackoffTimeoutAsync, merge, readConduitPeersManifest, sanitizeDocumentsForExport, stripInternalFields, wrapFunctionsAsync, wrapGrpcFunctions, wrapRouterGrpcFunction };
510
+ export { ConduitActiveSchema, ConduitBoolean, ConduitDate, ConduitJson, ConduitNumber, ConduitObjectId, type ConduitPackageJson, type ConduitPeerWatchEntry, type ConduitPeersManifest, ConduitRelation, type ConduitService, ConduitServiceModule, ConduitString, ConfigController, DEFAULT_STRIP_FIELDS, type ExportModelAdapter, type ExportResult, type ExportableResource, GrpcServer, type ImportModelAdapter, type ImportResult, type ImportResultEntry, ManagedModule, ModuleError, ModuleLifecycleStage, type RequestHandlers, RouteBuilder, type RouterRequestHandler, type RouterRequestHandlerCallback, RoutingManager, type SanitizeForExportOptions, type SocketEventHandler, type SocketRequestHandler, type SocketRequestHandlerCallback, type SocketRequestHandlers, addServiceToServer, containsRedactedMarker, convictConfigParser, createParsedRouterRequest, createServer, exportModel, importModel, initializeSdk, linearBackoffTimeout, linearBackoffTimeoutAsync, merge, readConduitPeersManifest, reconcileStoredModuleConfig, redactSensitiveConfig, restoreRedactedSecrets, sanitizeDocumentsForExport, stableConfigJson, storedConfigsEquivalent, stripInternalFields, wrapFunctionsAsync, wrapGrpcFunctions, wrapRouterGrpcFunction };
package/dist/index.d.ts CHANGED
@@ -163,6 +163,7 @@ declare abstract class ManagedModule<T> extends ConduitServiceModule {
163
163
  private _pendingConfigUpdates;
164
164
  private _processingConfig;
165
165
  protected constructor(moduleName: string, peerManifestRoot?: string);
166
+ protected get configInitialized(): boolean;
166
167
  get name(): string;
167
168
  get address(): string;
168
169
  start(): Promise<void>;
@@ -484,9 +485,26 @@ interface ImportModelAdapter {
484
485
  */
485
486
  declare function importModel(adapter: ImportModelAdapter, records: Record<string, unknown>[], options?: SanitizeForExportOptions): Promise<ImportResultEntry>;
486
487
 
488
+ declare const convictConfigParser: (config: Indexable) => Indexable;
489
+
490
+ declare function containsRedactedMarker(value: unknown): boolean;
491
+ declare function redactSensitiveConfig<T>(config: T, schema?: unknown): T;
492
+ declare function restoreRedactedSecrets<T>(incoming: T, current: T, schema?: unknown): T;
493
+
494
+ declare function stableConfigJson(value: unknown): string;
495
+ declare function storedConfigsEquivalent(left: unknown, right: unknown): boolean;
496
+ declare function reconcileStoredModuleConfig<T>(args: {
497
+ stored: T;
498
+ migrated: T;
499
+ configureOverride: (config: T) => Promise<T>;
500
+ }): Promise<{
501
+ config: T;
502
+ persisted: boolean;
503
+ }>;
504
+
487
505
  declare class ModuleError extends GrpcError {
488
506
  debugLogInfo?: string;
489
507
  constructor(errorDefinition: ModuleErrorDefinition, debugLogInfo?: string);
490
508
  }
491
509
 
492
- export { ConduitActiveSchema, ConduitBoolean, ConduitDate, ConduitJson, ConduitNumber, ConduitObjectId, type ConduitPackageJson, type ConduitPeerWatchEntry, type ConduitPeersManifest, ConduitRelation, type ConduitService, ConduitServiceModule, ConduitString, ConfigController, DEFAULT_STRIP_FIELDS, type ExportModelAdapter, type ExportResult, type ExportableResource, GrpcServer, type ImportModelAdapter, type ImportResult, type ImportResultEntry, ManagedModule, ModuleError, ModuleLifecycleStage, type RequestHandlers, RouteBuilder, type RouterRequestHandler, type RouterRequestHandlerCallback, RoutingManager, type SanitizeForExportOptions, type SocketEventHandler, type SocketRequestHandler, type SocketRequestHandlerCallback, type SocketRequestHandlers, addServiceToServer, createParsedRouterRequest, createServer, exportModel, importModel, initializeSdk, linearBackoffTimeout, linearBackoffTimeoutAsync, merge, readConduitPeersManifest, sanitizeDocumentsForExport, stripInternalFields, wrapFunctionsAsync, wrapGrpcFunctions, wrapRouterGrpcFunction };
510
+ export { ConduitActiveSchema, ConduitBoolean, ConduitDate, ConduitJson, ConduitNumber, ConduitObjectId, type ConduitPackageJson, type ConduitPeerWatchEntry, type ConduitPeersManifest, ConduitRelation, type ConduitService, ConduitServiceModule, ConduitString, ConfigController, DEFAULT_STRIP_FIELDS, type ExportModelAdapter, type ExportResult, type ExportableResource, GrpcServer, type ImportModelAdapter, type ImportResult, type ImportResultEntry, ManagedModule, ModuleError, ModuleLifecycleStage, type RequestHandlers, RouteBuilder, type RouterRequestHandler, type RouterRequestHandlerCallback, RoutingManager, type SanitizeForExportOptions, type SocketEventHandler, type SocketRequestHandler, type SocketRequestHandlerCallback, type SocketRequestHandlers, addServiceToServer, containsRedactedMarker, convictConfigParser, createParsedRouterRequest, createServer, exportModel, importModel, initializeSdk, linearBackoffTimeout, linearBackoffTimeoutAsync, merge, readConduitPeersManifest, reconcileStoredModuleConfig, redactSensitiveConfig, restoreRedactedSecrets, sanitizeDocumentsForExport, stableConfigJson, storedConfigsEquivalent, stripInternalFields, wrapFunctionsAsync, wrapGrpcFunctions, wrapRouterGrpcFunction };
package/dist/index.esm.js CHANGED
@@ -199,7 +199,7 @@ function addServiceToServer(server, protoPath, descriptorObject, functions) {
199
199
  // src/helpers/wrapGrpcFunctions.ts
200
200
  import { createVerifier } from "fast-jwt";
201
201
  import { status } from "@grpc/grpc-js";
202
- import { ConduitGrpcSdk } from "@conduitplatform/grpc-sdk";
202
+ import { ConduitGrpcSdk, GrpcError } from "@conduitplatform/grpc-sdk";
203
203
  function wrapGrpcFunctions(functions, postponeRestart, noAuth = false) {
204
204
  const grpcKey = process.env.GRPC_KEY;
205
205
  const wrappedFunctions = {};
@@ -232,11 +232,19 @@ function wrapGrpcFunctions(functions, postponeRestart, noAuth = false) {
232
232
  try {
233
233
  invoked = functions[name](call, callback);
234
234
  } catch (error) {
235
- return throwError(callback, error.message);
235
+ return throwError(
236
+ callback,
237
+ error.message,
238
+ error instanceof GrpcError ? error.code : status.INTERNAL
239
+ );
236
240
  }
237
241
  if (typeof invoked?.then === "function") {
238
242
  invoked.then().catch((error) => {
239
- return throwError(callback, error.message);
243
+ return throwError(
244
+ callback,
245
+ error.message,
246
+ error instanceof GrpcError ? error.code : status.INTERNAL
247
+ );
240
248
  });
241
249
  }
242
250
  };
@@ -1234,9 +1242,84 @@ async function setupLoki(module, instance) {
1234
1242
  }
1235
1243
  }
1236
1244
 
1237
- // src/utilities/initializeSdk.ts
1238
- import winston2 from "winston";
1245
+ // src/logging/fileTransports.ts
1246
+ import fs from "fs";
1247
+ import os from "os";
1239
1248
  import path3 from "path";
1249
+ import winston2 from "winston";
1250
+ import DailyRotateFile from "winston-daily-rotate-file";
1251
+ var DEFAULT_RETENTION_DAYS = 3;
1252
+ var DEFAULT_MAX_SIZE = "20m";
1253
+ var SIZE_STRING = /^(?:0\.)?\d+[kmg]$/i;
1254
+ function positiveIntFromEnv(raw, fallback) {
1255
+ if (raw === void 0) return fallback;
1256
+ const trimmed = raw.trim();
1257
+ if (!/^[0-9]+$/.test(trimmed)) return fallback;
1258
+ const value = Number(trimmed);
1259
+ if (!Number.isSafeInteger(value) || value <= 0) return fallback;
1260
+ return value;
1261
+ }
1262
+ function logFileMaxSize() {
1263
+ const raw = process.env.LOG_FILE_MAX_SIZE?.trim();
1264
+ if (!raw) return DEFAULT_MAX_SIZE;
1265
+ if (SIZE_STRING.test(raw)) return raw.toLowerCase();
1266
+ if (/^[0-9]+$/.test(raw)) {
1267
+ const bytes = Number(raw);
1268
+ if (Number.isSafeInteger(bytes) && bytes > 0) return bytes;
1269
+ }
1270
+ return DEFAULT_MAX_SIZE;
1271
+ }
1272
+ function formatMeta(meta) {
1273
+ if (Array.isArray(meta)) {
1274
+ if (meta.length === 0) return "";
1275
+ return meta.map((item) => JSON.stringify(item)).join(" ");
1276
+ }
1277
+ if (meta !== null && typeof meta === "object") {
1278
+ if (Object.keys(meta).length === 0) return "";
1279
+ return JSON.stringify(meta);
1280
+ }
1281
+ return "";
1282
+ }
1283
+ function createFileFormat() {
1284
+ return winston2.format.combine(
1285
+ winston2.format.errors({ stack: true }),
1286
+ winston2.format.timestamp({
1287
+ format: "YYYY-MM-DD HH:mm:ss"
1288
+ }),
1289
+ winston2.format.printf((info) => {
1290
+ const metaText = formatMeta(info.meta);
1291
+ const line = `[${info.timestamp}] [${info.level.toUpperCase()}]: ${info.message}`;
1292
+ if (info.stack) {
1293
+ return `${line} ${info.stack}`;
1294
+ }
1295
+ return metaText ? `${line} ${metaText}` : line;
1296
+ })
1297
+ );
1298
+ }
1299
+ function rotateTransport(logDir, name, level) {
1300
+ return new DailyRotateFile({
1301
+ dirname: logDir,
1302
+ filename: `${name}-%DATE%.log`,
1303
+ datePattern: "YYYY-MM-DD",
1304
+ level,
1305
+ maxFiles: `${positiveIntFromEnv(process.env.LOG_RETENTION_DAYS, DEFAULT_RETENTION_DAYS)}d`,
1306
+ maxSize: logFileMaxSize(),
1307
+ zippedArchive: false,
1308
+ auditFile: path3.join(logDir, `.${name}-audit.json`),
1309
+ format: createFileFormat()
1310
+ });
1311
+ }
1312
+ function createFileLogTransports() {
1313
+ if (process.env.LOG_TO_FILE?.trim() === "false") {
1314
+ return [];
1315
+ }
1316
+ const logDir = process.env.LOG_FILE_DIR?.trim() || path3.join(os.tmpdir(), "conduit-logs");
1317
+ fs.mkdirSync(logDir, { recursive: true });
1318
+ return [
1319
+ rotateTransport(logDir, "combined", "info"),
1320
+ rotateTransport(logDir, "errors", "error")
1321
+ ];
1322
+ }
1240
1323
 
1241
1324
  // src/metrics/index.ts
1242
1325
  import {
@@ -1635,17 +1718,9 @@ function clientMiddleware() {
1635
1718
  var initializeSdk = (coreUrl, moduleName, watchModules = true, serviceHealthStatusGetter = () => HealthCheckStatus2.SERVING) => {
1636
1719
  let logger;
1637
1720
  try {
1638
- logger = new ConduitLogger([
1639
- new winston2.transports.File({
1640
- filename: path3.join(__dirname, ".logs/combined.log"),
1641
- level: "info"
1642
- }),
1643
- new winston2.transports.File({
1644
- filename: path3.join(__dirname, ".logs/errors.log"),
1645
- level: "error"
1646
- })
1647
- ]);
1648
- } catch (e) {
1721
+ const fileTransports = createFileLogTransports();
1722
+ logger = fileTransports.length > 0 ? new ConduitLogger(fileTransports) : new ConduitLogger();
1723
+ } catch {
1649
1724
  logger = new ConduitLogger();
1650
1725
  }
1651
1726
  const grpcSdk = new ConduitGrpcSdk7(
@@ -1751,6 +1826,110 @@ var convictConfigParser = (config) => {
1751
1826
  return config;
1752
1827
  };
1753
1828
 
1829
+ // src/utilities/redactSensitiveConfig.ts
1830
+ var WELL_KNOWN_SECRET_KEYS = /^(apiKey|api_key|password|secret|privateKey|private_key)$/i;
1831
+ function isRecord(value) {
1832
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1833
+ }
1834
+ function isSchemaLeaf(value) {
1835
+ return isRecord(value) && ("default" in value || "format" in value || "type" in value) && !isRecord(value._cvtProperties);
1836
+ }
1837
+ function isSensitiveLeaf(value) {
1838
+ return isSchemaLeaf(value) && value.sensitive === true;
1839
+ }
1840
+ function unwrapSchema(schema) {
1841
+ if (isRecord(schema) && isRecord(schema._cvtProperties)) {
1842
+ return schema._cvtProperties;
1843
+ }
1844
+ return schema;
1845
+ }
1846
+ var REDACTED_MARKER = "[REDACTED]";
1847
+ function containsRedactedMarker(value) {
1848
+ if (value === REDACTED_MARKER) return true;
1849
+ if (Array.isArray(value)) {
1850
+ return value.some(containsRedactedMarker);
1851
+ }
1852
+ if (!isRecord(value)) return false;
1853
+ return Object.values(value).some(containsRedactedMarker);
1854
+ }
1855
+ function redactSensitiveConfig(config, schema) {
1856
+ if (!isRecord(config)) return config;
1857
+ const redacted = Array.isArray(config) ? [...config] : { ...config };
1858
+ const node = unwrapSchema(schema);
1859
+ for (const [key, value] of Object.entries(redacted)) {
1860
+ const childSchema = isRecord(node) ? node[key] : void 0;
1861
+ if (isSensitiveLeaf(childSchema) || WELL_KNOWN_SECRET_KEYS.test(key)) {
1862
+ if (typeof value === "string" && value.length > 0) {
1863
+ redacted[key] = REDACTED_MARKER;
1864
+ }
1865
+ continue;
1866
+ }
1867
+ if (isRecord(value) || Array.isArray(value)) {
1868
+ redacted[key] = redactSensitiveConfig(
1869
+ value,
1870
+ childSchema
1871
+ );
1872
+ }
1873
+ }
1874
+ return redacted;
1875
+ }
1876
+ function restoreRedactedSecrets(incoming, current, schema) {
1877
+ if (Array.isArray(incoming) && Array.isArray(current)) {
1878
+ return incoming.map(
1879
+ (item, index) => restoreRedactedSecrets(item, current[index], schema)
1880
+ );
1881
+ }
1882
+ if (!isRecord(incoming) || !isRecord(current)) return incoming;
1883
+ const restored = { ...incoming };
1884
+ const node = unwrapSchema(schema);
1885
+ for (const [key, value] of Object.entries(restored)) {
1886
+ const childSchema = isRecord(node) ? node[key] : void 0;
1887
+ const currentValue = current[key];
1888
+ if (isSensitiveLeaf(childSchema) || WELL_KNOWN_SECRET_KEYS.test(key)) {
1889
+ if (value === REDACTED_MARKER && typeof currentValue === "string" && currentValue.length > 0 && currentValue !== REDACTED_MARKER) {
1890
+ restored[key] = currentValue;
1891
+ }
1892
+ continue;
1893
+ }
1894
+ if ((isRecord(value) || Array.isArray(value)) && (isRecord(currentValue) || Array.isArray(currentValue))) {
1895
+ restored[key] = restoreRedactedSecrets(value, currentValue, childSchema);
1896
+ }
1897
+ }
1898
+ return restored;
1899
+ }
1900
+
1901
+ // src/utilities/reconcileModuleConfig.ts
1902
+ function isRecord2(value) {
1903
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1904
+ }
1905
+ function sortJson(value) {
1906
+ if (Array.isArray(value)) {
1907
+ return value.map(sortJson);
1908
+ }
1909
+ if (!isRecord2(value)) {
1910
+ return value;
1911
+ }
1912
+ return Object.fromEntries(
1913
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, nested]) => [key, sortJson(nested)])
1914
+ );
1915
+ }
1916
+ function stableConfigJson(value) {
1917
+ return JSON.stringify(sortJson(value));
1918
+ }
1919
+ function storedConfigsEquivalent(left, right) {
1920
+ return stableConfigJson(left) === stableConfigJson(right);
1921
+ }
1922
+ async function reconcileStoredModuleConfig(args) {
1923
+ if (storedConfigsEquivalent(args.stored, args.migrated)) {
1924
+ return { config: args.migrated, persisted: false };
1925
+ }
1926
+ if (containsRedactedMarker(args.migrated)) {
1927
+ return { config: args.migrated, persisted: false };
1928
+ }
1929
+ const persisted = await args.configureOverride(args.migrated);
1930
+ return { config: persisted, persisted: true };
1931
+ }
1932
+
1754
1933
  // src/routing/RoutingController.ts
1755
1934
  import { status as status4 } from "@grpc/grpc-js";
1756
1935
  var RoutingController = class {
@@ -1803,6 +1982,9 @@ var ManagedModule = class extends ConduitServiceModule {
1803
1982
  throw new Error("Failed to initialize grpcSdk");
1804
1983
  }
1805
1984
  }
1985
+ get configInitialized() {
1986
+ return this._configInitialized;
1987
+ }
1806
1988
  get name() {
1807
1989
  return this._moduleName;
1808
1990
  }
@@ -1994,9 +2176,10 @@ var ManagedModule = class extends ConduitServiceModule {
1994
2176
  });
1995
2177
  }
1996
2178
  let config = JSON.parse(call.request.newConfig);
1997
- config = merge(this.config.getProperties(), config);
1998
- config = await this.preConfig(config);
1999
2179
  const previousConfig = this.config.getProperties();
2180
+ config = merge(previousConfig, config);
2181
+ config = restoreRedactedSecrets(config, previousConfig, this.configSchema);
2182
+ config = await this.preConfig(config);
2000
2183
  try {
2001
2184
  this.config.load(config).validate({
2002
2185
  allowed: "warn"
@@ -2072,7 +2255,21 @@ var ManagedModule = class extends ConduitServiceModule {
2072
2255
  this.configOverride
2073
2256
  );
2074
2257
  ConfigController.getInstance();
2075
- if (config) ConfigController.getInstance().config = config;
2258
+ if (config) {
2259
+ const migrated = await this.preConfig(config);
2260
+ this.config.load(migrated).validate({
2261
+ allowed: "warn"
2262
+ });
2263
+ const persistable = this.config.getProperties();
2264
+ const reconciled = await reconcileStoredModuleConfig({
2265
+ stored: config,
2266
+ migrated: persistable,
2267
+ configureOverride: (next) => this.grpcSdk.config.configure(next, convictConfigParser(configSchema), true)
2268
+ });
2269
+ config = reconciled.config;
2270
+ this.config.load(config);
2271
+ ConfigController.getInstance().config = this.config.getProperties();
2272
+ }
2076
2273
  if (!config || config.active || !config.hasOwnProperty("active"))
2077
2274
  await this.onConfig();
2078
2275
  }
@@ -2082,8 +2279,8 @@ var ManagedModule = class extends ConduitServiceModule {
2082
2279
  };
2083
2280
 
2084
2281
  // src/classes/ModuleError.ts
2085
- import { GrpcError } from "@conduitplatform/grpc-sdk";
2086
- var ModuleError = class extends GrpcError {
2282
+ import { GrpcError as GrpcError2 } from "@conduitplatform/grpc-sdk";
2283
+ var ModuleError = class extends GrpcError2 {
2087
2284
  debugLogInfo;
2088
2285
  constructor(errorDefinition, debugLogInfo) {
2089
2286
  const { grpcCode, conduitCode, message } = errorDefinition;
@@ -2116,6 +2313,8 @@ export {
2116
2313
  RouteBuilder,
2117
2314
  RoutingManager,
2118
2315
  addServiceToServer,
2316
+ containsRedactedMarker,
2317
+ convictConfigParser,
2119
2318
  createParsedRouterRequest,
2120
2319
  createServer,
2121
2320
  exportModel,
@@ -2125,7 +2324,12 @@ export {
2125
2324
  linearBackoffTimeoutAsync,
2126
2325
  merge,
2127
2326
  readConduitPeersManifest,
2327
+ reconcileStoredModuleConfig,
2328
+ redactSensitiveConfig,
2329
+ restoreRedactedSecrets,
2128
2330
  sanitizeDocumentsForExport,
2331
+ stableConfigJson,
2332
+ storedConfigsEquivalent,
2129
2333
  stripInternalFields,
2130
2334
  wrapFunctionsAsync,
2131
2335
  wrapGrpcFunctions,