@camstack/server 1.2.788 → 1.2.790

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 (127) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/agent/agent-child-manifest.js +39 -0
  3. package/dist/agent/agent-hub-registration.js +11 -1
  4. package/dist/agent/forward-to-hub.js +43 -0
  5. package/dist/agent/main.js +31 -81
  6. package/dist/agent/stale-addon-gate.js +70 -34
  7. package/dist/api/trpc/generated-cap-mounts.js +1 -6
  8. package/dist/api/trpc/generated-cap-routers.js +1221 -1417
  9. package/dist/core/addon/addon-registry.service.js +25 -33
  10. package/dist/core/addon/boot-health-snapshot.js +0 -28
  11. package/dist/core/addon/{hub-spawn-gate.js → hub-addon-support.js} +12 -35
  12. package/dist/core/moleculer/moleculer.service.js +2 -13
  13. package/dist/core/moleculer/runner-hosted-on-node.js +23 -0
  14. package/dist/core/updates/required-addon-update.js +1 -1
  15. package/package.json +23 -58
  16. package/system/dist/addon-utils.mjs +1 -1
  17. package/system/dist/{agent-https-jJDe-XNl.js → agent-https-BmXXKQAA.js} +1 -1
  18. package/system/dist/{agent-https-szf2FU49.mjs → agent-https-ByceQLwr.mjs} +1 -1
  19. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  20. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +4 -4
  21. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  22. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +5 -5
  23. package/system/dist/builtins/alerts/alerts.addon.d.ts +8 -0
  24. package/system/dist/builtins/alerts/alerts.addon.js +72 -1
  25. package/system/dist/builtins/alerts/alerts.addon.mjs +74 -3
  26. package/system/dist/builtins/autotrack/index.js +1 -1
  27. package/system/dist/builtins/autotrack/index.mjs +1 -1
  28. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  29. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +5 -5
  30. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  31. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  32. package/system/dist/builtins/camera-grid/index.js +1 -1
  33. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  34. package/system/dist/builtins/composer/composer.addon.js +3 -3
  35. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  36. package/system/dist/builtins/console-logging/index.js +1 -1
  37. package/system/dist/builtins/console-logging/index.mjs +1 -1
  38. package/system/dist/builtins/core-blocks/core-blocks.addon.js +11 -5
  39. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +11 -5
  40. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  41. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  42. package/system/dist/builtins/device-manager/device-manager.addon.js +1 -1
  43. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  44. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  45. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  46. package/system/dist/builtins/keychain/index.js +4 -4
  47. package/system/dist/builtins/keychain/index.mjs +4 -4
  48. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  49. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  50. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  51. package/system/dist/builtins/local-auth/local-auth.addon.mjs +5 -5
  52. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  53. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  54. package/system/dist/builtins/loki-logging/index.js +1 -1
  55. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  56. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  57. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +10 -10
  58. package/system/dist/builtins/platform-probe/index.js +1 -1
  59. package/system/dist/builtins/platform-probe/index.mjs +10 -10
  60. package/system/dist/builtins/record-entries/index.js +1 -1
  61. package/system/dist/builtins/record-entries/index.mjs +1 -1
  62. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  63. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  64. package/system/dist/builtins/snapshot/index.js +1 -1
  65. package/system/dist/builtins/snapshot/index.mjs +1 -1
  66. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  67. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +20 -20
  68. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  69. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  70. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  71. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  72. package/system/dist/builtins/storage-orchestrator/access-guards.d.ts +1 -1
  73. package/system/dist/builtins/storage-orchestrator/custom-actions.d.ts +11 -0
  74. package/system/dist/builtins/storage-orchestrator/index.d.ts +1 -0
  75. package/system/dist/builtins/storage-orchestrator/index.js +2 -0
  76. package/system/dist/builtins/storage-orchestrator/index.mjs +2 -2
  77. package/system/dist/builtins/storage-orchestrator/location-instances.d.ts +72 -0
  78. package/system/dist/builtins/storage-orchestrator/location-repoint-move.d.ts +1 -1
  79. package/system/dist/builtins/storage-orchestrator/location-secret-refs.d.ts +26 -0
  80. package/system/dist/builtins/storage-orchestrator/location-store.d.ts +28 -2
  81. package/system/dist/builtins/storage-orchestrator/migrations/index.d.ts +9 -2
  82. package/system/dist/builtins/storage-orchestrator/migrations/legacy-location-secret-refs.d.ts +13 -0
  83. package/system/dist/builtins/storage-orchestrator/migrations/location-secret-ports.d.ts +15 -0
  84. package/system/dist/builtins/storage-orchestrator/migrations/location-secrets-to-record.d.ts +57 -0
  85. package/system/dist/builtins/storage-orchestrator/provider-discovery.d.ts +10 -13
  86. package/system/dist/builtins/storage-orchestrator/record-kinds.d.ts +6 -0
  87. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.d.ts +39 -8
  88. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +954 -131
  89. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +954 -132
  90. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.service.d.ts +8 -0
  91. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  92. package/system/dist/builtins/system-config/system-config.addon.mjs +115 -115
  93. package/system/dist/builtins/winston-logging/index.js +112 -3
  94. package/system/dist/builtins/winston-logging/index.mjs +112 -3
  95. package/system/dist/builtins/winston-logging/migrations/index.d.ts +8 -0
  96. package/system/dist/builtins/winston-logging/migrations/node-fields.d.ts +43 -0
  97. package/system/dist/builtins/winston-logging/winston-logging.addon.d.ts +10 -2
  98. package/system/dist/{capture-engine-DNHgjQot.js → capture-engine-BHj1fNYC.js} +1 -1
  99. package/system/dist/{capture-engine-BsKY_3xa.mjs → capture-engine-D9n4KDaN.mjs} +1 -1
  100. package/system/dist/{composition-sources-BgO0GQYW.js → composition-sources-BGgIuuvd.js} +1 -1
  101. package/system/dist/{composition-sources-BRdGsbVT.mjs → composition-sources-wI4qWTz2.mjs} +1 -1
  102. package/system/dist/{constants-CQeMrR4f.mjs → constants-DHqkxbYk.mjs} +1 -1
  103. package/system/dist/{constants-C3jGKQSQ.js → constants-DNdriMRD.js} +1 -1
  104. package/system/dist/{coral-accelerators-BW3OcrLD.mjs → coral-accelerators-DBlgWB8k.mjs} +6 -6
  105. package/system/dist/{custom-action-registry-N7flBDwT.mjs → custom-action-registry-B9zFBNVa.mjs} +37 -37
  106. package/system/dist/{device-ca-D3y6wGmn.js → device-ca-C2RzT1VT.js} +1 -1
  107. package/system/dist/{device-ca-ByVi5eUC.mjs → device-ca-gr5eE3h5.mjs} +1 -1
  108. package/system/dist/{dist-BsQA6-0i.mjs → dist-BUoL5bbr.mjs} +116 -418
  109. package/system/dist/{dist-BRI-Mwx0.js → dist-DV0V3JiE.js} +133 -417
  110. package/system/dist/file-host-worker.js +1 -1
  111. package/system/dist/file-host-worker.mjs +1 -1
  112. package/system/dist/{hub-mdns-ciao-Ry_Jpljx.js → hub-mdns-ciao-Be5PGXW6.js} +2 -2
  113. package/system/dist/{hub-mdns-ciao-8dJTW2LI.mjs → hub-mdns-ciao-DoSb8dwB.mjs} +2 -2
  114. package/system/dist/index.js +151 -53
  115. package/system/dist/index.mjs +362 -266
  116. package/system/dist/kernel/addon-health-monitor.d.ts +0 -21
  117. package/system/dist/kernel/index.d.ts +2 -0
  118. package/system/dist/kernel/transport/runner-of-addon.d.ts +2 -0
  119. package/system/dist/kernel/unsupported-addon-tracker.d.ts +74 -0
  120. package/system/dist/{legacy-integration-rows-door-D5BdSNla.js → legacy-integration-rows-door-D5s8oM7e.js} +1 -1
  121. package/system/dist/{legacy-integration-rows-door-CjXTbmvH.mjs → legacy-integration-rows-door-DRC0xn6k.mjs} +1 -1
  122. package/system/dist/migrations/hub/2026-11-06-addon-settings-bare-rows.d.ts +3 -0
  123. package/system/dist/{restore-archive-Co2lk3OU.mjs → restore-archive-DH3P9j-V.mjs} +94 -94
  124. package/system/dist/{restore-archive-GoWJMdHy.js → restore-archive-Dh4gfCRY.js} +1 -1
  125. package/system/dist/{wal-maintenance-DRnV6QYu.mjs → wal-maintenance-BWfH3Lov.mjs} +0 -0
  126. package/system/dist/{wal-maintenance-C1Haue74.js → wal-maintenance-DgN_WD5T.js} +0 -0
  127. package/system/package.json +4 -1
