clinkx 1.3.0 → 1.4.1

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 (179) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +13 -6
  3. package/clinkx-workflows/dist/child-env.d.ts +3 -0
  4. package/clinkx-workflows/dist/child-env.js +11 -0
  5. package/clinkx-workflows/dist/child-env.js.map +1 -1
  6. package/clinkx-workflows/dist/dashboard/api-routes.d.ts +21 -0
  7. package/clinkx-workflows/dist/dashboard/api-routes.js +27 -0
  8. package/clinkx-workflows/dist/dashboard/api-routes.js.map +1 -1
  9. package/clinkx-workflows/dist/dashboard/auth/challenge-store.d.ts +13 -0
  10. package/clinkx-workflows/dist/dashboard/auth/challenge-store.js.map +1 -1
  11. package/clinkx-workflows/dist/dashboard/auth/controller.d.ts +27 -0
  12. package/clinkx-workflows/dist/dashboard/auth/controller.js +262 -23
  13. package/clinkx-workflows/dist/dashboard/auth/controller.js.map +1 -1
  14. package/clinkx-workflows/dist/dashboard/auth/settings-step-up.d.ts +62 -0
  15. package/clinkx-workflows/dist/dashboard/auth/settings-step-up.js +70 -0
  16. package/clinkx-workflows/dist/dashboard/auth/settings-step-up.js.map +1 -0
  17. package/clinkx-workflows/dist/dashboard/request-admission.d.ts +6 -0
  18. package/clinkx-workflows/dist/dashboard/request-admission.js +9 -0
  19. package/clinkx-workflows/dist/dashboard/request-admission.js.map +1 -1
  20. package/clinkx-workflows/dist/dashboard/server-factory.js +15 -1
  21. package/clinkx-workflows/dist/dashboard/server-factory.js.map +1 -1
  22. package/clinkx-workflows/dist/dashboard/settings-contract.d.ts +1806 -0
  23. package/clinkx-workflows/dist/dashboard/settings-contract.js +630 -0
  24. package/clinkx-workflows/dist/dashboard/settings-contract.js.map +1 -0
  25. package/clinkx-workflows/dist/dashboard/settings-process-reader.d.ts +48 -0
  26. package/clinkx-workflows/dist/dashboard/settings-process-reader.js +195 -0
  27. package/clinkx-workflows/dist/dashboard/settings-process-reader.js.map +1 -0
  28. package/clinkx-workflows/dist/dashboard/settings-routes.d.ts +87 -0
  29. package/clinkx-workflows/dist/dashboard/settings-routes.js +690 -0
  30. package/clinkx-workflows/dist/dashboard/settings-routes.js.map +1 -0
  31. package/clinkx-workflows/dist/dashboard-ui/assets/index-CX4FrhYN.js +122 -0
  32. package/clinkx-workflows/dist/dashboard-ui/assets/style-C5guUjwN.css +1 -0
  33. package/clinkx-workflows/dist/dashboard-ui/index.html +2 -2
  34. package/clinkx-workflows/dist/durable-file-core.d.ts +76 -0
  35. package/clinkx-workflows/dist/durable-file-core.js +146 -0
  36. package/clinkx-workflows/dist/durable-file-core.js.map +1 -0
  37. package/clinkx-workflows/dist/durable-file.d.ts +8 -64
  38. package/clinkx-workflows/dist/durable-file.js +14 -137
  39. package/clinkx-workflows/dist/durable-file.js.map +1 -1
  40. package/clinkx-workflows/dist/index.js +68 -2
  41. package/clinkx-workflows/dist/index.js.map +1 -1
  42. package/clinkx-workflows/dist/settings/audit.d.ts +101 -0
  43. package/clinkx-workflows/dist/settings/audit.js +318 -0
  44. package/clinkx-workflows/dist/settings/audit.js.map +1 -0
  45. package/clinkx-workflows/dist/settings/bootstrap.d.ts +35 -0
  46. package/clinkx-workflows/dist/settings/bootstrap.js +52 -0
  47. package/clinkx-workflows/dist/settings/bootstrap.js.map +1 -0
  48. package/clinkx-workflows/dist/settings/codec.d.ts +51 -0
  49. package/clinkx-workflows/dist/settings/codec.js +410 -0
  50. package/clinkx-workflows/dist/settings/codec.js.map +1 -0
  51. package/clinkx-workflows/dist/settings/durable-write.d.ts +48 -0
  52. package/clinkx-workflows/dist/settings/durable-write.js +31 -0
  53. package/clinkx-workflows/dist/settings/durable-write.js.map +1 -0
  54. package/clinkx-workflows/dist/settings/index.d.ts +20 -0
  55. package/clinkx-workflows/dist/settings/index.js +23 -0
  56. package/clinkx-workflows/dist/settings/index.js.map +1 -0
  57. package/clinkx-workflows/dist/settings/loader.d.ts +80 -0
  58. package/clinkx-workflows/dist/settings/loader.js +577 -0
  59. package/clinkx-workflows/dist/settings/loader.js.map +1 -0
  60. package/clinkx-workflows/dist/settings/lock.d.ts +108 -0
  61. package/clinkx-workflows/dist/settings/lock.js +344 -0
  62. package/clinkx-workflows/dist/settings/lock.js.map +1 -0
  63. package/clinkx-workflows/dist/settings/paths.d.ts +65 -0
  64. package/clinkx-workflows/dist/settings/paths.js +173 -0
  65. package/clinkx-workflows/dist/settings/paths.js.map +1 -0
  66. package/clinkx-workflows/dist/settings/process-heartbeat.d.ts +47 -0
  67. package/clinkx-workflows/dist/settings/process-heartbeat.js +305 -0
  68. package/clinkx-workflows/dist/settings/process-heartbeat.js.map +1 -0
  69. package/clinkx-workflows/dist/settings/registry.d.ts +178 -0
  70. package/clinkx-workflows/dist/settings/registry.js +1290 -0
  71. package/clinkx-workflows/dist/settings/registry.js.map +1 -0
  72. package/clinkx-workflows/dist/settings/schema.d.ts +404 -0
  73. package/clinkx-workflows/dist/settings/schema.js +415 -0
  74. package/clinkx-workflows/dist/settings/schema.js.map +1 -0
  75. package/clinkx-workflows/dist/settings/store.d.ts +157 -0
  76. package/clinkx-workflows/dist/settings/store.js +842 -0
  77. package/clinkx-workflows/dist/settings/store.js.map +1 -0
  78. package/clinkx-workflows/dist/stdio-entry.d.ts +2 -0
  79. package/clinkx-workflows/dist/stdio-entry.js +52 -0
  80. package/clinkx-workflows/dist/stdio-entry.js.map +1 -0
  81. package/dist/dashboard-cli.d.ts +11 -3
  82. package/dist/dashboard-cli.js +199 -33
  83. package/dist/dashboard-cli.js.map +1 -1
  84. package/dist/dashboard-companion/client.d.ts +14 -0
  85. package/dist/dashboard-companion/client.js +16 -0
  86. package/dist/dashboard-companion/client.js.map +1 -1
  87. package/dist/dashboard-companion/credential-expectation.d.ts +23 -0
  88. package/dist/dashboard-companion/credential-expectation.js +50 -0
  89. package/dist/dashboard-companion/credential-expectation.js.map +1 -0
  90. package/dist/dashboard-companion/host-channel.d.ts +36 -0
  91. package/dist/dashboard-companion/host-channel.js +78 -0
  92. package/dist/dashboard-companion/host-channel.js.map +1 -0
  93. package/dist/dashboard-companion/host-status.d.ts +179 -0
  94. package/dist/dashboard-companion/host-status.js +122 -0
  95. package/dist/dashboard-companion/host-status.js.map +1 -0
  96. package/dist/dashboard-companion/protocol.js +17 -0
  97. package/dist/dashboard-companion/protocol.js.map +1 -1
  98. package/dist/dashboard-companion/standalone-assets.d.ts +8 -0
  99. package/dist/dashboard-companion/standalone-assets.js +7 -1
  100. package/dist/dashboard-companion/standalone-assets.js.map +1 -1
  101. package/dist/dashboard-companion/standalone-entry.js +34 -13
  102. package/dist/dashboard-companion/standalone-entry.js.map +1 -1
  103. package/dist/dashboard-gateway/control-plane/contracts.d.ts +38 -38
  104. package/dist/dashboard-gateway/tunnel-http.js +20 -0
  105. package/dist/dashboard-gateway/tunnel-http.js.map +1 -1
  106. package/dist/desktop-host/child-env.d.ts +23 -0
  107. package/dist/desktop-host/child-env.js +70 -0
  108. package/dist/desktop-host/child-env.js.map +1 -0
  109. package/dist/desktop-host/daemon-entry.d.ts +2 -0
  110. package/dist/desktop-host/daemon-entry.js +50 -0
  111. package/dist/desktop-host/daemon-entry.js.map +1 -0
  112. package/dist/desktop-host/daemon-env.d.ts +12 -0
  113. package/dist/desktop-host/daemon-env.js +35 -0
  114. package/dist/desktop-host/daemon-env.js.map +1 -0
  115. package/dist/desktop-host/daemon-protocol.d.ts +210 -0
  116. package/dist/desktop-host/daemon-protocol.js +56 -0
  117. package/dist/desktop-host/daemon-protocol.js.map +1 -0
  118. package/dist/desktop-host/daemon.d.ts +50 -0
  119. package/dist/desktop-host/daemon.js +441 -0
  120. package/dist/desktop-host/daemon.js.map +1 -0
  121. package/dist/desktop-host/enrollment.d.ts +17 -0
  122. package/dist/desktop-host/enrollment.js +25 -0
  123. package/dist/desktop-host/enrollment.js.map +1 -0
  124. package/dist/desktop-host/import.d.ts +14 -0
  125. package/dist/desktop-host/import.js +95 -0
  126. package/dist/desktop-host/import.js.map +1 -0
  127. package/dist/desktop-host/profile.d.ts +130 -0
  128. package/dist/desktop-host/profile.js +176 -0
  129. package/dist/desktop-host/profile.js.map +1 -0
  130. package/dist/desktop-host/service.d.ts +6 -0
  131. package/dist/desktop-host/service.js +7 -0
  132. package/dist/desktop-host/service.js.map +1 -0
  133. package/dist/desktop-host/supervisor.d.ts +57 -0
  134. package/dist/desktop-host/supervisor.js +256 -0
  135. package/dist/desktop-host/supervisor.js.map +1 -0
  136. package/dist/desktop-host/view-state.d.ts +138 -0
  137. package/dist/desktop-host/view-state.js +27 -0
  138. package/dist/desktop-host/view-state.js.map +1 -0
  139. package/dist/elaris/config.d.ts +10 -0
  140. package/dist/elaris/config.js +27 -1
  141. package/dist/elaris/config.js.map +1 -1
  142. package/dist/elaris/tools.js +4 -1
  143. package/dist/elaris/tools.js.map +1 -1
  144. package/dist/index.d.ts +0 -31
  145. package/dist/index.js +41 -404
  146. package/dist/index.js.map +1 -1
  147. package/dist/lib.d.ts +17 -0
  148. package/dist/lib.js +17 -0
  149. package/dist/lib.js.map +1 -0
  150. package/dist/progress-report/lock.d.ts +17 -59
  151. package/dist/progress-report/lock.js +25 -329
  152. package/dist/progress-report/lock.js.map +1 -1
  153. package/dist/registry.d.ts +7 -0
  154. package/dist/registry.js +21 -7
  155. package/dist/registry.js.map +1 -1
  156. package/dist/server.js +75 -4
  157. package/dist/server.js.map +1 -1
  158. package/dist/settings-cli/clients.d.ts +137 -0
  159. package/dist/settings-cli/clients.js +1124 -0
  160. package/dist/settings-cli/clients.js.map +1 -0
  161. package/dist/settings-cli/commands.d.ts +67 -0
  162. package/dist/settings-cli/commands.js +726 -0
  163. package/dist/settings-cli/commands.js.map +1 -0
  164. package/dist/settings-cli/format.d.ts +34 -0
  165. package/dist/settings-cli/format.js +40 -0
  166. package/dist/settings-cli/format.js.map +1 -0
  167. package/dist/settings-cli/main.d.ts +18 -0
  168. package/dist/settings-cli/main.js +256 -0
  169. package/dist/settings-cli/main.js.map +1 -0
  170. package/dist/stdio-main.d.ts +73 -0
  171. package/dist/stdio-main.js +455 -0
  172. package/dist/stdio-main.js.map +1 -0
  173. package/docs/configuration.md +340 -39
  174. package/docs/security.md +150 -6
  175. package/docs/verification/README.md +28 -2
  176. package/docs/verification/workflow-handoff.md +86 -0
  177. package/package.json +3 -3
  178. package/clinkx-workflows/dist/dashboard-ui/assets/index-DRId2DVA.js +0 -119
  179. package/clinkx-workflows/dist/dashboard-ui/assets/style-CHAw57y5.css +0 -1
