@camstack/server 1.2.734 → 1.2.736

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 (93) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/core/cap-providers.js +114 -8
  3. package/dist/api/trpc/generated-cap-mounts.js +17 -1
  4. package/dist/api/trpc/generated-cap-routers.js +1789 -1708
  5. package/dist/core/addon/addon-registry.service.js +2 -0
  6. package/dist/core/addon/addon-settings-provider.js +4 -0
  7. package/dist/core/addon/integration-instances-provider.js +21 -0
  8. package/package.json +4 -4
  9. package/system/dist/{agent-https-DEmi-YQ_.js → agent-https-Bi3JY1e0.js} +1 -1
  10. package/system/dist/{agent-https-DGp4gFzH.mjs → agent-https-DiK6iQzW.mjs} +1 -1
  11. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  12. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  13. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  14. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  15. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  16. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  17. package/system/dist/builtins/autotrack/index.js +1 -1
  18. package/system/dist/builtins/autotrack/index.mjs +1 -1
  19. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  20. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  21. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  22. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  23. package/system/dist/builtins/camera-grid/index.js +1 -1
  24. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  25. package/system/dist/builtins/composer/composer.addon.js +3 -3
  26. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  27. package/system/dist/builtins/console-logging/index.js +1 -1
  28. package/system/dist/builtins/console-logging/index.mjs +1 -1
  29. package/system/dist/builtins/core-blocks/core-blocks.addon.js +2 -2
  30. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  31. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  32. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  33. package/system/dist/builtins/device-manager/device-manager.addon.js +1 -1
  34. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  35. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  36. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  37. package/system/dist/builtins/keychain/index.js +3 -3
  38. package/system/dist/builtins/keychain/index.mjs +3 -3
  39. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  40. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  41. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  42. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  43. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  44. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  45. package/system/dist/builtins/loki-logging/index.js +440 -25
  46. package/system/dist/builtins/loki-logging/index.mjs +438 -25
  47. package/system/dist/builtins/loki-logging/loki-logging.addon.d.ts +23 -14
  48. package/system/dist/builtins/loki-logging/loki-record-kinds.d.ts +33 -0
  49. package/system/dist/builtins/loki-logging/migrations/connection-to-records.d.ts +47 -0
  50. package/system/dist/builtins/loki-logging/migrations/index.d.ts +8 -0
  51. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  52. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  53. package/system/dist/builtins/platform-probe/index.js +1 -1
  54. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  55. package/system/dist/builtins/record-entries/index.js +2 -22
  56. package/system/dist/builtins/record-entries/index.mjs +2 -22
  57. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  58. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  59. package/system/dist/builtins/snapshot/index.js +1 -1
  60. package/system/dist/builtins/snapshot/index.mjs +1 -1
  61. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  62. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  63. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  64. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  65. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +2 -2
  66. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +2 -2
  67. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  68. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  69. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  70. package/system/dist/builtins/system-config/system-config.addon.mjs +280 -280
  71. package/system/dist/builtins/winston-logging/index.js +1 -1
  72. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  73. package/system/dist/{composition-sources-DfyoPtMe.js → composition-sources-DQLGJMMh.js} +1 -1
  74. package/system/dist/{composition-sources-wVMwuZ-r.mjs → composition-sources-lnsR-YuH.mjs} +1 -1
  75. package/system/dist/{constants-C8fjD4YU.mjs → constants-D7I0cM20.mjs} +1 -1
  76. package/system/dist/{constants-CavIW3ee.js → constants-DA5jgmYT.js} +1 -1
  77. package/system/dist/{device-ca-B1vN9ZRB.mjs → device-ca-Clr2bCe-.mjs} +1 -1
  78. package/system/dist/{device-ca-b_fSvUlI.js → device-ca-GPjZE-Mm.js} +1 -1
  79. package/system/dist/{dist-SXRVvbkS.mjs → dist-Cyj93AvD.mjs} +534 -155
  80. package/system/dist/{dist-DDl6NKUe.js → dist-Xi7ZQ7UI.js} +569 -154
  81. package/system/dist/file-host-worker.js +1 -1
  82. package/system/dist/file-host-worker.mjs +1 -1
  83. package/system/dist/{hub-mdns-ciao-95JXbLd5.js → hub-mdns-ciao-BMgUdxgG.js} +2 -2
  84. package/system/dist/{hub-mdns-ciao-euMLdIPi.mjs → hub-mdns-ciao-ouzCfqVS.mjs} +2 -2
  85. package/system/dist/index.js +7 -7
  86. package/system/dist/index.mjs +7 -7
  87. package/system/dist/{restore-archive-DbtbDgPC.mjs → restore-archive-BG22FodH.mjs} +78 -78
  88. package/system/dist/{restore-archive-CMkK7SeP.js → restore-archive-CZozfCX-.js} +1 -1
  89. package/system/dist/{retention-BGUmx4FD.mjs → retention-BfC_C1vy.mjs} +1 -1
  90. package/system/dist/{retention-DI_dDceD.js → retention-DCrdPMot.js} +1 -1
  91. package/system/dist/{wal-maintenance-CgHJ7XTw.mjs → wal-maintenance-C2GNRuvy.mjs} +0 -0
  92. package/system/dist/{wal-maintenance-BaPMwUtL.js → wal-maintenance-PjOoh6-K.js} +0 -0
  93. package/system/package.json +4 -1