@@ -1,4 +1,4 @@
1
- import { As as defineAddonMigrations, Ci as modeMayWrite, Ec as EventCategory, Lo as BaseAddon, Lr as gbToBytes, Ma as storageCapability, Na as storageMigrationCapability, Ns as defineRecordKinds, Sa as settingsStoreCapability, Tr as evictionPolicyOfLocation, Xs as isSecretMarker, Zr as isLocationEnabled, ai as legacyModeOf, dc as resolveSecretMarkers, en as StorageCleanupJobSchema, gi as mayWriteToLocation, hi as mayReadLocation, la as resolveLocationMode, nn as StorageLocationTypeSchema, pc as secretTreeFromPaths, rc as normalizeNodeId, rn as StorageMigrationJobSchema, tn as StorageLocationModeSchema, to as withLocationMode, ts as REDACTED_SECRET, ws as collectSecretConfigKeys, xt as LegacyStorageLocationDefaultSchema, yc as transformSecretWrite } from "../../dist-BsQA6-0i.mjs";
1
+ import { $s as isSecretMarker, Bo as BaseAddon, Ds as collectSecretConfigKeys, Er as evictionPolicyOfLocation, Es as buildSecretRef, Fa as storageMigrationCapability, Ha as switchStateOfMode, Is as defineRecordKinds, Jt as STORAGE_LOCATION_MODES, Ms as customAction, Ns as defineAddonMigrations, Pa as storageCapability, Ps as defineCustomActions, Qr as isLocationEnabled, Qs as isSecretFieldView, Rr as gbToBytes, Ti as modeMayWrite, Vr as integrationInstancesCapability, Zs as isSecretClear, _i as mayWriteToLocation, da as resolveLocationMode, fc as recordSecretRef, gi as mayReadLocation, in as StorageMigrationJobSchema, io as withLocationMode, is as REDACTED_SECRET, kc as EventCategory, mc as resolveSecretMarkers, nc as makeSecretMarker, nn as StorageLocationModeSchema, oc as normalizeNodeId, oi as legacyModeOf, rn as StorageLocationTypeSchema, tn as StorageCleanupJobSchema, uc as parseSecretRef, wa as settingsStoreCapability, wi as modeForSwitch, xc as toSecretFieldView, xt as LegacyStorageLocationDefaultSchema } from "../../dist-BUoL5bbr.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
3
  import { z } from "zod";
4
4
  import { randomUUID } from "node:crypto";
@@ -7,6 +7,39 @@ import * as path$1 from "node:path";
7
7
  import path from "node:path";
8
8
  import * as fs from "node:fs/promises";
9
9
  import { opendir, readdir } from "node:fs/promises";
10
+ //#region src/builtins/storage-orchestrator/location-secret-refs.ts
11
+ /**
12
+ * Where a storage location's credentials live (planning#440 step 6, D879, D987).
13
+ *
14
+ * A credential is a keychain value bound to the location's OWN record: the body's `secrets` map
15
+ * (`secrets{password}`) is what the records door stores, so deleting the row deletes the value and
16
+ * one location's credential is never another's. Before this, the credential was filed under
17
+ * `row/storage_locations/<id>` and the row's `config` held the marker; those refs are the LEGACY
18
+ * ones the migration `storage-orchestrator/2026-11-07-location-secrets-to-record` moves.
19
+ *
20
+ * The in-memory location still carries a marker per credential in `config` (the orchestrator
21
+ * resolves it through `ctx.secrets` when a provider needs the value); the marker built here is the
22
+ * one the records door itself wrote, so both ends agree without a read.
23
+ */
24
+ /** The addon id the records door and the keychain both file this owner's values under. */
25
+ var STORAGE_RECORD_OWNER = "storage-orchestrator";
26
+ /** The record kind the locations live in (`record-kinds.ts`). */
27
+ var LOCATIONS_RECORD_KIND = "locations";
28
+ /** The body field that holds the credentials, by config key. */
29
+ var LOCATION_SECRETS_FIELD = "secrets";
30
+ /** The ref the records door files the credential `key` of location `id` under. */
31
+ function locationSecretRef(id, key) {
32
+ return recordSecretRef(STORAGE_RECORD_OWNER, LOCATIONS_RECORD_KIND, id, `${LOCATION_SECRETS_FIELD}{${encodeURIComponent(key)}}`);
33
+ }
34
+ /** The marker the location carries in memory for a credential kept in its record. */
35
+ function locationSecretMarker(id, key) {
36
+ return makeSecretMarker(locationSecretRef(id, key));
37
+ }
38
+ /** Is `value` the marker of the credential `key` of location `id` kept in its own record? */
39
+ function isOwnLocationMarker(id, key, value) {
40
+ return isSecretMarker(value) && value.$secret === locationSecretRef(id, key);
41
+ }
42
+ //#endregion
10
43
  //#region src/builtins/storage-orchestrator/record-kinds.ts
11
44
  var import_read_all_rows = require_read_all_rows();