@@ -0,0 +1,690 @@
1
+ import { logger } from "../logger.js";
2
+ import { SETTINGS_REGISTRY, getSettingDescriptor, isSecretSettingKey } from "../settings/registry.js";
3
+ import { SettingsStoreError } from "../settings/store.js";
4
+ import { computeSettingsIntentDigest, DashboardStepUpError, } from "./auth/settings-step-up.js";
5
+ import { MAX_SETTINGS_OPS_PER_SAVE, SETTINGS_ERROR_HTTP_STATUS, SettingsErrorSchema, SettingsGetResponseSchema, SettingsProcessesResponseSchema, SettingsSaveRequestSchema, SettingsSaveResponseSchema, SecretsSaveRequestSchema, SecretsSaveResponseSchema, StepUpOptionsRequestSchema, StepUpOptionsResponseSchema, projectSettingDescriptor, } from "./settings-contract.js";
6
+ // ---------------------------------------------------------------------------
7
+ // Route segments
8
+ // ---------------------------------------------------------------------------
9
+ /** `["api","settings"]` — the GET read route. */
10
+ export function isSettingsReadSegments(segments) {
11
+ return segments.length === 2 && segments[0] === "api" && segments[1] === "settings";
12
+ }
13
+ /** `["api","settings","processes"]` — the GET processes route. */
14
+ export function isSettingsProcessesSegments(segments) {
15
+ return segments.length === 3 && segments[0] === "api" && segments[1] === "settings" &&
16
+ segments[2] === "processes";
17
+ }
18
+ /** `["api","settings","save"]` — the settings save POST. */
19
+ export function isSettingsSaveSegments(segments) {
20
+ return segments.length === 3 && segments[0] === "api" && segments[1] === "settings" &&
21
+ segments[2] === "save";
22
+ }
23
+ /** `["api","settings","secrets","save"]` — the secrets save POST. */
24
+ export function isSettingsSecretsSaveSegments(segments) {
25
+ return segments.length === 4 && segments[0] === "api" && segments[1] === "settings" &&
26
+ segments[2] === "secrets" && segments[3] === "save";
27
+ }
28
+ /** `["api","settings","step-up"]` — the step-up options POST. */
29
+ export function isSettingsStepUpSegments(segments) {
30
+ return segments.length === 3 && segments[0] === "api" && segments[1] === "settings" &&
31
+ segments[2] === "step-up";
32
+ }
33
+ /** Exactly the five settings routes — used by `isKnownDashboardApiRoute`. */
34
+ export function isSettingsApiSegments(segments) {
35
+ return isSettingsReadSegments(segments) ||
36
+ isSettingsProcessesSegments(segments) ||
37
+ isSettingsSaveSegments(segments) ||
38
+ isSettingsSecretsSaveSegments(segments) ||
39
+ isSettingsStepUpSegments(segments);
40
+ }
41
+ /** The three settings POSTs — used by `isDashboardWritePathSegments`. */
42
+ export function isSettingsWriteSegments(segments) {
43
+ return isSettingsSaveSegments(segments) ||
44
+ isSettingsSecretsSaveSegments(segments) ||
45
+ isSettingsStepUpSegments(segments);
46
+ }
47
+ // ---------------------------------------------------------------------------
48
+ // Body caps (shared shape with the gateway forwarding tiers in B2-1)
49
+ // ---------------------------------------------------------------------------
50
+ /** Step-up options requests carry an intent projection only. */
51
+ export const MAX_SETTINGS_STEP_UP_BODY_BYTES = 16 * 1024;
52
+ /** Saves may carry a WebAuthn assertion alongside up to 64 ops. */
53
+ export const MAX_SETTINGS_SAVE_BODY_BYTES = 64 * 1024;
54
+ const SETTINGS_ERROR_MESSAGE_MAX_CHARS = 2048;
55
+ const FIELD_ERROR_MESSAGE_MAX_CHARS = 512;
56
+ class SettingsBodyError extends Error {
57
+ status;
58
+ code;
59
+ constructor(status, code) {
60
+ super(code);
61
+ this.name = "SettingsBodyError";
62
+ this.status = status;
63
+ this.code = code;
64
+ }
65
+ }
66
+ function singleDistinctHeader(request, name) {
67
+ const values = request.headersDistinct[name];
68
+ return values?.length === 1 ? values[0] : undefined;
69
+ }
70
+ function capText(text, max) {
71
+ return text.length <= max ? text : `${text.slice(0, max - 15)}…[truncated]`;
72
+ }
73
+ async function readSettingsJsonBody(request, maxBytes) {
74
+ const contentType = singleDistinctHeader(request, "content-type");
75
+ if (contentType == null || contentType.toLowerCase() !== "application/json") {
76
+ throw new SettingsBodyError(400, "invalid_request");
77
+ }
78
+ const values = request.headersDistinct["content-length"];
79
+ if (values != null && values.length !== 1) {
80
+ throw new SettingsBodyError(400, "invalid_request");
81
+ }
82
+ const raw = values?.[0];
83
+ if (raw != null) {
84
+ if (!/^(0|[1-9]\d*)$/.test(raw) || !Number.isSafeInteger(Number(raw))) {
85
+ throw new SettingsBodyError(400, "invalid_request");
86
+ }
87
+ if (Number(raw) > maxBytes) {
88
+ throw new SettingsBodyError(413, "content_too_large_for_dashboard");
89
+ }
90
+ }
91
+ const chunks = [];
92
+ let total = 0;
93
+ for await (const chunk of request) {
94
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
95
+ total += bytes.byteLength;
96
+ if (total > maxBytes) {
97
+ request.resume();
98
+ throw new SettingsBodyError(413, "content_too_large_for_dashboard");
99
+ }
100
+ chunks.push(bytes);
101
+ }
102
+ let text;
103
+ try {
104
+ text = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
105
+ }
106
+ catch {
107
+ throw new SettingsBodyError(400, "invalid_request");
108
+ }
109
+ try {
110
+ return JSON.parse(text);
111
+ }
112
+ catch {
113
+ throw new SettingsBodyError(400, "invalid_request");
114
+ }
115
+ }
116
+ function sendSettingsJson(request, response, status, value) {
117
+ const body = `${JSON.stringify(value)}\n`;
118
+ response.writeHead(status, {
119
+ "Cache-Control": "no-store",
120
+ "Content-Type": "application/json; charset=utf-8",
121
+ "Content-Length": Buffer.byteLength(body),
122
+ });
123
+ response.end(request.method === "HEAD" ? undefined : body);
124
+ }
125
+ function sendSettingsError(request, response, status, code, message, details = {}) {
126
+ const body = SettingsErrorSchema.parse({
127
+ error: code,
128
+ message: capText(message, SETTINGS_ERROR_MESSAGE_MAX_CHARS),
129
+ ...(details.fieldErrors == null || details.fieldErrors.length === 0
130
+ ? {}
131
+ : {
132
+ fieldErrors: details.fieldErrors
133
+ .slice(0, MAX_SETTINGS_OPS_PER_SAVE)
134
+ .map((error) => ({
135
+ key: error.key,
136
+ message: capText(error.message, FIELD_ERROR_MESSAGE_MAX_CHARS),
137
+ })),
138
+ }),
139
+ ...(details.expectedRevision == null ? {} : { expectedRevision: details.expectedRevision }),
140
+ ...(details.revision == null ? {} : { revision: details.revision }),
141
+ });
142
+ sendSettingsJson(request, response, status, body);
143
+ }
144
+ function sendGenericError(request, response, status, code, allow) {
145
+ response.writeHead(status, {
146
+ ...(allow == null ? {} : { Allow: allow }),
147
+ "Cache-Control": "no-store",
148
+ "Content-Type": "application/json; charset=utf-8",
149
+ });
150
+ response.end(`{"error":{"code":"${code}"}}\n`);
151
+ }
152
+ /** Map zod issues onto the contract's bounded field-error list. */
153
+ function fieldErrorsFromIssues(issues) {
154
+ return issues.slice(0, MAX_SETTINGS_OPS_PER_SAVE).map((issue) => ({
155
+ key: issue.path.length === 0
156
+ ? "(request)"
157
+ : issue.path.map((segment) => String(segment)).join("."),
158
+ message: issue.message,
159
+ }));
160
+ }
161
+ /** The class of change, computed server-side from the registry. */
162
+ function opsTouchElevatedClass(ops) {
163
+ return ops.some((op) => {
164
+ // Own-property lookup only (S1): an inherited Object member must never
165
+ // read as a descriptor, so a `constructor`/`__proto__` key is non-elevated
166
+ // only because the wire schema already rejected it upstream.
167
+ const descriptor = getSettingDescriptor(op.key);
168
+ return descriptor != null &&
169
+ (descriptor.class === "policy" || descriptor.class === "secret");
170
+ });
171
+ }
172
+ /** A secret key never contributes a value to the step-up intent projection. */
173
+ function intentOpsFromWire(ops) {
174
+ return ops.map((op) => {
175
+ if (op.value === undefined || isSecretSettingKey(op.key)) {
176
+ return { key: op.key, action: op.action };
177
+ }
178
+ return {
179
+ key: op.key,
180
+ action: op.action,
181
+ value: op.value,
182
+ };
183
+ });
184
+ }
185
+ export function createDashboardSettingsRoutes(options) {
186
+ const { store, processReader, processesDir, passkeyAuth } = options;
187
+ const authMode = options.authMode ??
188
+ (passkeyAuth != null ? "passkey" : "bearer");
189
+ const now = options.now ?? (() => new Date());
190
+ const descriptors = Object.values(SETTINGS_REGISTRY)
191
+ .map((descriptor) => projectSettingDescriptor(descriptor))
192
+ .sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0));
193
+ function requireStepUp(request, response, intent, assertion) {
194
+ // Bearer/none: no session exists to bind a challenge to.
195
+ if (passkeyAuth == null) {
196
+ sendSettingsError(request, response, 403, "step_up_unavailable", "policy- and secret-class settings changes require a passkey step-up, which is unavailable in bearer/none auth mode");
197
+ return Promise.resolve(false);
198
+ }
199
+ const credentials = passkeyAuth.sessionCredentials(request);
200
+ if (credentials == null) {
201
+ sendSettingsError(request, response, 403, "settings_auth_required", "a live passkey session is required for this settings change");
202
+ return Promise.resolve(false);
203
+ }
204
+ if (assertion == null) {
205
+ sendSettingsError(request, response, 403, "step_up_required", "this settings change touches a policy- or secret-class key; request options at /api/settings/step-up and carry the assertion as stepUp on the save");
206
+ return Promise.resolve(false);
207
+ }
208
+ const intentDigest = computeSettingsIntentDigest(intent);
209
+ return passkeyAuth
210
+ .verifyStepUp({
211
+ sessionId: credentials.sessionId,
212
+ originProof: credentials.originProof,
213
+ intentDigest,
214
+ challengeId: assertion.challengeId,
215
+ response: assertion.response,
216
+ })
217
+ .then(() => true, (error) => {
218
+ if (error instanceof DashboardStepUpError) {
219
+ if (error.code === "auth_busy") {
220
+ sendSettingsError(request, response, 503, "settings_unavailable", error.message);
221
+ }
222
+ else if (error.code === "unauthorized") {
223
+ sendSettingsError(request, response, 403, "settings_auth_required", error.message);
224
+ }
225
+ else if (error.code === "not_enrolled") {
226
+ sendSettingsError(request, response, 403, "step_up_unavailable", error.message);
227
+ }
228
+ else {
229
+ sendSettingsError(request, response, 403, "step_up_failed", error.message);
230
+ }
231
+ return false;
232
+ }
233
+ throw error;
234
+ });
235
+ }
236
+ function mapStoreError(request, response, error) {
237
+ if (!(error instanceof SettingsStoreError))
238
+ throw error;
239
+ // Q3/L1: `settings_locked` messages may name container-only paths (the
240
+ // compose `.lock`, `/data/settings/.lock`), but the mid-update variant
241
+ // (`settings/lock.ts` assertHeld) names NO file — there, any `.lock`
242
+ // present belongs to another writer, so a "remove the file" instruction
243
+ // would be wrong. Append only the neutral container→host path hint.
244
+ // Dashboard layer only: the CLI runs on the host, and `settings/lock.ts`
245
+ // is shared with the progress-report session lock, so its messages stay
246
+ // unchanged.
247
+ const message = error.code === "settings_locked"
248
+ ? `${error.message}. Any paths above are as seen by this dashboard process; in a container, apply them to the host directory bind-mounted at its settings directory.`
249
+ : error.message;
250
+ sendSettingsError(request, response, error.status, error.code, message, {
251
+ ...(error.fieldErrors == null ? {} : { fieldErrors: error.fieldErrors }),
252
+ ...(error.expectedRevision == null ? {} : { expectedRevision: error.expectedRevision }),
253
+ });
254
+ }
255
+ async function handleRead(request, response) {
256
+ const [read, secrets] = await Promise.all([
257
+ store.read(),
258
+ store.secretStatus(),
259
+ ]);
260
+ for (const warning of secrets.warnings) {
261
+ logger.warn({ warning }, "dashboard settings: secrets status warning");
262
+ }
263
+ if (secrets.state === "unreadable") {
264
+ logger.warn({ reason: secrets.reason }, "dashboard settings: the secrets document is unreadable; it projects as unset until an explicit recovery save");
265
+ }
266
+ // T09 wire delta: one flat secrets state and one bindable settings state
267
+ // per GET, so the dashboard can drive the unreadable banner without
268
+ // discriminating on `state`.
269
+ const secretsState = secrets.state === "present"
270
+ ? "ok"
271
+ : secrets.state === "unreadable"
272
+ ? "unreadable"
273
+ : "absent";
274
+ const settingsState = read.state === "present"
275
+ ? { status: "ok" }
276
+ : read.state === "unreadable"
277
+ ? { status: "unreadable", digest: read.digest }
278
+ : { status: "absent" };
279
+ const serverNow = now().toISOString();
280
+ const base = {
281
+ schemaVersion: "clinkx-settings-get-v1",
282
+ settingsState,
283
+ secretsState,
284
+ secrets: secrets.entries,
285
+ secretsRevision: secrets.revision,
286
+ serverNow,
287
+ descriptors,
288
+ };
289
+ let payload;
290
+ if (read.state === "present") {
291
+ // S2 belt-and-braces: the store already excludes secret-class keys;
292
+ // the route filters again so a store regression can never reach the
293
+ // wire (which refines the same invariant).
294
+ const values = {};
295
+ for (const [key, value] of Object.entries(read.values)) {
296
+ if (isSecretSettingKey(key))
297
+ continue;
298
+ values[key] = value;
299
+ }
300
+ payload = {
301
+ ...base,
302
+ state: "ok",
303
+ revision: read.revision,
304
+ updatedAt: read.updatedAt ?? serverNow,
305
+ updatedBy: read.updatedBy ?? { actor: "system", auth: "local-fs" },
306
+ values,
307
+ };
308
+ }
309
+ else if (read.state === "unreadable") {
310
+ payload = {
311
+ ...base,
312
+ state: "unreadable",
313
+ reason: read.reason ?? "the settings document is unreadable",
314
+ digest: read.digest,
315
+ };
316
+ }
317
+ else {
318
+ payload = { ...base, state: "absent" };
319
+ }
320
+ const parsed = SettingsGetResponseSchema.safeParse(payload);
321
+ if (!parsed.success) {
322
+ logger.error({ issues: parsed.error.issues.slice(0, 8) }, "dashboard settings GET response failed its own contract");
323
+ sendGenericError(request, response, 500, "internal_error");
324
+ return;
325
+ }
326
+ sendSettingsJson(request, response, 200, parsed.data);
327
+ }
328
+ async function handleProcesses(request, response) {
329
+ const [read, secrets, list] = await Promise.all([
330
+ store.read(),
331
+ store.secretStatus(),
332
+ processReader.list(processesDir),
333
+ ]);
334
+ for (const warning of list.warnings) {
335
+ logger.warn({ warning }, "dashboard settings: process heartbeat skipped");
336
+ }
337
+ const currentRevision = read.state === "present" ? read.revision : null;
338
+ const processes = list.processes.map((entry) => {
339
+ const document = entry.document;
340
+ const shadowedKeys = [];
341
+ const envEqualsFileKeys = [];
342
+ const invalidFallbackKeys = [];
343
+ for (const [key, provenance] of Object.entries(document.provenance)) {
344
+ // Everything env supplies counts, with or without a file value: the
345
+ // equality hint exists only when the file holds a comparable value.
346
+ // Secret and withheld keys never carry it, so listing them here says
347
+ // nothing about their value.
348
+ if (provenance.source === "env" && provenance.env_equals_file !== true) {
349
+ shadowedKeys.push(key);
350
+ }
351
+ if (provenance.env_equals_file === true) {
352
+ envEqualsFileKeys.push(key);
353
+ }
354
+ if (provenance.source === "invalid_fallback") {
355
+ invalidFallbackKeys.push(key);
356
+ }
357
+ }
358
+ shadowedKeys.sort();
359
+ envEqualsFileKeys.sort();
360
+ invalidFallbackKeys.sort();
361
+ // T09 freshness rule: current only when the loaded settings revision
362
+ // AND digest AND secrets revision all match the store's current
363
+ // documents. A row with missing metadata (pre-W3 heartbeat, no
364
+ // revision/digest) is current:false — its freshness is unknown, never
365
+ // confirmed. L2 exception: with NO store document (fresh install, or
366
+ // secrets only), a process that loaded nothing (null/absent revision
367
+ // and digest) IS current — the present-only rule marked every live
368
+ // process restart-required forever with nothing to restart into. A
369
+ // null loaded secrets revision counts as "no secrets document" and
370
+ // matches an absent (revision 0) store document.
371
+ const loadedSecretsRevision = document.settings.secrets_revision ?? null;
372
+ const settingsMatch = read.state === "present"
373
+ ? document.settings.revision != null &&
374
+ document.settings.digest != null &&
375
+ document.settings.revision === read.revision &&
376
+ document.settings.digest === read.digest
377
+ : read.state === "absent" &&
378
+ document.settings.revision == null &&
379
+ document.settings.digest == null;
380
+ const current = settingsMatch &&
381
+ document.settings.secrets_revision !== undefined &&
382
+ (document.settings.secrets_revision ?? 0) === secrets.revision;
383
+ return {
384
+ id: entry.id,
385
+ host: document.hostname,
386
+ pid: document.pid,
387
+ entry: document.entry,
388
+ version: document.version,
389
+ startedAt: document.started_at,
390
+ lastSeenAt: entry.lastSeenAt,
391
+ liveness: entry.liveness,
392
+ settingsState: document.settings.state,
393
+ loadedRevision: document.settings.revision ?? null,
394
+ loadedSecretsRevision,
395
+ current,
396
+ shadowedKeys,
397
+ envEqualsFileKeys,
398
+ invalidFallbackKeys,
399
+ unknownEnvKeys: document.unknown_env_keys,
400
+ warnings: document.warnings,
401
+ };
402
+ });
403
+ const parsed = SettingsProcessesResponseSchema.safeParse({
404
+ schemaVersion: "clinkx-settings-processes-v1",
405
+ serverNow: now().toISOString(),
406
+ currentRevision,
407
+ processes,
408
+ truncated: list.truncated,
409
+ });
410
+ if (!parsed.success) {
411
+ logger.error({ issues: parsed.error.issues.slice(0, 8) }, "dashboard settings processes response failed its own contract");
412
+ sendGenericError(request, response, 500, "internal_error");
413
+ return;
414
+ }
415
+ sendSettingsJson(request, response, 200, parsed.data);
416
+ }
417
+ async function handleSave(request, response) {
418
+ let body;
419
+ try {
420
+ body = await readSettingsJsonBody(request, MAX_SETTINGS_SAVE_BODY_BYTES);
421
+ }
422
+ catch (error) {
423
+ if (error instanceof SettingsBodyError) {
424
+ if (error.code === "content_too_large_for_dashboard") {
425
+ sendSettingsError(request, response, error.status, error.code, `the settings save body exceeds ${String(MAX_SETTINGS_SAVE_BODY_BYTES)} bytes`);
426
+ }
427
+ else {
428
+ sendGenericError(request, response, error.status, "invalid_request");
429
+ }
430
+ return;
431
+ }
432
+ throw error;
433
+ }
434
+ const parsed = SettingsSaveRequestSchema.safeParse(body);
435
+ if (!parsed.success) {
436
+ sendSettingsError(request, response, SETTINGS_ERROR_HTTP_STATUS.settings_invalid, "settings_invalid", "the settings save request failed validation", { fieldErrors: fieldErrorsFromIssues(parsed.error.issues) });
437
+ return;
438
+ }
439
+ const saveRequest = parsed.data;
440
+ const intent = {
441
+ target: "settings",
442
+ expectedRevision: saveRequest.expectedRevision,
443
+ ops: intentOpsFromWire(saveRequest.ops),
444
+ ...(saveRequest.recover === true ? { recover: true } : {}),
445
+ ...(saveRequest.expectedDigest != null
446
+ ? { expectedDigest: saveRequest.expectedDigest }
447
+ : {}),
448
+ };
449
+ // R5/S3: EVERY recover requires a step-up, even with tuning-only ops —
450
+ // recovery rewrites a document a routine save may not touch, and the
451
+ // intent digest binds the recovery fact and digest.
452
+ if (opsTouchElevatedClass(saveRequest.ops) || saveRequest.recover === true) {
453
+ const verified = await requireStepUp(request, response, intent, saveRequest.stepUp);
454
+ if (!verified)
455
+ return;
456
+ }
457
+ try {
458
+ const result = await store.save({
459
+ expectedRevision: saveRequest.expectedRevision,
460
+ ops: saveRequest.ops.map((op) => ({
461
+ key: op.key,
462
+ action: op.action,
463
+ ...(op.value === undefined ? {} : { value: op.value }),
464
+ })),
465
+ actor: "dashboard",
466
+ auth: authMode,
467
+ ...(saveRequest.recover === true && saveRequest.expectedDigest != null
468
+ ? { recover: true, expectedDigest: saveRequest.expectedDigest }
469
+ : {}),
470
+ });
471
+ if (result.outcome === "published_uncertain") {
472
+ sendSettingsError(request, response, 500, "settings_published_uncertain", `the settings document WAS published at revision ${String(result.revision)} but its durability could not be confirmed (published_uncertain); re-read before retrying`, { revision: result.revision });
473
+ return;
474
+ }
475
+ sendSettingsJson(request, response, 200, SettingsSaveResponseSchema.parse({
476
+ schemaVersion: "clinkx-settings-save-response-v1",
477
+ revision: result.revision,
478
+ updatedAt: result.updatedAt,
479
+ applied: result.applied,
480
+ }));
481
+ return;
482
+ }
483
+ catch (error) {
484
+ mapStoreError(request, response, error);
485
+ return;
486
+ }
487
+ }
488
+ async function handleSecretsSave(request, response) {
489
+ let body;
490
+ try {
491
+ body = await readSettingsJsonBody(request, MAX_SETTINGS_SAVE_BODY_BYTES);
492
+ }
493
+ catch (error) {
494
+ if (error instanceof SettingsBodyError) {
495
+ if (error.code === "content_too_large_for_dashboard") {
496
+ sendSettingsError(request, response, error.status, error.code, `the secrets save body exceeds ${String(MAX_SETTINGS_SAVE_BODY_BYTES)} bytes`);
497
+ }
498
+ else {
499
+ sendGenericError(request, response, error.status, "invalid_request");
500
+ }
501
+ return;
502
+ }
503
+ throw error;
504
+ }
505
+ const parsed = SecretsSaveRequestSchema.safeParse(body);
506
+ if (!parsed.success) {
507
+ sendSettingsError(request, response, SETTINGS_ERROR_HTTP_STATUS.settings_invalid, "settings_invalid", "the secrets save request failed validation", { fieldErrors: fieldErrorsFromIssues(parsed.error.issues) });
508
+ return;
509
+ }
510
+ const saveRequest = parsed.data;
511
+ const intent = {
512
+ target: "secrets",
513
+ expectedRevision: saveRequest.expectedRevision,
514
+ ops: intentOpsFromWire(saveRequest.ops),
515
+ };
516
+ const verified = await requireStepUp(request, response, intent, saveRequest.stepUp);
517
+ if (!verified)
518
+ return;
519
+ try {
520
+ const result = await store.saveSecrets({
521
+ expectedRevision: saveRequest.expectedRevision,
522
+ ops: saveRequest.ops.map((op) => ({
523
+ key: op.key,
524
+ action: op.action,
525
+ ...(op.value === undefined ? {} : { value: op.value }),
526
+ })),
527
+ actor: "dashboard",
528
+ auth: authMode,
529
+ });
530
+ if (result.outcome === "published_uncertain") {
531
+ sendSettingsError(request, response, 500, "settings_published_uncertain", `the secrets document WAS published at revision ${String(result.revision)} but its durability could not be confirmed (published_uncertain); re-read before retrying`, { revision: result.revision });
532
+ return;
533
+ }
534
+ sendSettingsJson(request, response, 200, SecretsSaveResponseSchema.parse({
535
+ schemaVersion: "clinkx-settings-secrets-save-response-v1",
536
+ revision: result.revision,
537
+ updatedAt: result.updatedAt,
538
+ applied: result.applied,
539
+ }));
540
+ return;
541
+ }
542
+ catch (error) {
543
+ mapStoreError(request, response, error);
544
+ return;
545
+ }
546
+ }
547
+ async function handleStepUp(request, response) {
548
+ let body;
549
+ try {
550
+ body = await readSettingsJsonBody(request, MAX_SETTINGS_STEP_UP_BODY_BYTES);
551
+ }
552
+ catch (error) {
553
+ if (error instanceof SettingsBodyError) {
554
+ if (error.code === "content_too_large_for_dashboard") {
555
+ sendSettingsError(request, response, error.status, error.code, `the step-up options body exceeds ${String(MAX_SETTINGS_STEP_UP_BODY_BYTES)} bytes`);
556
+ }
557
+ else {
558
+ sendGenericError(request, response, error.status, "invalid_request");
559
+ }
560
+ return;
561
+ }
562
+ throw error;
563
+ }
564
+ const parsed = StepUpOptionsRequestSchema.safeParse(body);
565
+ if (!parsed.success) {
566
+ sendSettingsError(request, response, SETTINGS_ERROR_HTTP_STATUS.settings_invalid, "settings_invalid", "the step-up options request failed validation", { fieldErrors: fieldErrorsFromIssues(parsed.error.issues) });
567
+ return;
568
+ }
569
+ const intentRequest = parsed.data.intent;
570
+ const target = intentRequest.target;
571
+ const intent = {
572
+ target,
573
+ expectedRevision: intentRequest.expectedRevision,
574
+ ops: intentOpsFromWire(intentRequest.ops),
575
+ ...(intentRequest.recover === true ? { recover: true } : {}),
576
+ ...(intentRequest.expectedDigest != null
577
+ ? { expectedDigest: intentRequest.expectedDigest }
578
+ : {}),
579
+ };
580
+ const intentDigest = computeSettingsIntentDigest(intent);
581
+ // A recovery ceremony is minted even for tuning-only ops: the save it
582
+ // authorizes requires step-up (R5), so the options response must match.
583
+ const elevated = target === "secrets" ||
584
+ intentRequest.recover === true ||
585
+ opsTouchElevatedClass(intentRequest.ops);
586
+ if (!elevated) {
587
+ sendSettingsJson(request, response, 200, StepUpOptionsResponseSchema.parse({
588
+ schemaVersion: "clinkx-settings-step-up-response-v1",
589
+ required: false,
590
+ intentDigest,
591
+ }));
592
+ return;
593
+ }
594
+ if (passkeyAuth == null) {
595
+ sendSettingsError(request, response, 403, "step_up_unavailable", "policy- and secret-class settings changes require a passkey step-up, which is unavailable in bearer/none auth mode");
596
+ return;
597
+ }
598
+ const credentials = passkeyAuth.sessionCredentials(request);
599
+ if (credentials == null) {
600
+ sendSettingsError(request, response, 403, "settings_auth_required", "a live passkey session is required to request step-up options");
601
+ return;
602
+ }
603
+ let challenge;
604
+ try {
605
+ challenge = await passkeyAuth.stepUpOptions({
606
+ sessionId: credentials.sessionId,
607
+ originProof: credentials.originProof,
608
+ intentDigest,
609
+ });
610
+ }
611
+ catch (error) {
612
+ if (!(error instanceof DashboardStepUpError))
613
+ throw error;
614
+ if (error.code === "auth_busy") {
615
+ sendSettingsError(request, response, 503, "settings_unavailable", error.message);
616
+ }
617
+ else if (error.code === "unauthorized") {
618
+ sendSettingsError(request, response, 403, "settings_auth_required", error.message);
619
+ }
620
+ else {
621
+ // not_enrolled: this deployment can never mint a step-up.
622
+ sendSettingsError(request, response, 403, "step_up_unavailable", error.message);
623
+ }
624
+ return;
625
+ }
626
+ sendSettingsJson(request, response, 200, StepUpOptionsResponseSchema.parse({
627
+ schemaVersion: "clinkx-settings-step-up-response-v1",
628
+ required: true,
629
+ challenge: {
630
+ challengeId: challenge.challengeId,
631
+ createdAt: challenge.createdAt,
632
+ expiresAt: challenge.expiresAt,
633
+ },
634
+ intentDigest,
635
+ publicKey: challenge.options,
636
+ }));
637
+ }
638
+ return {
639
+ handles(segments) {
640
+ return isSettingsApiSegments(segments);
641
+ },
642
+ async handle(request, response, target) {
643
+ const segments = target.segments;
644
+ if (target.query.size !== 0) {
645
+ // No settings route accepts query parameters; reject instead of
646
+ // silently ignoring them.
647
+ sendGenericError(request, response, 400, "invalid_request");
648
+ return;
649
+ }
650
+ if (isSettingsProcessesSegments(segments)) {
651
+ if (request.method !== "GET" && request.method !== "HEAD") {
652
+ sendGenericError(request, response, 405, "method_not_allowed", "GET, HEAD");
653
+ return;
654
+ }
655
+ await handleProcesses(request, response);
656
+ return;
657
+ }
658
+ if (isSettingsReadSegments(segments)) {
659
+ if (request.method !== "GET" && request.method !== "HEAD") {
660
+ sendGenericError(request, response, 405, "method_not_allowed", "GET, HEAD");
661
+ return;
662
+ }
663
+ await handleRead(request, response);
664
+ return;
665
+ }
666
+ if (isSettingsSaveSegments(segments)) {
667
+ if (request.method !== "POST") {
668
+ sendGenericError(request, response, 405, "method_not_allowed", "POST");
669
+ return;
670
+ }
671
+ await handleSave(request, response);
672
+ return;
673
+ }
674
+ if (isSettingsSecretsSaveSegments(segments)) {
675
+ if (request.method !== "POST") {
676
+ sendGenericError(request, response, 405, "method_not_allowed", "POST");
677
+ return;
678
+ }
679
+ await handleSecretsSave(request, response);
680
+ return;
681
+ }
682
+ if (request.method !== "POST") {
683
+ sendGenericError(request, response, 405, "method_not_allowed", "POST");
684
+ return;
685
+ }
686
+ await handleStepUp(request, response);
687
+ },
688
+ };
689
+ }
690
+ //# sourceMappingURL=settings-routes.js.map