@@ -1,4 +1,4 @@
1
- import { Xr as logDestinationCapability, do as BaseAddon } from "../../dist-SXRVvbkS.mjs";
1
+ import { Bo as RevConflictError, Cs as isSecretFieldView, Dr as integrationInstancesCapability, Oi as preconditionOf, Pt as RecordIntegrationInstances, Qr as logDestinationCapability, as as defineAddonMigrations, po as BaseAddon, ss as defineEntryKind, ws as isSecretMarker } from "../../dist-Cyj93AvD.mjs";
2
2
  import { n as compileLogFilter, o as lineMatches } from "../../log-read-filter-D7Ev3zm-.mjs";
3
3
  import { z } from "zod";
4
4
  //#region src/builtins/loki-logging/loki-payload.ts
@@ -179,7 +179,7 @@ var LokiLineSchema = z.object({
179
179
  tags: z.record(z.string(), z.unknown()).optional(),
180
180
  meta: z.record(z.string(), z.unknown()).optional()
181
181
  });
182
- function levelOf(label) {
182
+ function levelOf$1(label) {
183
183
  return label === "debug" || label === "warn" || label === "error" ? label : "info";
184
184
  }
185
185
  /** A query_range body → rows, newest first. Lines that are not ours are dropped. */
@@ -188,7 +188,7 @@ function parseQueryRange(body) {
188
188
  if (!parsed.success) throw new Error("Loki answered with an unexpected query_range shape");
189
189
  const rows = [];
190
190
  for (const stream of parsed.data.data.result) {
191
- const level = levelOf(stream.stream["level"]);
191
+ const level = levelOf$1(stream.stream["level"]);
192
192
  for (const [nsText, text] of stream.values) {
193
193
  let json;
194
194
  try {
@@ -604,6 +604,220 @@ var LokiDestination = class {
604
604
  }
605
605
  };
606
606
  //#endregion
607
+ //#region src/builtins/loki-logging/loki-record-kinds.ts
608
+ /**
609
+ * The Loki connection as a record (D985): one `destinations` row per Loki instance, owned by
610
+ * `loki-logging`, listed on the Integrations page like any other connection. The row id is the
611
+ * `integrations` registry id (`int_NNNN`). The password is a keychain marker bound to the row.
612
+ *
613
+ * The kind name is `destinations` (kind names are lower-case-dashed); the owner is `loki-logging`.
614
+ */
615
+ /** The inclusive bounds of the numeric fields: the schema and the settings migration read ONE copy. */
616
+ var LOKI_BOUNDS = {
617
+ batchIntervalMs: {
618
+ min: 250,
619
+ max: 6e4
620
+ },
621
+ batchSize: {
622
+ min: 1,
623
+ max: 5e3
624
+ },
625
+ timeoutMs: {
626
+ min: 1e3,
627
+ max: 6e4
628
+ }
629
+ };
630
+ var lokiDestinationsKind = defineEntryKind("destinations", {
631
+ title: "Loki destinations",
632
+ nameField: "name",
633
+ schema: z.object({
634
+ name: z.string().min(1),
635
+ url: z.string(),
636
+ level: z.enum([
637
+ "debug",
638
+ "info",
639
+ "warn",
640
+ "error"
641
+ ]),
642
+ job: z.string(),
643
+ extraLabels: z.string(),
644
+ tenantId: z.string(),
645
+ username: z.string(),
646
+ password: z.string().optional().meta({ secret: true }),
647
+ batchIntervalMs: z.number().int().min(LOKI_BOUNDS.batchIntervalMs.min).max(LOKI_BOUNDS.batchIntervalMs.max),
648
+ batchSize: z.number().int().min(LOKI_BOUNDS.batchSize.min).max(LOKI_BOUNDS.batchSize.max),
649
+ timeoutMs: z.number().int().min(LOKI_BOUNDS.timeoutMs.min).max(LOKI_BOUNDS.timeoutMs.max)
650
+ })
651
+ });
652
+ var LOKI_DEFAULT_BODY = {
653
+ url: "",
654
+ level: "info",
655
+ job: "camstack",
656
+ extraLabels: "",
657
+ tenantId: "",
658
+ username: "",
659
+ batchIntervalMs: 5e3,
660
+ batchSize: 200,
661
+ timeoutMs: 1e4
662
+ };
663
+ //#endregion
664
+ //#region src/builtins/loki-logging/migrations/connection-to-records.ts
665
+ /**
666
+ * The Loki connection moves from the addon's settings into a `destinations` record (D985):
667
+ * an integration row in the registry, a record under that id, and the password re-bound to
668
+ * the record's keychain slot. The old keys are deleted by the second migration of the
669
+ * catalogue (`dropMovedSettings`), only after this one succeeded.
670
+ *
671
+ * Idempotent and ordered so a crash is safe: nothing is written before the old settings are
672
+ * read in full (a password that cannot be resolved aborts the pass); an existing record is
673
+ * never overwritten; the old password is cleared only once the record verifiably holds it.
674
+ */
675
+ /** The settings scope of this addon (`<addonId>:addon-settings`). */
676
+ var LOKI_SETTINGS_SCOPE = "loki-logging:addon-settings";
677
+ /** The connection keys the record now owns. `password` is the secret, cleared separately. */
678
+ var MOVED_PLAIN_KEYS = [
679
+ "url",
680
+ "level",
681
+ "job",
682
+ "extraLabels",
683
+ "tenantId",
684
+ "username",
685
+ "batchIntervalMs",
686
+ "batchSize",
687
+ "timeoutMs"
688
+ ];
689
+ var LOKI_NAME = "Loki";
690
+ function text(stored, key, fallback) {
691
+ const value = stored[key];
692
+ return typeof value === "string" ? value : fallback;
693
+ }
694
+ /**
695
+ * A whole number inside the kind's own bounds (`LOKI_BOUNDS`, the same copy the schema uses): an
696
+ * out-of-range legacy value would make the record write throw and block the owner, so it is
697
+ * clamped, and the clamp is named.
698
+ */
699
+ function bounded(stored, key, fallback, log) {
700
+ const value = stored[key];
701
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
702
+ const { min, max } = LOKI_BOUNDS[key];
703
+ const clamped = Math.min(max, Math.max(min, Math.round(value)));
704
+ if (clamped !== value) log.warn(`Loki migration: the legacy "${key}" is outside ${min}..${max}; clamped to ${clamped}`);
705
+ return clamped;
706
+ }
707
+ function levelOf(stored) {
708
+ const value = stored["level"];
709
+ return value === "debug" || value === "info" || value === "warn" || value === "error" ? value : LOKI_DEFAULT_BODY.level;
710
+ }
711
+ function bodyFrom(stored, log) {
712
+ const password = text(stored, "password", "");
713
+ return {
714
+ name: LOKI_NAME,
715
+ url: text(stored, "url", LOKI_DEFAULT_BODY.url),
716
+ level: levelOf(stored),
717
+ job: text(stored, "job", LOKI_DEFAULT_BODY.job),
718
+ extraLabels: text(stored, "extraLabels", LOKI_DEFAULT_BODY.extraLabels),
719
+ tenantId: text(stored, "tenantId", LOKI_DEFAULT_BODY.tenantId),
720
+ username: text(stored, "username", LOKI_DEFAULT_BODY.username),
721
+ ...password.length > 0 ? { password } : {},
722
+ batchIntervalMs: bounded(stored, "batchIntervalMs", LOKI_DEFAULT_BODY.batchIntervalMs, log),
723
+ batchSize: bounded(stored, "batchSize", LOKI_DEFAULT_BODY.batchSize, log),
724
+ timeoutMs: bounded(stored, "timeoutMs", LOKI_DEFAULT_BODY.timeoutMs, log)
725
+ };
726
+ }
727
+ async function moveConnectionToRecord(ports) {
728
+ const stored = await ports.readStored();
729
+ const url = text(stored, "url", "");
730
+ const hasPassword = text(stored, "password", "").length > 0;
731
+ if (url.length === 0 && !hasPassword) return {
732
+ outcome: "already-done",
733
+ summary: { moved: false }
734
+ };
735
+ const id = await ports.ensureIntegration(LOKI_NAME);
736
+ const put = await ports.putRecord(id, bodyFrom(stored, ports));
737
+ if (hasPassword) if (put === "created" || (await ports.readRecord(id))?.hasPassword === true) await ports.clearOldPassword();
738
+ else ports.warn("Loki migration: the existing record holds no password; the legacy one is kept, not cleared");
739
+ return put === "created" ? {
740
+ outcome: "done",
741
+ summary: {
742
+ moved: true,
743
+ integrationId: id
744
+ }
745
+ } : {
746
+ outcome: "already-done",
747
+ summary: {
748
+ moved: false,
749
+ integrationId: id
750
+ }
751
+ };
752
+ }
753
+ async function planDropMovedSettings(ports) {
754
+ const stored = await ports.readRawStored();
755
+ const present = [...MOVED_PLAIN_KEYS, "password"].filter((key) => key in stored);
756
+ if (present.length === 0) return { edits: [] };
757
+ await confirmRecordHoldsLegacy(ports, stored);
758
+ return { edits: [{
759
+ op: "deleteKeys",
760
+ scope: LOKI_SETTINGS_SCOPE,
761
+ keys: present,
762
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [key, stored[key]])))
763
+ }] };
764
+ }
765
+ /**
766
+ * The keys are deleted only when the record is confirmed to hold what they carried: the url,
767
+ * and the password when the legacy settings still have one. Otherwise the migration fails, the
768
+ * keys stay, and the next boot retries.
769
+ */
770
+ async function confirmRecordHoldsLegacy(ports, stored) {
771
+ const legacyUrl = text(stored, "url", "");
772
+ const legacyPassword = "password" in stored;
773
+ if (legacyUrl.length === 0 && !legacyPassword) return;
774
+ const refuse = (reason) => {
775
+ ports.warn(`Loki migration: the legacy keys are kept: ${reason}`);
776
+ throw new Error(`the legacy Loki keys are not deleted: ${reason}`);
777
+ };
778
+ const id = await ports.findIntegration();
779
+ if (id === null) return refuse("no integration row exists");
780
+ const record = await ports.readRecord(id);
781
+ if (record === null) return refuse("the destinations record does not exist");
782
+ if (legacyUrl.length > 0 && record.url.length === 0) return refuse("the record holds no url");
783
+ if (legacyPassword && !record.hasPassword) return refuse("the record holds no password");
784
+ }
785
+ //#endregion
786
+ //#region src/builtins/loki-logging/migrations/index.ts
787
+ var CONNECTION_TO_RECORDS_ID = "loki-logging/2026-11-02-connection-to-records";
788
+ /** The `loki-logging` catalogue (D987): offered to the engine when the hub-resident addon initialises. */
789
+ var ADDON_MIGRATIONS = [{
790
+ meta: {
791
+ id: CONNECTION_TO_RECORDS_ID,
792
+ owner: "loki-logging",
793
+ level: "addon-state",
794
+ seq: 1,
795
+ dependsOn: [],
796
+ store: "settings",
797
+ scope: "cluster",
798
+ onFailure: "block-owner",
799
+ bodyKind: "procedure",
800
+ description: "Move the Loki connection (url, credentials, labels, batching) from the addon settings into a destinations record under an integrations row",
801
+ fixtureMark: "the D777 retirement marker the migration does not know"
802
+ },
803
+ procedure: moveConnectionToRecord
804
+ }, {
805
+ meta: {
806
+ id: "loki-logging/2026-11-02-drop-moved-settings",
807
+ owner: "loki-logging",
808
+ level: "addon-state",
809
+ seq: 2,
810
+ dependsOn: [CONNECTION_TO_RECORDS_ID],
811
+ store: "settings",
812
+ scope: "cluster",
813
+ onFailure: "block-owner",
814
+ bodyKind: "plan",
815
+ description: "Delete the connection keys that moved into the destinations record",
816
+ fixtureMark: "the D777 retirement marker the migration does not know"
817
+ },
818
+ plan: planDropMovedSettings
819
+ }];
820
+ //#endregion
607
821
  //#region src/builtins/loki-logging/retire-enabled-flag.ts
608
822
  /** The retired settings key. */
609
823
  var RETIRED_ENABLED_KEY = "enabled";
@@ -649,35 +863,220 @@ var RETIREMENT_RETRY_DELAYS_MS = [
649
863
  3e4,
650
864
  6e4
651
865
  ];
652
- var DEFAULTS = {
653
- url: "",
654
- job: "camstack",
655
- level: "info",
656
- batchIntervalMs: 5e3,
657
- batchSize: 200,
658
- extraLabels: "",
659
- tenantId: "",
660
- username: "",
661
- password: "",
662
- timeoutMs: 1e4
663
- };
866
+ /** An agent re-reads the record on this period; the hub applies a change at once (`onChanged`). */
867
+ var AGENT_REFRESH_MS = 3e4;
868
+ /** The headers the destination itself sends: tenant and basic auth. */
869
+ function probeHeaders(auth) {
870
+ const headers = {};
871
+ if (auth.tenantId.trim().length > 0) headers["X-Scope-OrgID"] = auth.tenantId.trim();
872
+ if (auth.username.length > 0) headers["authorization"] = `Basic ${Buffer.from(`${auth.username}:${auth.password}`).toString("base64")}`;
873
+ return headers;
874
+ }
875
+ /** A failure message with the userinfo of any URL in it (and the typed URL's own) removed. */
876
+ function stripUserinfo(message, typedUrl) {
877
+ let out = message.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]*@/gi, "$1");
878
+ try {
879
+ const parsed = new URL(typedUrl);
880
+ for (const secret of [parsed.username, parsed.password]) if (secret.length > 0) out = out.split(decodeURIComponent(secret)).join("***");
881
+ } catch {}
882
+ return out;
883
+ }
884
+ /** Where the connection probe asks: Loki answers `ready` once its ring is up. */
885
+ var READY_PATH = "/ready";
664
886
  var LokiLoggingAddon = class extends BaseAddon {
665
887
  destination = null;
888
+ instances = null;
889
+ current = null;
890
+ refreshTimer = null;
666
891
  retirementTimer = null;
667
892
  shuttingDown = false;
893
+ declared = false;
894
+ secretsWarned = false;
668
895
  constructor() {
669
- super({ ...DEFAULTS });
896
+ super({});
897
+ }
898
+ isHub() {
899
+ return (this.ctx.kernel.localNodeId ?? "hub") === "hub";
670
900
  }
671
901
  async onInitialize() {
672
902
  this.destination = new LokiDestination();
673
- await this.destination.initialize(this.destinationConfig());
674
- this.ctx.logger.info(this.config.url.length > 0 ? `Loki logging initialized → ${this.config.url}` : "Loki logging registered but inactive (no URL set)");
675
903
  this.shuttingDown = false;
676
- this.attemptEnabledFlagRetirement(0);
677
- return [{
904
+ const registrations = [{
678
905
  capability: logDestinationCapability,
679
906
  provider: this.destination
680
907
  }];
908
+ const records = this.ctx.records;
909
+ if (records !== void 0) {
910
+ const hub = this.isHub();
911
+ if (hub) await this.ensureDeclared();
912
+ else await this.ensureDeclaredQuietly();
913
+ this.instances = new RecordIntegrationInstances(records, lokiDestinationsKind, {
914
+ description: {
915
+ instanceMode: "single",
916
+ kind: "destination",
917
+ canTest: true
918
+ },
919
+ formSchema: () => this.connectionForm(),
920
+ initialBody: (name) => ({
921
+ ...LOKI_DEFAULT_BODY,
922
+ name
923
+ }),
924
+ configured: (body) => body.url.length > 0,
925
+ onChanged: async () => {
926
+ await this.refreshFromRecord();
927
+ },
928
+ test: (input) => this.probe(input.id, input.values)
929
+ });
930
+ if (hub) {
931
+ await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, this.migrationPorts()));
932
+ registrations.push({
933
+ capability: integrationInstancesCapability,
934
+ provider: this.instances.toProvider()
935
+ });
936
+ } else {
937
+ this.refreshTimer = setInterval(() => void this.refreshFromRecord(), AGENT_REFRESH_MS);
938
+ this.refreshTimer.unref?.();
939
+ }
940
+ await this.refreshFromRecord();
941
+ }
942
+ await this.destination.initialize(this.destinationConfig());
943
+ const url = this.current?.url ?? "";
944
+ this.ctx.logger.info(url.length > 0 ? `Loki logging initialized → ${url}` : "Loki logging registered but inactive (no URL set)");
945
+ this.attemptEnabledFlagRetirement(0);
946
+ return registrations;
947
+ }
948
+ async ensureDeclared() {
949
+ const records = this.ctx.records;
950
+ if (records === void 0 || this.declared) return;
951
+ await records.declare({ destinations: lokiDestinationsKind });
952
+ this.declared = true;
953
+ }
954
+ async ensureDeclaredQuietly() {
955
+ try {
956
+ await this.ensureDeclared();
957
+ } catch (err) {
958
+ this.ctx.logger.warn("Loki logging: the connection kind could not be declared yet", { meta: { error: err instanceof Error ? err.message : String(err) } });
959
+ }
960
+ }
961
+ /** Re-read the connection record and apply it to the live destination. */
962
+ async refreshFromRecord() {
963
+ if (this.instances === null || this.shuttingDown) return;
964
+ let first;
965
+ try {
966
+ if (!this.declared) await this.ensureDeclared();
967
+ [first] = await this.instances.listResolved();
968
+ } catch (err) {
969
+ this.ctx.logger.warn("Loki logging: the connection record could not be read", { meta: { error: err instanceof Error ? err.message : String(err) } });
970
+ return;
971
+ }
972
+ if (first?.secrets === "unavailable") {
973
+ if (!this.secretsWarned) {
974
+ this.secretsWarned = true;
975
+ this.ctx.logger.warn("Loki logging: the keychain is locked; the destination keeps its previous configuration");
976
+ }
977
+ return;
978
+ }
979
+ this.secretsWarned = false;
980
+ this.current = first?.body ?? null;
981
+ await this.destination?.reconfigure(this.destinationConfig());
982
+ }
983
+ /** The ports of the connection migrations: the old settings in, the record out. */
984
+ migrationPorts() {
985
+ const records = this.ctx.records;
986
+ const instances = this.instances;
987
+ if (records === void 0 || instances === null) throw new Error("records are not available");
988
+ const handle = records.kind(lokiDestinationsKind);
989
+ return {
990
+ readStored: async () => {
991
+ const stored = await this.resolveGlobalStore();
992
+ const password = stored["password"];
993
+ if (isSecretMarker(password)) throw new Error("the old Loki password could not be resolved");
994
+ return stored;
995
+ },
996
+ readRawStored: async () => this.resolveGlobalStore(),
997
+ warn: (message) => {
998
+ this.ctx.logger.warn(message);
999
+ },
1000
+ findIntegration: async () => {
1001
+ return (await this.ctx.api.integrations.getByAddonId.query({ addonId: this.ctx.id }))?.id ?? null;
1002
+ },
1003
+ readRecord: async (id) => {
1004
+ const row = await handle.getResolved(id);
1005
+ if (row === null) return null;
1006
+ return {
1007
+ url: row.data.url,
1008
+ hasPassword: (row.data.password ?? "").length > 0
1009
+ };
1010
+ },
1011
+ ensureIntegration: async (name) => {
1012
+ const existing = await this.ctx.api.integrations.getByAddonId.query({ addonId: this.ctx.id });
1013
+ if (existing !== null && existing !== void 0) return existing.id;
1014
+ return (await this.ctx.api.integrations.create.mutate({
1015
+ addonId: this.ctx.id,
1016
+ name,
1017
+ skipRestart: true
1018
+ })).id;
1019
+ },
1020
+ putRecord: async (id, body) => {
1021
+ if (await handle.get(id) !== null) return "exists";
1022
+ try {
1023
+ await handle.put({
1024
+ id,
1025
+ data: body
1026
+ }, { ifRev: 0 });
1027
+ } catch (err) {
1028
+ if (err instanceof RevConflictError) return "exists";
1029
+ throw err;
1030
+ }
1031
+ return "created";
1032
+ },
1033
+ clearOldPassword: async () => {
1034
+ await this.clearSecrets(["password"]);
1035
+ }
1036
+ };
1037
+ }
1038
+ /** Probe a Loki instance (`/ready`) with the form's values, falling back to the stored ones. */
1039
+ async probe(id, values) {
1040
+ const stored = id !== null && this.instances !== null ? await this.instances.getResolved(id) : null;
1041
+ const typed = (key) => {
1042
+ const value = values[key];
1043
+ return typeof value === "string" && value.length > 0 ? value : stored?.[key] ?? "";
1044
+ };
1045
+ const url = typed("url");
1046
+ if (url.length === 0) return {
1047
+ success: false,
1048
+ status: "rejected",
1049
+ error: "No Loki URL set"
1050
+ };
1051
+ const password = values["password"];
1052
+ const fresh = typeof password === "string" && password.length > 0 && password !== "__camstack_redacted__" && !isSecretFieldView(password);
1053
+ const headers = probeHeaders({
1054
+ username: typed("username"),
1055
+ tenantId: typed("tenantId"),
1056
+ password: fresh ? password : stored?.password ?? ""
1057
+ });
1058
+ const started = Date.now();
1059
+ try {
1060
+ const res = await fetch(new URL(READY_PATH, url), {
1061
+ headers,
1062
+ signal: AbortSignal.timeout(stored?.timeoutMs ?? LOKI_DEFAULT_BODY.timeoutMs)
1063
+ });
1064
+ return res.ok ? {
1065
+ success: true,
1066
+ status: "validated",
1067
+ latencyMs: Date.now() - started
1068
+ } : {
1069
+ success: false,
1070
+ status: "rejected",
1071
+ error: `Loki answered HTTP ${res.status}`
1072
+ };
1073
+ } catch (err) {
1074
+ return {
1075
+ success: false,
1076
+ status: "inconclusive",
1077
+ error: stripUserinfo(err instanceof Error ? err.message : String(err), url)
1078
+ };
1079
+ }
681
1080
  }
682
1081
  /** One attempt of the D777 carry-over; reschedules itself while deferred. */
683
1082
  async attemptEnabledFlagRetirement(attempt) {
@@ -729,6 +1128,8 @@ var LokiLoggingAddon = class extends BaseAddon {
729
1128
  this.shuttingDown = true;
730
1129
  if (this.retirementTimer !== null) clearTimeout(this.retirementTimer);
731
1130
  this.retirementTimer = null;
1131
+ if (this.refreshTimer !== null) clearInterval(this.refreshTimer);
1132
+ this.refreshTimer = null;
732
1133
  await this.destination?.shutdown();
733
1134
  this.destination = null;
734
1135
  }
@@ -740,8 +1141,7 @@ var LokiLoggingAddon = class extends BaseAddon {
740
1141
  * pushing. Without this the destination keeps its boot-time config forever.
741
1142
  */
742
1143
  async onConfigChanged() {
743
- await this.destination?.reconfigure(this.destinationConfig());
744
- this.ctx.logger.info(this.config.url.length > 0 ? `Loki logging reconfigured → ${this.config.url}` : "Loki logging now inactive (no URL)");
1144
+ await this.refreshFromRecord();
745
1145
  }
746
1146
  /**
747
1147
  * `node` is a Loki LABEL, so it must be the node's real identity and must not
@@ -755,17 +1155,30 @@ var LokiLoggingAddon = class extends BaseAddon {
755
1155
  * would have broken this addon's settings reload.
756
1156
  */
757
1157
  destinationConfig() {
1158
+ const body = this.current ?? {
1159
+ ...LOKI_DEFAULT_BODY,
1160
+ name: ""
1161
+ };
758
1162
  return {
759
- ...this.config,
760
1163
  enabled: true,
761
- node: this.ctx.kernel.localNodeId ?? "hub"
1164
+ url: body.url,
1165
+ job: body.job,
1166
+ node: this.ctx.kernel.localNodeId ?? "hub",
1167
+ level: body.level,
1168
+ batchIntervalMs: body.batchIntervalMs,
1169
+ batchSize: body.batchSize,
1170
+ extraLabels: body.extraLabels,
1171
+ tenantId: body.tenantId,
1172
+ username: body.username,
1173
+ password: body.password ?? "",
1174
+ timeoutMs: body.timeoutMs
762
1175
  };
763
1176
  }
764
1177
  getDestination() {
765
1178
  if (!this.destination) throw new Error("Loki logging not initialized");
766
1179
  return this.destination;
767
1180
  }
768
- globalSettingsSchema() {
1181
+ connectionForm() {
769
1182
  return this.schema({ sections: [{
770
1183
  id: "loki-logging",
771
1184
  title: "Loki",
@@ -16,27 +16,36 @@
16
16
  *
17
17
  * Why Loki's push API rather than Promtail: see the docblock in `loki-payload.ts`.
18
18
  */
19
- import type { ConfigUISchema, LogLevel, ProviderRegistration } from "@camstack/types";
19
+ import type { ProviderRegistration } from "@camstack/types";
20
20
  import { BaseAddon } from "@camstack/types";
21
21
  import { LokiDestination } from "./loki-destination.js";
22
- interface LokiAddonConfig {
23
- readonly url: string;
24
- readonly job: string;
25
- readonly level: LogLevel;
26
- readonly batchIntervalMs: number;
27
- readonly batchSize: number;
28
- readonly extraLabels: string;
29
- readonly tenantId: string;
30
- readonly username: string;
31
- readonly password: string;
32
- readonly timeoutMs: number;
33
- }
22
+ /**
23
+ * The addon keeps NO connection setting of its own (D985): the connection is a `destinations`
24
+ * record. What remains in the settings store is the D777 retirement marker only.
25
+ */
26
+ type LokiAddonConfig = Readonly<Record<string, unknown>>;
27
+ /** A failure message with the userinfo of any URL in it (and the typed URL's own) removed. */
28
+ export declare function stripUserinfo(message: string, typedUrl: string): string;
34
29
  export declare class LokiLoggingAddon extends BaseAddon<LokiAddonConfig> {
35
30
  private destination;
31
+ private instances;
32
+ private current;
33
+ private refreshTimer;
36
34
  private retirementTimer;
37
35
  private shuttingDown;
36
+ private declared;
37
+ private secretsWarned;
38
38
  constructor();
39
+ private isHub;
39
40
  protected onInitialize(): Promise<ProviderRegistration[]>;
41
+ private ensureDeclared;
42
+ private ensureDeclaredQuietly;
43
+ /** Re-read the connection record and apply it to the live destination. */
44
+ private refreshFromRecord;
45
+ /** The ports of the connection migrations: the old settings in, the record out. */
46
+ private migrationPorts;
47
+ /** Probe a Loki instance (`/ready`) with the form's values, falling back to the stored ones. */
48
+ private probe;
40
49
  /** One attempt of the D777 carry-over; reschedules itself while deferred. */
41
50
  private attemptEnabledFlagRetirement;
42
51
  protected onShutdown(): Promise<void>;
@@ -61,6 +70,6 @@ export declare class LokiLoggingAddon extends BaseAddon<LokiAddonConfig> {
61
70
  */
62
71
  private destinationConfig;
63
72
  getDestination(): LokiDestination;
64
- protected globalSettingsSchema(): ConfigUISchema;
73
+ private connectionForm;
65
74
  }
66
75
  export {};
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The Loki connection as a record (D985): one `destinations` row per Loki instance, owned by
3
+ * `loki-logging`, listed on the Integrations page like any other connection. The row id is the
4
+ * `integrations` registry id (`int_NNNN`). The password is a keychain marker bound to the row.
5
+ *
6
+ * The kind name is `destinations` (kind names are lower-case-dashed); the owner is `loki-logging`.
7
+ */
8
+ import { type DefinedRecordKind } from "@camstack/types";
9
+ import { z } from "zod";
10
+ export interface LokiBound {
11
+ readonly min: number;
12
+ readonly max: number;
13
+ }
14
+ /** The inclusive bounds of the numeric fields: the schema and the settings migration read ONE copy. */
15
+ export declare const LOKI_BOUNDS: Readonly<Record<"batchIntervalMs" | "batchSize" | "timeoutMs", LokiBound>>;
16
+ export type LokiDestinationBody = {
17
+ readonly name: string;
18
+ readonly url: string;
19
+ readonly level: "debug" | "info" | "warn" | "error";
20
+ readonly job: string;
21
+ readonly extraLabels: string;
22
+ readonly tenantId: string;
23
+ readonly username: string;
24
+ readonly password?: string | undefined;
25
+ readonly batchIntervalMs: number;
26
+ readonly batchSize: number;
27
+ readonly timeoutMs: number;
28
+ };
29
+ /** The schema is checked against the interface by its annotation: a drifted field fails the typecheck. */
30
+ export declare const LokiDestinationBodySchema: z.ZodType<LokiDestinationBody>;
31
+ export declare const LOKI_DESTINATIONS_KIND_NAME = "destinations";
32
+ export declare const lokiDestinationsKind: DefinedRecordKind<z.ZodType<LokiDestinationBody>>;
33
+ export declare const LOKI_DEFAULT_BODY: Omit<LokiDestinationBody, "name">;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The Loki connection moves from the addon's settings into a `destinations` record (D985):
3
+ * an integration row in the registry, a record under that id, and the password re-bound to
4
+ * the record's keychain slot. The old keys are deleted by the second migration of the
5
+ * catalogue (`dropMovedSettings`), only after this one succeeded.
6
+ *
7
+ * Idempotent and ordered so a crash is safe: nothing is written before the old settings are
8
+ * read in full (a password that cannot be resolved aborts the pass); an existing record is
9
+ * never overwritten; the old password is cleared only once the record verifiably holds it.
10
+ */
11
+ import { type MigrationPlan, type MigrationProcedureResult } from "@camstack/types";
12
+ import { type LokiDestinationBody } from "../loki-record-kinds.js";
13
+ /** The settings scope of this addon (`<addonId>:addon-settings`). */
14
+ export declare const LOKI_SETTINGS_SCOPE = "loki-logging:addon-settings";
15
+ /** The connection keys the record now owns. `password` is the secret, cleared separately. */
16
+ export declare const MOVED_PLAIN_KEYS: readonly string[];
17
+ /** What the migrations say about a decision they took; never carries a value. */
18
+ export interface LokiMigrationLog {
19
+ warn(message: string): void;
20
+ }
21
+ /** What the destinations record holds, as far as the migrations care. */
22
+ export interface LokiRecordState {
23
+ readonly url: string;
24
+ readonly hasPassword: boolean;
25
+ }
26
+ export interface LokiMigrationPorts extends LokiMigrationLog {
27
+ /** The stored settings, secrets resolved. Throws when a secret cannot be resolved. */
28
+ readStored(): Promise<Readonly<Record<string, unknown>>>;
29
+ /** The id of the `integrations` row for this addon, created when absent. */
30
+ ensureIntegration(name: string): Promise<string>;
31
+ /** Put the record under `id` with `ifRev: 0`; `exists` when a record is already there. */
32
+ putRecord(id: string, body: LokiDestinationBody): Promise<"created" | "exists">;
33
+ /** The record under `id`, secret resolved; null when absent. Throws when it cannot be read. */
34
+ readRecord(id: string): Promise<LokiRecordState | null>;
35
+ /** Remove the old password and its keychain value. */
36
+ clearOldPassword(): Promise<void>;
37
+ }
38
+ export declare function moveConnectionToRecord(ports: LokiMigrationPorts): Promise<MigrationProcedureResult>;
39
+ export interface DropMovedSettingsPorts extends LokiMigrationLog {
40
+ /** The id of the `integrations` row for this addon; null when it has none. */
41
+ findIntegration(): Promise<string | null>;
42
+ /** The record under `id`, secret resolved; null when absent. Throws when it cannot be read. */
43
+ readRecord(id: string): Promise<LokiRecordState | null>;
44
+ /** The addon's stored settings as written (markers unresolved), unparsed. */
45
+ readRawStored(): Promise<Readonly<Record<string, unknown>>>;
46
+ }
47
+ export declare function planDropMovedSettings(ports: DropMovedSettingsPorts): Promise<MigrationPlan>;
@@ -0,0 +1,8 @@
1
+ import type { AddonMigration } from "@camstack/types";
2
+ import { type DropMovedSettingsPorts, type LokiMigrationPorts } from "./connection-to-records.js";
3
+ export type { DropMovedSettingsPorts, LokiMigrationLog, LokiMigrationPorts, LokiRecordState } from "./connection-to-records.js";
4
+ /** Both bodies read through ONE port object, so the addon binds the catalogue once. */
5
+ export type LokiCataloguePorts = LokiMigrationPorts & DropMovedSettingsPorts;
6
+ export declare const CONNECTION_TO_RECORDS_ID = "loki-logging/2026-11-02-connection-to-records";
7
+ /** The `loki-logging` catalogue (D987): offered to the engine when the hub-resident addon initialises. */
8
+ export declare const ADDON_MIGRATIONS: readonly AddonMigration<LokiCataloguePorts>[];