12
45
  var StorageLocationBodySchema = z.object({
@@ -20,7 +53,8 @@ var StorageLocationBodySchema = z.object({
20
53
  nodeId: z.string().optional(),
21
54
  enabled: z.boolean().optional(),
22
55
  mode: StorageLocationModeSchema.optional(),
23
- isDefault: z.boolean().optional()
56
+ isDefault: z.boolean().optional(),
57
+ secrets: z.record(z.string(), z.string().meta({ secret: true })).optional()
24
58
  });
25
59
  var StorageSeedMarkerBodySchema = z.object({ seededAt: z.number() });
26
60
  var StorageDrainStateBodySchema = z.object({
@@ -73,11 +107,43 @@ _storageOrchestratorRecordKinds["drain-state"];
73
107
  //#endregion
74
108
  //#region src/builtins/storage-orchestrator/location-store.ts
75
109
  /**
76
- * The keychain scope collection a storage location's secret fields are filed
77
- * under (`row/storage_locations/<id>`). The table it was named for is gone; the
78
- * string stays because existing secret markers point at it.
110
+ * Credentials a save carries, by config key, until the store writes the row: a value sets the
111
+ * credential, `null` removes it. The service persists without waiting (`upsert` is fire and
112
+ * forget), so the plaintext cannot ride on the location itself; it is staged here, one shot per
113
+ * location id, and `SqliteLocationStore.upsert` hands it to the records door with the row.
79
114
  */
80
- var STORAGE_LOCATIONS_SECRET_SCOPE = "storage_locations";
115
+ var LocationSecretStaging = class {
116
+ staged = /* @__PURE__ */ new Map();
117
+ waiting = /* @__PURE__ */ new Map();
118
+ settledBy = /* @__PURE__ */ new Map();
119
+ stage(id, secrets) {
120
+ if (Object.keys(secrets).length === 0) return;
121
+ this.staged.set(id, secrets);
122
+ this.settledBy.set(id, new Promise((resolve) => {
123
+ this.waiting.set(id, resolve);
124
+ }));
125
+ }
126
+ /** The staged credentials of `id`, once; a save that was refused discards them instead. */
127
+ take(id) {
128
+ const secrets = this.staged.get(id) ?? {};
129
+ this.staged.delete(id);
130
+ return secrets;
131
+ }
132
+ /** The row of `id` is written (or the write failed): whoever waits for the credential may go on. */
133
+ written(id) {
134
+ this.waiting.get(id)?.();
135
+ this.waiting.delete(id);
136
+ this.settledBy.delete(id);
137
+ }
138
+ discard(id) {
139
+ this.staged.delete(id);
140
+ this.written(id);
141
+ }
142
+ /** Resolves when the staged credentials of `id` are written; at once when none are staged. */
143
+ settled(id) {
144
+ return this.settledBy.get(id) ?? Promise.resolve();
145
+ }
146
+ };
81
147
  /**
82
148
  * `ILocationStore` on the storage-orchestrator's own record kinds (`locations`
83
149
  * and `seed-markers`).
@@ -85,9 +151,11 @@ var STORAGE_LOCATIONS_SECRET_SCOPE = "storage_locations";
85
151
  var SqliteLocationStore = class {
86
152
  locationsKind;
87
153
  seedMarkersKind;
88
- constructor(locationsKind, seedMarkersKind) {
154
+ staging;
155
+ constructor(locationsKind, seedMarkersKind, staging = new LocationSecretStaging()) {
89
156
  this.locationsKind = locationsKind;
90
157
  this.seedMarkersKind = seedMarkersKind;
158
+ this.staging = staging;
91
159
  }
92
160
  static seedMarkersOf(records) {
93
161
  return records.kind(storageOrchestratorRecordKinds["seed-markers"]);
@@ -118,22 +186,40 @@ var SqliteLocationStore = class {
118
186
  return out;
119
187
  }
120
188
  async upsert(loc) {
121
- const data = storageOrchestratorRecordKinds.locations.schema.parse(locationToBody(loc));
122
- await this.locationsKind.put({
123
- id: loc.id,
124
- data
125
- });
189
+ const staged = this.staging.take(loc.id);
190
+ try {
191
+ const data = storageOrchestratorRecordKinds.locations.schema.parse(locationToBody(loc, staged));
192
+ await this.locationsKind.put({
193
+ id: loc.id,
194
+ data
195
+ });
196
+ } finally {
197
+ this.staging.written(loc.id);
198
+ }
126
199
  }
127
200
  async delete(id) {
128
201
  await this.locationsKind.delete(id);
129
202
  }
130
203
  };
131
- function locationToBody(loc) {
204
+ /**
205
+ * The body a location is stored as. A credential the location keeps in its own record (the marker
206
+ * of `location-secret-refs.ts`) leaves `config` for `secrets`, where the records door keeps the
207
+ * value and the redaction token means "keep what is stored"; `staged` sets or removes one. Any
208
+ * other marker (a legacy ref the migration has not moved yet) stays in `config` untouched.
209
+ */
210
+ function locationToBody(loc, staged = {}) {
211
+ const config = {};
212
+ const secrets = {};
213
+ for (const [key, value] of Object.entries(loc.config)) if (isOwnLocationMarker(loc.id, key, value)) secrets[key] = REDACTED_SECRET;
214
+ else config[key] = value;
215
+ for (const [key, value] of Object.entries(staged)) if (value === null) delete secrets[key];
216
+ else secrets[key] = value;
132
217
  return {
133
218
  type: loc.type,
134
219
  displayName: loc.displayName,
135
220
  providerId: loc.providerId,
136
- config: { ...loc.config },
221
+ config,
222
+ ...Object.keys(secrets).length > 0 ? { secrets } : {},
137
223
  isSystem: loc.isSystem,
138
224
  createdAt: loc.createdAt,
139
225
  updatedAt: loc.updatedAt,
@@ -150,7 +236,10 @@ function bodyToPersistedLocation(id, body) {
150
236
  type: parsedType.data,
151
237
  displayName: body.displayName,
152
238
  providerId: body.providerId,
153
- config: { ...body.config },
239
+ config: {
240
+ ...body.config,
241
+ ...Object.fromEntries(Object.keys(body.secrets ?? {}).map((key) => [key, locationSecretMarker(id, key)]))
242
+ },
154
243
  ...body.nodeId !== void 0 ? { nodeId: body.nodeId } : {},
155
244
  ...body.enabled !== void 0 ? { enabled: body.enabled } : {},
156
245
  ...body.mode !== void 0 ? { mode: body.mode } : {},
@@ -233,7 +322,7 @@ var StorageMigrationCoordinator = class {
233
322
  if (target.type !== storageClass) throw new Error(`Storage location "${targetId}" is type "${target.type}", expected "${storageClass}"`);
234
323
  if (source.id === target.id) throw new Error(namedSourceId ? `Source and destination are the same location ("${targetId}")` : `Storage location "${targetId}" is already the only write target for "${storageClass}"`);
235
324
  const freezeSource = !writeSet.some((loc) => loc.id === source.id);
236
- if (!MOVER_CLASSES.includes(storageClass)) throw new Error(`No mover owns "${storageClass}" — the migration can move its write set but cannot move its bytes. Move it by hand, then enable the destination (and disable the source) with upsertLocation.`);
325
+ if (!MOVER_CLASSES.includes(storageClass)) throw new Error(`No mover owns "${storageClass}" — the migration can move its write set but cannot move its bytes. Move it by hand, then enable the destination (and disable the source) from the Storage page.`);
237
326
  moves.push({
238
327
  storageClass,
239
328
  fromLocationId: source.id,
@@ -1016,11 +1105,121 @@ function buildStorageLocationRegistry(perAddon) {
1016
1105
  }
1017
1106
  };
1018
1107
  }
1019
- /** The `storage-orchestrator` catalogue (D987): offered to the engine once the seed state is known. */
1108
+ //#endregion
1109
+ //#region src/builtins/storage-orchestrator/migrations/legacy-location-secret-refs.ts
1110
+ /**
1111
+ * The keychain refs a storage location's credentials were filed under BEFORE they moved into the
1112
+ * location's own record (`row/storage_locations/<id>`). Only the migration
1113
+ * `storage-orchestrator/2026-11-07-location-secrets-to-record` reads this shape.
1114
+ */
1115
+ /** The keychain collection of the legacy per-row refs (the table it was named for is gone). */
1116
+ var LEGACY_LOCATION_SECRET_COLLECTION = "storage_locations";
1117
+ /** The ref a credential of `id` was filed under before the move to the record. */
1118
+ function legacyLocationSecretRef(id, key) {
1119
+ return buildSecretRef({
1120
+ owner: STORAGE_RECORD_OWNER,
1121
+ scope: {
1122
+ kind: "row",
1123
+ collection: LEGACY_LOCATION_SECRET_COLLECTION,
1124
+ rowId: id
1125
+ },
1126
+ fieldPath: key
1127
+ });
1128
+ }
1129
+ /**
1130
+ * Is `value` a marker the migration has to move: a keychain marker of THIS location's legacy
1131
+ * collection. Anything else (a record-bound marker, someone else's ref) is left alone.
1132
+ */
1133
+ function isLegacyLocationMarker(id, value) {
1134
+ if (!isSecretMarker(value)) return false;
1135
+ const parts = parseSecretRef(value.$secret);
1136
+ if (parts === null || parts.scope.kind !== "row") return false;
1137
+ return parts.scope.collection === LEGACY_LOCATION_SECRET_COLLECTION && parts.scope.rowId === id;
1138
+ }
1139
+ //#endregion
1140
+ //#region src/builtins/storage-orchestrator/migrations/location-secrets-to-record.ts
1141
+ function sameSecrets(back, expected) {
1142
+ const entries = (value) => JSON.stringify(Object.entries(value).toSorted(([a], [b]) => a < b ? -1 : 1));
1143
+ return entries(back) === entries(expected);
1144
+ }
1145
+ /**
1146
+ * Release the legacy values a row already moved off of. Fail-safe in both directions: a keychain
1147
+ * that cannot answer, or a record credential that does not resolve, releases nothing here (the
1148
+ * next boot looks again); nothing is ever released on a guess.
1149
+ */
1150
+ async function sweepStrandedLegacy(ports, all) {
1151
+ const candidates = all.filter((row) => Object.keys(row.legacy).length === 0 && row.recorded.length > 0);
1152
+ if (candidates.length === 0) return 0;
1153
+ const refOf = (row, key) => legacyLocationSecretRef(row.id, key);
1154
+ const answers = await ports.resolveLegacy(candidates.flatMap((row) => row.recorded.map((key) => refOf(row, key))));
1155
+ const stranded = [];
1156
+ for (const row of candidates) {
1157
+ const present = row.recorded.filter((key) => answers.get(refOf(row, key))?.kind === "value");
1158
+ if (present.length === 0) continue;
1159
+ const moved = await ports.readMoved(row.id).catch(() => null);
1160
+ for (const key of present) if ((moved?.secrets[key] ?? "") !== "") stranded.push(refOf(row, key));
1161
+ }
1162
+ if (stranded.length > 0) await ports.releaseLegacy(stranded);
1163
+ return stranded.length;
1164
+ }
1165
+ async function moveLocationSecretsToRecords(ports) {
1166
+ const all = await ports.readLegacy();
1167
+ const released = await sweepStrandedLegacy(ports, all);
1168
+ const rows = all.filter((row) => Object.keys(row.legacy).length > 0);
1169
+ if (rows.length === 0) return released > 0 ? {
1170
+ outcome: "done",
1171
+ summary: {
1172
+ locations: 0,
1173
+ credentials: 0,
1174
+ released
1175
+ }
1176
+ } : {
1177
+ outcome: "already-done",
1178
+ summary: { reason: "no-legacy-secrets" }
1179
+ };
1180
+ const refs = [...new Set(rows.flatMap((row) => Object.values(row.legacy).map((m) => m.$secret)))];
1181
+ const answers = await ports.resolveLegacy(refs);
1182
+ const lost = [];
1183
+ for (const row of rows) for (const [key, marker] of Object.entries(row.legacy)) if (answers.get(marker.$secret)?.kind !== "value") lost.push(`${row.id}.${key}`);
1184
+ if (lost.length > 0) throw new Error(`storage-orchestrator: ${lost.length} location credential(s) cannot be read from the keychain (${lost.join(", ")}); nothing was moved`);
1185
+ let moved = 0;
1186
+ let credentials = 0;
1187
+ try {
1188
+ for (const row of rows) {
1189
+ const expected = {};
1190
+ for (const [key, marker] of Object.entries(row.legacy)) {
1191
+ const answer = answers.get(marker.$secret);
1192
+ if (answer?.kind === "value") expected[key] = answer.value;
1193
+ }
1194
+ await ports.moveToRecord(row.id, expected);
1195
+ const back = await ports.readMoved(row.id);
1196
+ const staleKeys = back === null ? [] : back.configKeys.filter((key) => key in expected);
1197
+ if (back === null || !sameSecrets(back.secrets, expected) || staleKeys.length > 0) throw new Error(`storage-orchestrator: location '${row.id}' did not read back as moved; its legacy credentials were kept`);
1198
+ await ports.releaseLegacy(Object.values(row.legacy).map((marker) => marker.$secret));
1199
+ moved += 1;
1200
+ credentials += Object.keys(expected).length;
1201
+ }
1202
+ } finally {
1203
+ if (moved > 0) await ports.refreshLocations();
1204
+ }
1205
+ return {
1206
+ outcome: "done",
1207
+ summary: {
1208
+ locations: moved,
1209
+ credentials
1210
+ }
1211
+ };
1212
+ }
1213
+ //#endregion
1214
+ //#region src/builtins/storage-orchestrator/migrations/index.ts
1215
+ var STORAGE_ORCHESTRATOR_ID = "storage-orchestrator";
1216
+ var RESEED_PRUNED_DEFAULTS_ID = "storage-orchestrator/2026-11-04-reseed-pruned-defaults";
1217
+ var LOCATION_SECRETS_TO_RECORD_ID = "storage-orchestrator/2026-11-07-location-secrets-to-record";
1218
+ /** The `storage-orchestrator` catalogue (D987), declared whole every time and run by id. */
1020
1219
  var ADDON_MIGRATIONS = [{
1021
1220
  meta: {
1022
- id: "storage-orchestrator/2026-11-04-reseed-pruned-defaults",
1023
- owner: "storage-orchestrator",
1221
+ id: RESEED_PRUNED_DEFAULTS_ID,
1222
+ owner: STORAGE_ORCHESTRATOR_ID,
1024
1223
  level: "addon-state",
1025
1224
  seq: 1,
1026
1225
  dependsOn: [],
@@ -1038,8 +1237,76 @@ var ADDON_MIGRATIONS = [{
1038
1237
  summary: { types: [...types] }
1039
1238
  };
1040
1239
  }
1240
+ }, {
1241
+ meta: {
1242
+ id: LOCATION_SECRETS_TO_RECORD_ID,
1243
+ owner: STORAGE_ORCHESTRATOR_ID,
1244
+ level: "addon-state",
1245
+ seq: 2,
1246
+ dependsOn: [],
1247
+ store: "settings",
1248
+ scope: "cluster",
1249
+ onFailure: "block-owner",
1250
+ bodyKind: "procedure",
1251
+ description: "Move each storage location's credentials from the per-row keychain refs into the location's own record",
1252
+ fixtureMark: "a location row that carries no credential (a drain row, recordings:default), which the move must not touch"
1253
+ },
1254
+ procedure: moveLocationSecretsToRecords
1041
1255
  }];
1042
1256
  //#endregion
1257
+ //#region src/builtins/storage-orchestrator/migrations/location-secret-ports.ts
1258
+ function locationSecretPortsOver(deps) {
1259
+ const { locations, secrets } = deps;
1260
+ return {
1261
+ async readLegacy() {
1262
+ return (await (0, import_read_all_rows.readAllRows)(locations)).map((row) => {
1263
+ const legacy = {};
1264
+ for (const [key, value] of Object.entries(row.data.config)) if (isLegacyLocationMarker(row.id, value)) legacy[key] = value;
1265
+ return {
1266
+ id: row.id,
1267
+ legacy,
1268
+ recorded: Object.keys(row.data.secrets ?? {})
1269
+ };
1270
+ });
1271
+ },
1272
+ async resolveLegacy(refs) {
1273
+ const answer = await secrets.resolve(refs);
1274
+ const out = /* @__PURE__ */ new Map();
1275
+ for (const ref of refs) {
1276
+ const entry = answer[ref];
1277
+ if (entry?.kind === "value") out.set(ref, {
1278
+ kind: "value",
1279
+ value: entry.value
1280
+ });
1281
+ else out.set(ref, { kind: entry?.kind === "missing" ? "missing" : "unavailable" });
1282
+ }
1283
+ return out;
1284
+ },
1285
+ async moveToRecord(id, moved) {
1286
+ const removed = {};
1287
+ for (const key of Object.keys(moved)) removed[key] = null;
1288
+ await locations.patch(id, {
1289
+ secrets: moved,
1290
+ config: removed
1291
+ });
1292
+ },
1293
+ async readMoved(id) {
1294
+ const row = await locations.getResolved(id);
1295
+ if (row === null) return null;
1296
+ return {
1297
+ secrets: row.data.secrets ?? {},
1298
+ configKeys: Object.keys(row.data.config)
1299
+ };
1300
+ },
1301
+ async releaseLegacy(refs) {
1302
+ await secrets.delete(refs);
1303
+ },
1304
+ async refreshLocations() {
1305
+ await deps.refreshLocations();
1306
+ }
1307
+ };
1308
+ }
1309
+ //#endregion
1043
1310
  //#region src/builtins/storage-orchestrator/location-occupancy.ts
1044
1311
  /**
1045
1312
  * Delete-time occupancy of a location's on-disk root.
@@ -2053,6 +2320,465 @@ function restoreRedactedSecrets(incoming, stored, secretKeys) {
2053
2320
  return touched ? out : incoming;
2054
2321
  }
2055
2322
  //#endregion
2323
+ //#region src/builtins/storage-orchestrator/custom-actions.ts
2324
+ /**
2325
+ * The forced delete of a storage location (D49). `deleteInstance` keeps the occupancy refusal;
2326
+ * this is the separate, explicit action for a location the check could not read (a removed disk,
2327
+ * another node, a remote provider). The caller states it after a second confirmation.
2328
+ */
2329
+ var forceDeleteLocationInput = z.object({ id: z.string().min(1) });
2330
+ var storageOrchestratorActions = defineCustomActions({ forceDeleteLocation: customAction(forceDeleteLocationInput, z.object({ ok: z.literal(true) }), {
2331
+ kind: "mutation",
2332
+ auth: "admin"
2333
+ }) });
2334
+ //#endregion
2335
+ //#region src/builtins/storage-orchestrator/location-instances.ts
2336
+ /**
2337
+ * The storage locations as `integration-instances` (planning#440 step 6, D985, D986): one
2338
+ * instance per location, one KIND per declared location type (`recordings`, `backups`, ...).
2339
+ * The form is the provider select, the provider's own fields and the location's state; the
2340
+ * credentials the provider declares go to the keychain bound to the location's record
2341
+ * (`location-secret-refs.ts`, D879).
2342
+ *
2343
+ * A location keeps ONE typed state (`mode`, D385) and only `storage-location-mode.ts` reads it.
2344
+ * The row switch maps to it: on is `active`; off is `readonly` (the write switch, D383), and a
2345
+ * location that is already `drain` or `disabled` stays as it is. Delete keeps the occupancy
2346
+ * refusal; the forced delete is NOT a flag here, it is the separate `forceDeleteLocation`
2347
+ * action (D49: destructive, confirmed by a second read).
2348
+ *
2349
+ * The edit form is the provider's schema as it is. The create form offers every provider, so
2350
+ * each provider's fields are namespaced `<providerId>.<key>` and shown for that provider; a
2351
+ * `notEquals` / `notIn` condition on a select is rewritten to the options it leaves, because the
2352
+ * selector of another provider is unset and an unset value would satisfy a negation.
2353
+ */
2354
+ var STORAGE_INSTANCE_KIND = "storage-location";
2355
+ var STORAGE_FUNCTION_CAP = "storage";
2356
+ /** The generic widget id the admin UI maps to its path browser. */
2357
+ var STORAGE_PATH_WIDGET = "storage/path-browser";
2358
+ var PROVIDER_FIELD = "providerId";
2359
+ var MODE_FIELD = "mode";
2360
+ var NODE_FIELD = "nodeId";
2361
+ var MIN_FREE_FIELD = "minFreePercent";
2362
+ var MAX_USED_FIELD = "maxUsedGb";
2363
+ /** Config keys the framework owns; a provider never declares them. */
2364
+ var FRAMEWORK_NUMBER_KEYS = [MIN_FREE_FIELD, MAX_USED_FIELD];
2365
+ /** The legacy mirror of the mode; it is derived and never part of a form. */
2366
+ var LEGACY_READ_ONLY = "readOnly";
2367
+ var LOCATION_ID_SLUG = /^[a-z0-9-]+$/;
2368
+ function isRecord(value) {
2369
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2370
+ }
2371
+ function isConfigField(value) {
2372
+ return isRecord(value) && typeof value["key"] === "string" && typeof value["label"] === "string" && typeof value["type"] === "string";
2373
+ }
2374
+ function isConfigSection(value) {
2375
+ return isRecord(value) && typeof value["id"] === "string" && typeof value["title"] === "string" && Array.isArray(value["fields"]) && value["fields"].every(isConfigField);
2376
+ }
2377
+ /** The sections a provider's `configSchema` carries; anything else is no form. */
2378
+ function providerSections(schema) {
2379
+ if (!isRecord(schema)) return [];
2380
+ const sections = schema["sections"];
2381
+ return Array.isArray(sections) ? sections.filter(isConfigSection) : [];
2382
+ }
2383
+ function isStorageMode(value) {
2384
+ return STORAGE_LOCATION_MODES.some((mode) => mode === value);
2385
+ }
2386
+ function namespaced(providerId, key) {
2387
+ return `${providerId}.${key}`;
2388
+ }
2389
+ function conditionOf(field) {
2390
+ return "showWhen" in field ? field.showWhen : void 0;
2391
+ }
2392
+ /** The field under a new key and a new condition (a field type without one ignores it). */
2393
+ function placed(field, key, showWhen) {
2394
+ return Object.assign({}, field, {
2395
+ key,
2396
+ showWhen
2397
+ });
2398
+ }
2399
+ /** A provider's field as the create form shows it: its own key space, shown for that provider. */
2400
+ function namespacedField(providerId, field, siblings) {
2401
+ const key = namespaced(providerId, field.key);
2402
+ if (field.type === "object-array") return {
2403
+ ...field,
2404
+ key
2405
+ };
2406
+ const own = conditionOf(field);
2407
+ if (own === void 0) return placed(field, key, {
2408
+ field: PROVIDER_FIELD,
2409
+ equals: providerId
2410
+ });
2411
+ const sibling = siblings.find((f) => f.key === own.field);
2412
+ let showWhen = {
2413
+ ...own,
2414
+ field: namespaced(providerId, own.field)
2415
+ };
2416
+ if (sibling?.type === "select") {
2417
+ const values = sibling.options.map((option) => option.value);
2418
+ if (own.notEquals !== void 0) {
2419
+ const excluded = own.notEquals;
2420
+ const { notEquals: _dropped, ...rest } = showWhen;
2421
+ showWhen = {
2422
+ ...rest,
2423
+ in: values.filter((value) => value !== excluded)
2424
+ };
2425
+ } else if (own.notIn !== void 0) {
2426
+ const excluded = own.notIn;
2427
+ const { notIn: _dropped, ...rest } = showWhen;
2428
+ showWhen = {
2429
+ ...rest,
2430
+ in: values.filter((value) => !excluded.includes(value))
2431
+ };
2432
+ }
2433
+ }
2434
+ return placed(field, key, showWhen);
2435
+ }
2436
+ function createProviderSections(providers) {
2437
+ return providers.flatMap((provider) => providerSections(provider.configSchema).map((section) => {
2438
+ const all = providerSections(provider.configSchema).flatMap((s) => s.fields);
2439
+ return {
2440
+ ...section,
2441
+ id: `${provider.providerId}:${section.id}`,
2442
+ fields: section.fields.map((field) => namespacedField(provider.providerId, field, all))
2443
+ };
2444
+ }));
2445
+ }
2446
+ /**
2447
+ * Where the location lives. On an existing location its state (`mode`) is not a form field: the
2448
+ * admin page changes it through its own control, which knows the last-writable guard and confirms
2449
+ * `disabled`. A new location asks only whether it takes writes or is only read (`withState`).
2450
+ */
2451
+ function stateSection(nodeLocalIds, withState = false) {
2452
+ const fields = [];
2453
+ if (withState) fields.push({
2454
+ type: "select",
2455
+ key: MODE_FIELD,
2456
+ label: "State",
2457
+ default: "active",
2458
+ options: [{
2459
+ value: "active",
2460
+ label: "Active"
2461
+ }, {
2462
+ value: "readonly",
2463
+ label: "Read-only"
2464
+ }]
2465
+ });
2466
+ if (nodeLocalIds === null || nodeLocalIds.length > 0) fields.push({
2467
+ type: "text",
2468
+ key: NODE_FIELD,
2469
+ label: "Node",
2470
+ description: "The node whose disk this location is. Empty means the hub.",
2471
+ ...nodeLocalIds === null ? {} : { showWhen: {
2472
+ field: PROVIDER_FIELD,
2473
+ in: [...nodeLocalIds]
2474
+ } }
2475
+ });
2476
+ return {
2477
+ id: "state",
2478
+ title: withState ? "Placement" : "Node",
2479
+ columns: 1,
2480
+ fields
2481
+ };
2482
+ }
2483
+ function protectionSection() {
2484
+ return {
2485
+ id: "protection",
2486
+ title: "Disk protection",
2487
+ columns: 2,
2488
+ fields: [{
2489
+ type: "number",
2490
+ key: MIN_FREE_FIELD,
2491
+ label: "Keep free (%)",
2492
+ min: 0,
2493
+ max: 100
2494
+ }, {
2495
+ type: "number",
2496
+ key: MAX_USED_FIELD,
2497
+ label: "Use at most (GB)",
2498
+ min: 0
2499
+ }]
2500
+ };
2501
+ }
2502
+ function stateOf(location) {
2503
+ return resolveLocationMode(location);
2504
+ }
2505
+ /** A form value that names a credential KEPT: left out, empty, the redaction token or the view. */
2506
+ function keepsSecret(value) {
2507
+ return value === void 0 || value === "" || value === "__camstack_redacted__" || isSecretFieldView(value) || isSecretMarker(value);
2508
+ }
2509
+ function numberOrNull(value) {
2510
+ if (value === void 0) return void 0;
2511
+ if (value === null || value === "") return null;
2512
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2513
+ }
2514
+ var StorageLocationInstances = class {
2515
+ deps;
2516
+ constructor(deps) {
2517
+ this.deps = deps;
2518
+ }
2519
+ kinds() {
2520
+ return this.deps.declarations().map((declaration) => ({
2521
+ id: declaration.id,
2522
+ label: declaration.displayName,
2523
+ functionCap: STORAGE_FUNCTION_CAP,
2524
+ role: "services",
2525
+ canTest: true,
2526
+ widgets: [{
2527
+ id: STORAGE_PATH_WIDGET,
2528
+ placement: "connection"
2529
+ }]
2530
+ }));
2531
+ }
2532
+ viewOf(location) {
2533
+ const mode = stateOf(location);
2534
+ const secretKeys = this.deps.secretKeys(location.providerId, location.config);
2535
+ const formValues = {
2536
+ [PROVIDER_FIELD]: location.providerId,
2537
+ [MODE_FIELD]: mode
2538
+ };
2539
+ if (location.nodeId !== void 0) formValues[NODE_FIELD] = location.nodeId;
2540
+ for (const [key, value] of Object.entries(location.config)) {
2541
+ if (key === LEGACY_READ_ONLY) continue;
2542
+ if (secretKeys.has(key)) {
2543
+ const view = toSecretFieldView(value);
2544
+ if (view !== null) formValues[key] = view;
2545
+ } else formValues[key] = value;
2546
+ }
2547
+ return {
2548
+ id: location.id,
2549
+ name: location.displayName,
2550
+ configured: true,
2551
+ enabled: switchStateOfMode(mode),
2552
+ kind: location.type,
2553
+ formValues,
2554
+ status: {
2555
+ state: switchStateOfMode(mode) ? "ok" : "off",
2556
+ label: mode
2557
+ }
2558
+ };
2559
+ }
2560
+ describe = async () => ({
2561
+ role: "services",
2562
+ instanceMode: "multiple",
2563
+ kind: STORAGE_INSTANCE_KIND,
2564
+ canTest: true,
2565
+ mintsId: true,
2566
+ kinds: [...this.kinds()]
2567
+ });
2568
+ instanceFormSchema = async ({ id }) => {
2569
+ const providers = await this.deps.providers();
2570
+ if (id === null) {
2571
+ const nodeLocal = providers.filter((p) => p.nodeLocal).map((p) => p.providerId);
2572
+ return { sections: [
2573
+ {
2574
+ id: "provider",
2575
+ title: "Provider",
2576
+ columns: 1,
2577
+ fields: [{
2578
+ type: "select",
2579
+ key: PROVIDER_FIELD,
2580
+ label: "Provider",
2581
+ required: true,
2582
+ options: providers.map((p) => ({
2583
+ value: p.providerId,
2584
+ label: p.displayName
2585
+ }))
2586
+ }]
2587
+ },
2588
+ ...createProviderSections(providers),
2589
+ stateSection(nodeLocal, true),
2590
+ protectionSection()
2591
+ ] };
2592
+ }
2593
+ const location = this.deps.locations().find((l) => l.id === id);
2594
+ if (location === void 0) throw new Error(`storage location '${id}' not found`);
2595
+ const provider = providers.find((p) => p.providerId === location.providerId);
2596
+ return { sections: [
2597
+ stateSection(provider?.nodeLocal === true ? [location.providerId] : []),
2598
+ ...provider === void 0 ? [] : providerSections(provider.configSchema),
2599
+ protectionSection()
2600
+ ] };
2601
+ };
2602
+ listInstances = async () => this.deps.locations().map((location) => this.viewOf(location));
2603
+ getInstance = async ({ id }) => {
2604
+ const location = this.deps.locations().find((l) => l.id === id);
2605
+ return location === void 0 ? null : this.viewOf(location);
2606
+ };
2607
+ /**
2608
+ * The config and credentials a form `values` object means for a provider: its own namespaced
2609
+ * keys (create form) or plain keys (edit form), the framework numbers, nothing of another
2610
+ * provider. `base` is the stored config; a credential kept stays as stored.
2611
+ */
2612
+ configFrom(providerId, values, base) {
2613
+ const config = { ...base };
2614
+ const clear = [];
2615
+ const prefix = `${providerId}.`;
2616
+ const secretKeys = this.deps.secretKeys(providerId, base);
2617
+ const named = [];
2618
+ for (const [raw, value] of Object.entries(values)) {
2619
+ if (raw === PROVIDER_FIELD || raw === MODE_FIELD || raw === NODE_FIELD) continue;
2620
+ if (raw.startsWith(prefix)) named.push([raw.slice(prefix.length), value]);
2621
+ else if (!raw.includes(".")) named.push([raw, value]);
2622
+ }
2623
+ for (const [key, value] of named) {
2624
+ if (value === void 0) continue;
2625
+ if (FRAMEWORK_NUMBER_KEYS.includes(key)) {
2626
+ const number = numberOrNull(value);
2627
+ if (number === null) delete config[key];
2628
+ else if (number !== void 0) config[key] = number;
2629
+ continue;
2630
+ }
2631
+ if (secretKeys.has(key)) {
2632
+ if (isSecretClear(value)) clear.push(key);
2633
+ else if (keepsSecret(value)) continue;
2634
+ else if (typeof value === "string") config[key] = value;
2635
+ continue;
2636
+ }
2637
+ if (value === null || value === "") delete config[key];
2638
+ else config[key] = value;
2639
+ }
2640
+ return {
2641
+ config,
2642
+ clear
2643
+ };
2644
+ }
2645
+ async mintId(kind, name) {
2646
+ const taken = new Set(this.deps.locations().map((l) => l.id));
2647
+ const slug = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
2648
+ const base = `${kind}:${slug.length > 0 ? slug : "default"}`;
2649
+ if (!taken.has(base)) return base;
2650
+ for (let n = 2;; n += 1) {
2651
+ const candidate = `${base}-${n}`;
2652
+ if (!taken.has(candidate)) return candidate;
2653
+ }
2654
+ }
2655
+ createInstance = async ({ id, name, kind, values }) => {
2656
+ const form = values ?? {};
2657
+ const declared = this.deps.declarations();
2658
+ const type = kind ?? (declared.length === 1 ? declared[0]?.id : void 0);
2659
+ if (type === void 0) throw new Error("pick the kind of location first");
2660
+ if (!declared.some((d) => d.id === type)) throw new Error(`unknown location kind '${type}'`);
2661
+ const providerId = form[PROVIDER_FIELD];
2662
+ if (typeof providerId !== "string" || providerId === "") throw new Error("pick a provider");
2663
+ const minted = id ?? await this.mintId(type, name);
2664
+ const slug = minted.slice(type.length + 1);
2665
+ if (!minted.startsWith(`${type}:`) || !LOCATION_ID_SLUG.test(slug)) throw new Error(`id must be '${type}:<slug>' (lowercase letters, digits and hyphens)`);
2666
+ if (this.deps.locations().some((l) => l.id === minted)) throw new Error(`storage location '${minted}' already exists`);
2667
+ const { config, clear } = this.configFrom(providerId, form, {});
2668
+ const mode = form[MODE_FIELD];
2669
+ const node = form[NODE_FIELD];
2670
+ await this.deps.save({
2671
+ id: minted,
2672
+ type,
2673
+ displayName: name,
2674
+ providerId,
2675
+ config,
2676
+ isSystem: false,
2677
+ ...typeof node === "string" && node !== "" ? { nodeId: node } : {},
2678
+ ...isStorageMode(mode) ? { mode } : {}
2679
+ }, clear);
2680
+ return { id: minted };
2681
+ };
2682
+ /** The whole location again, from the stored row, with `patch` on top (the save REPLACES). */
2683
+ rebuilt(stored, patch) {
2684
+ const nodeId = patch.nodeId ?? stored.nodeId;
2685
+ return {
2686
+ id: stored.id,
2687
+ type: stored.type,
2688
+ displayName: patch.displayName ?? stored.displayName,
2689
+ providerId: stored.providerId,
2690
+ config: patch.config ?? stored.config,
2691
+ isSystem: stored.isSystem,
2692
+ ...nodeId !== void 0 ? { nodeId } : {},
2693
+ ...patch.mode !== void 0 ? { mode: patch.mode } : {}
2694
+ };
2695
+ }
2696
+ updateInstance = async ({ id, name, values }) => {
2697
+ const stored = this.deps.locations().find((l) => l.id === id);
2698
+ if (stored === void 0) throw new Error(`storage location '${id}' not found`);
2699
+ const { config, clear } = this.configFrom(stored.providerId, values, stored.config);
2700
+ const mode = values[MODE_FIELD];
2701
+ const node = values[NODE_FIELD];
2702
+ await this.deps.save(this.rebuilt(stored, {
2703
+ ...name !== void 0 ? { displayName: name } : {},
2704
+ config,
2705
+ ...isStorageMode(mode) ? { mode } : {},
2706
+ ...typeof node === "string" && node !== "" ? { nodeId: node } : {}
2707
+ }), clear);
2708
+ return { ok: true };
2709
+ };
2710
+ setInstanceEnabled = async ({ id, enabled }) => {
2711
+ const stored = this.deps.locations().find((l) => l.id === id);
2712
+ if (stored === void 0) throw new Error(`storage location '${id}' not found`);
2713
+ const move = modeForSwitch(enabled, stateOf(stored));
2714
+ if (move.kind === "refuse") throw new Error(`storage location '${id}': ${move.reason}`);
2715
+ if (move.kind === "set") await this.deps.save(this.rebuilt(stored, { mode: move.mode }), []);
2716
+ return { ok: true };
2717
+ };
2718
+ /** The occupancy refusal stays; the forced delete is the separate action. */
2719
+ deleteInstance = async ({ id }) => {
2720
+ await this.deps.remove(id);
2721
+ return { ok: true };
2722
+ };
2723
+ testInstance = async ({ id, values }) => {
2724
+ const stored = id === null ? void 0 : this.deps.locations().find((l) => l.id === id);
2725
+ if (id !== null && stored === void 0) return {
2726
+ success: false,
2727
+ status: "inconclusive",
2728
+ error: `storage location '${id}' not found`
2729
+ };
2730
+ const formProvider = values[PROVIDER_FIELD];
2731
+ const providerId = stored?.providerId ?? (typeof formProvider === "string" ? formProvider : "");
2732
+ if (providerId === "") return {
2733
+ success: false,
2734
+ status: "inconclusive",
2735
+ error: "Pick a provider first"
2736
+ };
2737
+ const { config } = this.configFrom(providerId, values, stored?.config ?? {});
2738
+ const started = Date.now();
2739
+ const limit = this.deps.testTimeoutMs ?? 2e4;
2740
+ let timer;
2741
+ const timedOut = new Promise((resolve) => {
2742
+ timer = setTimeout(() => resolve({
2743
+ success: false,
2744
+ status: "inconclusive",
2745
+ error: `The provider did not answer within ${Math.round(limit / 1e3)} s`
2746
+ }), limit);
2747
+ });
2748
+ const probe = this.deps.probe(providerId, config).then((result) => result.ok ? {
2749
+ success: true,
2750
+ status: "validated",
2751
+ latencyMs: Date.now() - started
2752
+ } : {
2753
+ success: false,
2754
+ status: "rejected",
2755
+ error: result.error ?? "The provider refused this configuration"
2756
+ }).catch((err) => ({
2757
+ success: false,
2758
+ status: "inconclusive",
2759
+ error: err instanceof Error ? err.message : String(err)
2760
+ }));
2761
+ try {
2762
+ return await Promise.race([probe, timedOut]);
2763
+ } finally {
2764
+ if (timer !== void 0) clearTimeout(timer);
2765
+ }
2766
+ };
2767
+ toProvider() {
2768
+ return {
2769
+ describe: this.describe,
2770
+ instanceFormSchema: this.instanceFormSchema,
2771
+ listInstances: this.listInstances,
2772
+ getInstance: this.getInstance,
2773
+ createInstance: this.createInstance,
2774
+ updateInstance: this.updateInstance,
2775
+ setInstanceEnabled: this.setInstanceEnabled,
2776
+ deleteInstance: this.deleteInstance,
2777
+ testInstance: this.testInstance
2778
+ };
2779
+ }
2780
+ };
2781
+ //#endregion
2056
2782
  //#region src/builtins/storage-orchestrator/provider-discovery.ts
2057
2783
  async function collectProviderInfos(providers, onError) {
2058
2784
  const out = [];
@@ -3184,6 +3910,30 @@ var StorageOrchestratorService = class {
3184
3910
  } : { added };
3185
3911
  }
3186
3912
  /**
3913
+ * Re-read the `config` of every location the store holds and replace the in-memory one where it
3914
+ * differs. The credential migration moves a location's secrets into its record, which changes
3915
+ * the markers its config carries; the in-memory copy would otherwise keep pointing at keychain
3916
+ * values the migration released. Only `config` is taken: the rest of a location is what this
3917
+ * process already decided. Returns the ids refreshed.
3918
+ */
3919
+ async refreshConfigsFromStore() {
3920
+ const store = this.locationStore;
3921
+ if (store === null) return [];
3922
+ const rows = await store.loadAll();
3923
+ const refreshed = [];
3924
+ for (const row of rows) {
3925
+ const live = this.locations.get(row.id);
3926
+ if (live === void 0) continue;
3927
+ if (JSON.stringify(live.config) === JSON.stringify(row.config)) continue;
3928
+ this.locations.set(row.id, {
3929
+ ...live,
3930
+ config: row.config
3931
+ });
3932
+ refreshed.push(row.id);
3933
+ }
3934
+ return refreshed;
3935
+ }
3936
+ /**
3187
3937
  * Re-create the default of a type whose seed marker survived the loss of every
3188
3938
  * row (the 2026-11-01 prune: it deleted the rows and, until D1006, left the
3189
3939
  * marker). That state cannot be an operator action — the service refuses to
@@ -3880,6 +4630,8 @@ var STORAGE_OCCUPANCY_CAP_NAME = "storage-occupancy";
3880
4630
  * before `nodeId` existed.
3881
4631
  */
3882
4632
  var HUB_NODE_ID = "hub";
4633
+ /** How long a save waits for its credential to reach the record before it answers anyway. */
4634
+ var SECRET_PERSIST_WAIT_MS = 5e3;
3883
4635
  /** How often the pressure manager re-evaluates free space per location. */
3884
4636
  var PRESSURE_SWEEP_INTERVAL_MS = 6e4;
3885
4637
  /**
@@ -3942,6 +4694,8 @@ var StorageOrchestratorAddon = class extends BaseAddon {
3942
4694
  * is readable through a provider the orchestrator can otherwise use.
3943
4695
  */
3944
4696
  secretKeysByProvider = /* @__PURE__ */ new Map();
4697
+ /** Credentials of a save on their way to the location's record (`LocationSecretStaging`). */
4698
+ secretStaging = new LocationSecretStaging();
3945
4699
  /**
3946
4700
  * Disposers run on `onShutdown` — currently the eventBus subscription
3947
4701
  * for `capability:provider-registered` events used by the lazy seed
@@ -3993,67 +4747,6 @@ var StorageOrchestratorAddon = class extends BaseAddon {
3993
4747
  },
3994
4748
  listLocationDeclarations: async () => service.listDeclarations(),
3995
4749
  listDrainProgress: async () => this.drainProgress(),
3996
- upsertLocation: async (input) => {
3997
- const stored = service.getLocationById(input.id);
3998
- const config = restoreRedactedSecrets(input.config, stored?.config, this.secretKeysFor(input.providerId, stored?.config ?? {}));
3999
- const keychained = await this.keepSecretsInKeychain(input.id, input.providerId, config, stored?.config ?? {});
4000
- const next = keychained === input.config ? input : {
4001
- ...input,
4002
- config: keychained
4003
- };
4004
- const saved = await this.upsertCarryingData(stored, next, () => service.upsertLocation(next));
4005
- this.announceLocationsChanged(saved.id, saved.type, "upsert");
4006
- return this.redacted(saved);
4007
- },
4008
- deleteLocation: async ({ id, force }) => {
4009
- const doomed = service.getLocationById(id);
4010
- await service.deleteLocation(id, { force: force === true });
4011
- this.announceLocationsChanged(id, doomed?.type ?? "", "delete");
4012
- },
4013
- testLocation: async ({ id }) => {
4014
- const loc = service.getLocationById(id);
4015
- if (!loc) return {
4016
- ok: false,
4017
- error: `Location "${id}" not found`
4018
- };
4019
- try {
4020
- const p = await service.getProviderFor(loc);
4021
- const live = await this.withResolvedSecrets(loc);
4022
- return p.testLocation({ config: live.config });
4023
- } catch (err) {
4024
- return {
4025
- ok: false,
4026
- error: err instanceof Error ? err.message : String(err)
4027
- };
4028
- }
4029
- },
4030
- listProviders: async () => {
4031
- return collectProviderInfos(getProviders(), (_provider, err, index) => {
4032
- this.ctx.logger.warn("storage-orchestrator: getProviderInfo failed", { meta: {
4033
- providerIndex: index,
4034
- error: err instanceof Error ? err.message : String(err)
4035
- } });
4036
- });
4037
- },
4038
- testConfig: async ({ providerId, locationId, config }) => {
4039
- const stored = locationId === void 0 ? void 0 : service.getLocationById(locationId);
4040
- const base = stored?.providerId === providerId ? stored.config : void 0;
4041
- const resolved = restoreRedactedSecrets(config, base, this.secretKeysFor(providerId, base ?? {}));
4042
- const providers = getProviders();
4043
- for (const p of providers) try {
4044
- if ((await p.getProviderInfo()).providerId !== providerId) continue;
4045
- return p.testLocation({ config: resolved });
4046
- } catch (err) {
4047
- return {
4048
- ok: false,
4049
- error: err instanceof Error ? err.message : String(err)
4050
- };
4051
- }
4052
- return {
4053
- ok: false,
4054
- error: `No storage-provider registered for providerId "${providerId}"`
4055
- };
4056
- },
4057
4750
  resolve: async ({ location, relativePath }) => {
4058
4751
  const loc = await this.withResolvedSecrets(service.resolveRef(location));
4059
4752
  this.refuseRemoteResolve(loc);
@@ -4345,20 +5038,65 @@ var StorageOrchestratorAddon = class extends BaseAddon {
4345
5038
  this.recordLocationHistory();
4346
5039
  }, PRESSURE_SWEEP_INTERVAL_MS);
4347
5040
  this.ctx.logger.info("Storage orchestrator initialized");
4348
- return [
4349
- {
4350
- capability: storageCapability,
4351
- provider
4352
- },
4353
- {
4354
- capability: storageMigrationCapability,
4355
- provider: migrationProvider
5041
+ const instances = this.locationsKind === null ? null : new StorageLocationInstances({
5042
+ locations: () => service.listLocations(),
5043
+ declarations: () => service.listDeclarations(),
5044
+ providers: () => collectProviderInfos(getProviders(), (_provider, err, index) => {
5045
+ this.ctx.logger.warn("storage-orchestrator: getProviderInfo failed", { meta: {
5046
+ providerIndex: index,
5047
+ error: err instanceof Error ? err.message : String(err)
5048
+ } });
5049
+ }),
5050
+ save: async (input, clear) => this.redacted(await this.saveLocation(input, clear)),
5051
+ remove: (id) => this.removeLocation(id, false),
5052
+ probe: async (providerId, config) => {
5053
+ const live = await this.resolvedConfig(`probe:${providerId}`, config);
5054
+ const match = (await Promise.all(getProviders().map(async (p) => ({
5055
+ p,
5056
+ info: await p.getProviderInfo()
5057
+ })))).find((entry) => entry.info.providerId === providerId);
5058
+ if (match === void 0) return {
5059
+ ok: false,
5060
+ error: `No storage-provider registered for providerId "${providerId}"`
5061
+ };
5062
+ return match.p.testLocation({ config: live });
4356
5063
  },
4357
- {
4358
- capability: settingsStoreCapability,
4359
- provider: createDataStoreDispatch(getEngines, () => this.hubSettingsForward())
4360
- }
4361
- ];
5064
+ secretKeys: (providerId, config) => this.secretKeysFor(providerId, config)
5065
+ });
5066
+ return {
5067
+ providers: [
5068
+ {
5069
+ capability: storageCapability,
5070
+ provider
5071
+ },
5072
+ {
5073
+ capability: storageMigrationCapability,
5074
+ provider: migrationProvider
5075
+ },
5076
+ {
5077
+ capability: settingsStoreCapability,
5078
+ provider: createDataStoreDispatch(getEngines, () => this.hubSettingsForward())
5079
+ },
5080
+ ...instances === null ? [] : [{
5081
+ capability: integrationInstancesCapability,
5082
+ provider: instances.toProvider()
5083
+ }]
5084
+ ],
5085
+ customActions: storageOrchestratorActions,
5086
+ actionHandlers: { forceDeleteLocation: async (input) => {
5087
+ const { id } = forceDeleteLocationInput.parse(input);
5088
+ await this.removeLocation(id, true);
5089
+ return { ok: true };
5090
+ } }
5091
+ };
5092
+ }
5093
+ /** Delete a location; the occupancy refusal stands unless `force` was stated. */
5094
+ async removeLocation(id, force) {
5095
+ const service = this.service;
5096
+ if (service === null) throw new Error("storage-orchestrator is not initialised");
5097
+ const doomed = service.getLocationById(id);
5098
+ await service.deleteLocation(id, { force });
5099
+ this.announceLocationsChanged(id, doomed?.type ?? "", "delete");
4362
5100
  }
4363
5101
  /**
4364
5102
  * The remote behind the data door on a node that owns no engine.
@@ -4430,7 +5168,7 @@ var StorageOrchestratorAddon = class extends BaseAddon {
4430
5168
  return null;
4431
5169
  }
4432
5170
  if (this.locationsKind === null || this.seedMarkersKind === null) return null;
4433
- return new SqliteLocationStore(this.locationsKind, this.seedMarkersKind);
5171
+ return new SqliteLocationStore(this.locationsKind, this.seedMarkersKind, this.secretStaging);
4434
5172
  }
4435
5173
  /**
4436
5174
  * Late-wire the persistence store once a `data-store-provider` engine
@@ -4740,55 +5478,99 @@ var StorageOrchestratorAddon = class extends BaseAddon {
4740
5478
  * ref; the provider then fails its own connection, by name.
4741
5479
  */
4742
5480
  async withResolvedSecrets(location) {
5481
+ const config = await this.resolvedConfig(location.id, location.config);
5482
+ return config === location.config ? location : {
5483
+ ...location,
5484
+ config
5485
+ };
5486
+ }
5487
+ /** `config` with every keychain marker resolved; the same object when it holds none. */
5488
+ async resolvedConfig(locationId, config) {
4743
5489
  const secrets = this.ctx.secrets;
4744
- if (secrets === void 0) return location;
4745
- const { value, unresolved } = await resolveSecretMarkers(location.config, secrets);
5490
+ if (secrets === void 0) return config;
5491
+ const { value, unresolved } = await resolveSecretMarkers(config, secrets);
4746
5492
  if (unresolved.length > 0) this.ctx.logger.error("storage location secret unavailable", { meta: {
4747
- locationId: location.id,
5493
+ locationId,
4748
5494
  secrets: unresolved.map((u) => ({
4749
5495
  ref: u.ref,
4750
5496
  reason: u.reason
4751
5497
  }))
4752
5498
  } });
4753
- return value === location.config ? location : {
4754
- ...location,
4755
- config: value
5499
+ return value;
5500
+ }
5501
+ /**
5502
+ * Save one location the way every door does (the legacy `upsertLocation` and the instance
5503
+ * provider): the sentinel travelling back in means "keep the stored secret", the provider's
5504
+ * declared credentials are staged for the location's own record (D787, never the row's
5505
+ * `config`), a SINGLETON that changes root carries its bytes, and the change is announced.
5506
+ * Returns the saved location with its markers; the callers redact it.
5507
+ */
5508
+ async saveLocation(input, clearSecrets = []) {
5509
+ const service = this.service;
5510
+ if (service === null) throw new Error("storage-orchestrator is not initialised");
5511
+ const stored = service.getLocationById(input.id);
5512
+ const restored = restoreRedactedSecrets(input.config, stored?.config, this.secretKeysFor(input.providerId, stored?.config ?? {}));
5513
+ const prepared = this.prepareLocationSecrets(input.id, input.providerId, restored, stored?.config ?? {}, clearSecrets);
5514
+ const next = prepared.config === input.config ? input : {
5515
+ ...input,
5516
+ config: prepared.config
4756
5517
  };
5518
+ this.secretStaging.stage(input.id, prepared.staged);
5519
+ try {
5520
+ const saved = await this.upsertCarryingData(stored, next, () => service.upsertLocation(next));
5521
+ await this.persistedWithin(input.id);
5522
+ this.announceLocationsChanged(saved.id, saved.type, "upsert");
5523
+ return saved;
5524
+ } catch (err) {
5525
+ this.secretStaging.discard(input.id);
5526
+ throw err;
5527
+ }
5528
+ }
5529
+ /** The record write of a save that staged a credential is awaited, bounded: a hung store must not hang the save. */
5530
+ async persistedWithin(id) {
5531
+ let timer;
5532
+ const bound = new Promise((resolve) => {
5533
+ timer = setTimeout(resolve, SECRET_PERSIST_WAIT_MS);
5534
+ });
5535
+ try {
5536
+ await Promise.race([this.secretStaging.settled(id), bound]);
5537
+ } finally {
5538
+ if (timer !== void 0) clearTimeout(timer);
5539
+ }
4757
5540
  }
4758
5541
  /**
4759
- * Strip the provider's DECLARED secrets (its form schema, by type) out of a
4760
- * location config into the keychain, under `row/storage_locations/<id>`.
4761
- * A provider that has not registered declares nothing: only keys that
4762
- * already hold a marker are handled then — a new plaintext is never guessed
4763
- * at, it stays as sent until the provider is back and the location is saved.
5542
+ * Split the credentials of an incoming config from the rest (D787). A declared secret key with a
5543
+ * new value is STAGED (the records door stores it with the row) and the location carries the
5544
+ * marker of its own record; a key that is absent, empty or already a marker keeps what is stored;
5545
+ * `clear` removes it. A provider that has not registered declares nothing: a new plaintext is
5546
+ * never guessed at, it stays as sent until the provider is back and the location is saved.
4764
5547
  */
4765
- async keepSecretsInKeychain(locationId, providerId, config, stored) {
4766
- const secrets = this.ctx.secrets;
4767
- if (secrets === void 0) return config;
5548
+ prepareLocationSecrets(locationId, providerId, config, stored, clear) {
5549
+ if (this.ctx.secrets === void 0) return {
5550
+ config,
5551
+ staged: {}
5552
+ };
4768
5553
  const declared = this.declaredSecretKeys(providerId) ?? /* @__PURE__ */ new Set();
4769
- const markerKeys = Object.entries(stored).filter(([, v]) => isSecretMarker(v)).map(([k]) => k);
4770
- const tree = secretTreeFromPaths([...new Set([...declared, ...markerKeys])]);
4771
- if (tree.size === 0) return config;
4772
- const result = await transformSecretWrite({
4773
- tree,
4774
- secrets,
4775
- patch: { ...config },
4776
- stored: { ...stored },
4777
- scope: {
4778
- kind: "row",
4779
- collection: STORAGE_LOCATIONS_SECRET_SCOPE,
4780
- rowId: locationId
5554
+ const out = { ...config };
5555
+ const staged = {};
5556
+ for (const key of new Set([...declared, ...clear])) {
5557
+ if (clear.includes(key)) {
5558
+ delete out[key];
5559
+ staged[key] = null;
5560
+ continue;
4781
5561
  }
4782
- });
4783
- const merged = { ...result.patch };
4784
- for (const key of tree.keys()) if (!(key in merged) && key in stored) merged[key] = stored[key];
4785
- result.afterWrite().then(({ orphaned }) => {
4786
- if (orphaned.length > 0) this.ctx.logger.warn("storage location: dropped keychain refs could not be deleted", { meta: {
4787
- locationId,
4788
- refs: [...orphaned]
4789
- } });
4790
- });
4791
- return merged;
5562
+ const value = out[key];
5563
+ if (typeof value === "string" && value.length > 0) {
5564
+ staged[key] = value;
5565
+ out[key] = locationSecretMarker(locationId, key);
5566
+ } else if (value === void 0 || value === "") if (isSecretMarker(stored[key])) out[key] = stored[key];
5567
+ else delete out[key];
5568
+ }
5569
+ for (const [key, value] of Object.entries(stored)) if (isSecretMarker(value) && !(key in out) && !clear.includes(key)) out[key] = value;
5570
+ return {
5571
+ config: Object.keys(staged).length > 0 || Object.keys(out).length !== Object.keys(config).length || Object.entries(out).some(([key, value]) => config[key] !== value) ? out : config,
5572
+ staged
5573
+ };
4792
5574
  }
4793
5575
  redacted(location) {
4794
5576
  return redactLocation(location, this.secretKeysFor(location.providerId, location.config));
@@ -5017,6 +5799,7 @@ var StorageOrchestratorAddon = class extends BaseAddon {
5017
5799
  */
5018
5800
  async seedFromDeclarations() {
5019
5801
  if (!this.service) return;
5802
+ await this.moveLocationSecrets();
5020
5803
  await this.refreshNodeLocalCache();
5021
5804
  const declarers = this.ctx.kernel.listStorageLocationDeclarers?.();
5022
5805
  const perAddon = declarers !== void 0 ? declarers.filter((d) => d.loaded).map((d) => d.declarations) : this.ctx.kernel.listStorageLocationDeclarations?.() ?? [];
@@ -5054,7 +5837,7 @@ var StorageOrchestratorAddon = class extends BaseAddon {
5054
5837
  if (!this.seedAnswered || !service.locationsAuthoritative()) return;
5055
5838
  this.reseedRepairRunning = true;
5056
5839
  try {
5057
- await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, { reseed: () => service.reseedPrunedDefaults(seedInput) }));
5840
+ await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, this.cataloguePorts(service, seedInput)), { only: [RESEED_PRUNED_DEFAULTS_ID] });
5058
5841
  this.reseedRepairDone = true;
5059
5842
  } catch (err) {
5060
5843
  this.ctx.logger.warn("storage-orchestrator: the pruned-default repair did not run", { meta: { error: err instanceof Error ? err.message : String(err) } });
@@ -5063,6 +5846,45 @@ var StorageOrchestratorAddon = class extends BaseAddon {
5063
5846
  }
5064
5847
  }
5065
5848
  /**
5849
+ * Every port of the catalogue, bound once. The reseed port only answers inside the seed pass
5850
+ * (it needs the declarations); the credential ports need the hub's records and keychain, so
5851
+ * a node without them runs neither step.
5852
+ */
5853
+ cataloguePorts(service, seedInput) {
5854
+ const locations = this.locationsKind;
5855
+ const secrets = this.ctx.secrets;
5856
+ if (locations === null || secrets === void 0) throw new Error("storage-orchestrator: the credential move needs the records and the keychain");
5857
+ return {
5858
+ reseed: () => seedInput === null ? [] : service.reseedPrunedDefaults(seedInput),
5859
+ ...locationSecretPortsOver({
5860
+ locations,
5861
+ secrets,
5862
+ refreshLocations: () => service.refreshConfigsFromStore()
5863
+ })
5864
+ };
5865
+ }
5866
+ secretsMoveDone = false;
5867
+ secretsMoveRunning = false;
5868
+ /**
5869
+ * D987: move the credentials of every location from the per-row keychain refs into the
5870
+ * location's own record. Runs once the persisted rows are loaded; a refusal (keychain locked,
5871
+ * a value gone) leaves every row as it was and the next seed pass asks again.
5872
+ */
5873
+ async moveLocationSecrets() {
5874
+ const service = this.service;
5875
+ if (!service || this.secretsMoveDone || this.secretsMoveRunning) return;
5876
+ if (!service.hasStore() || this.locationsKind === null || this.ctx.secrets === void 0) return;
5877
+ this.secretsMoveRunning = true;
5878
+ try {
5879
+ await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, this.cataloguePorts(service, null)), { only: [LOCATION_SECRETS_TO_RECORD_ID] });
5880
+ this.secretsMoveDone = true;
5881
+ } catch (err) {
5882
+ this.ctx.logger.error("storage-orchestrator: the location credentials were NOT moved to their records; they stay where they were", { meta: { error: err instanceof Error ? err.message : String(err) } });
5883
+ } finally {
5884
+ this.secretsMoveRunning = false;
5885
+ }
5886
+ }
5887
+ /**
5066
5888
  * Alert when a declared type has nowhere to write. Runs after every seed pass
5067
5889
  * and every change to the set of locations; a no-op until a pass has an
5068
5890
  * answered state AND the kernel could list its declarers (D315).
@@ -5131,4 +5953,4 @@ function parseOrphanStatus(raw) {
5131
5953
  };
5132
5954
  }
5133
5955
  //#endregion
5134
- export { StorageOrchestratorAddon, StorageOrchestratorAddon as default, stripForwardedCaller as a, SqliteLocationStore as c, createHubCapForwardService as i, storageOrchestratorRecordKinds as l, HUB_CAP_FWD_ACTION as n, buildStorageLocationRegistry as o, HUB_CAP_FWD_SERVICE as r, StorageMigrationCoordinator as s, StorageOrchestratorService as t };
5956
+ export { StorageOrchestratorAddon, StorageOrchestratorAddon as default, createHubCapForwardService as a, StorageMigrationCoordinator as c, HUB_CAP_FWD_SERVICE as i, SqliteLocationStore as l, storageOrchestratorActions as n, stripForwardedCaller as o, HUB_CAP_FWD_ACTION as r, buildStorageLocationRegistry as s, StorageOrchestratorService as t, storageOrchestratorRecordKinds as u };