@proofoftech/flowsafe 0.19.0 → 0.20.0

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 (172) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +15 -0
  3. package/deployment-identity-protocol.d.mts +45 -1
  4. package/deployment-identity-protocol.mjs +169 -5
  5. package/dist/agent-host/index.d.ts +1 -1
  6. package/dist/agent-host/index.d.ts.map +1 -1
  7. package/dist/agent-host/index.js.map +1 -1
  8. package/dist/agent-host/router.d.ts.map +1 -1
  9. package/dist/agent-host/router.js +6 -2
  10. package/dist/agent-host/router.js.map +1 -1
  11. package/dist/agent-host/thread-host.d.ts +11 -0
  12. package/dist/agent-host/thread-host.d.ts.map +1 -1
  13. package/dist/agent-host/thread-host.js +53 -1
  14. package/dist/agent-host/thread-host.js.map +1 -1
  15. package/dist/agent-host/thread-topology.d.ts +35 -1
  16. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  17. package/dist/agent-host/thread-topology.js +103 -7
  18. package/dist/agent-host/thread-topology.js.map +1 -1
  19. package/dist/agent-runner/durable-agent-runner.d.ts +19 -4
  20. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  21. package/dist/agent-runner/durable-agent-runner.js +58 -28
  22. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  23. package/dist/approval-api/d1-store.d.ts.map +1 -1
  24. package/dist/approval-api/d1-store.js +6 -3
  25. package/dist/approval-api/d1-store.js.map +1 -1
  26. package/dist/approval-api/principal-identity.d.ts +32 -0
  27. package/dist/approval-api/principal-identity.d.ts.map +1 -0
  28. package/dist/approval-api/principal-identity.js +69 -0
  29. package/dist/approval-api/principal-identity.js.map +1 -0
  30. package/dist/approval-api/principal.d.ts +9 -12
  31. package/dist/approval-api/principal.d.ts.map +1 -1
  32. package/dist/approval-api/principal.js +9 -45
  33. package/dist/approval-api/principal.js.map +1 -1
  34. package/dist/approval-api/router.d.ts.map +1 -1
  35. package/dist/approval-api/router.js +9 -1
  36. package/dist/approval-api/router.js.map +1 -1
  37. package/dist/approval-api/service.d.ts +19 -0
  38. package/dist/approval-api/service.d.ts.map +1 -1
  39. package/dist/approval-api/service.js +41 -10
  40. package/dist/approval-api/service.js.map +1 -1
  41. package/dist/approval-api/types.d.ts +12 -0
  42. package/dist/approval-api/types.d.ts.map +1 -1
  43. package/dist/approval-api/types.js +12 -0
  44. package/dist/approval-api/types.js.map +1 -1
  45. package/dist/background-tasks/host.d.ts +127 -14
  46. package/dist/background-tasks/host.d.ts.map +1 -1
  47. package/dist/background-tasks/host.js +579 -50
  48. package/dist/background-tasks/host.js.map +1 -1
  49. package/dist/background-tasks/index.d.ts +2 -2
  50. package/dist/background-tasks/index.d.ts.map +1 -1
  51. package/dist/background-tasks/index.js +11 -6
  52. package/dist/background-tasks/index.js.map +1 -1
  53. package/dist/background-tasks/routes.d.ts +19 -2
  54. package/dist/background-tasks/routes.d.ts.map +1 -1
  55. package/dist/background-tasks/routes.js +4 -4
  56. package/dist/background-tasks/routes.js.map +1 -1
  57. package/dist/deployment-identity-protocol.d.ts +2 -2
  58. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  59. package/dist/deployment-identity-protocol.js +1 -1
  60. package/dist/deployment-identity-protocol.js.map +1 -1
  61. package/dist/do-runner/cause-chain.d.ts +53 -0
  62. package/dist/do-runner/cause-chain.d.ts.map +1 -0
  63. package/dist/do-runner/cause-chain.js +96 -0
  64. package/dist/do-runner/cause-chain.js.map +1 -0
  65. package/dist/do-runner/d1-storage.d.ts +109 -5
  66. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  67. package/dist/do-runner/d1-storage.js +289 -44
  68. package/dist/do-runner/d1-storage.js.map +1 -1
  69. package/dist/do-runner/deployment-identity.d.ts +29 -5
  70. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  71. package/dist/do-runner/deployment-identity.js +23 -6
  72. package/dist/do-runner/deployment-identity.js.map +1 -1
  73. package/dist/do-runner/do-error-response.d.ts +4 -23
  74. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  75. package/dist/do-runner/do-error-response.js +19 -24
  76. package/dist/do-runner/do-error-response.js.map +1 -1
  77. package/dist/do-runner/do-status-error.d.ts +37 -0
  78. package/dist/do-runner/do-status-error.d.ts.map +1 -0
  79. package/dist/do-runner/do-status-error.js +42 -0
  80. package/dist/do-runner/do-status-error.js.map +1 -0
  81. package/dist/do-runner/durable-object.d.ts +2 -1
  82. package/dist/do-runner/durable-object.d.ts.map +1 -1
  83. package/dist/do-runner/durable-object.js +205 -19
  84. package/dist/do-runner/durable-object.js.map +1 -1
  85. package/dist/do-runner/execution-fence.d.ts +335 -0
  86. package/dist/do-runner/execution-fence.d.ts.map +1 -0
  87. package/dist/do-runner/execution-fence.js +534 -0
  88. package/dist/do-runner/execution-fence.js.map +1 -0
  89. package/dist/do-runner/index.d.ts +10 -3
  90. package/dist/do-runner/index.d.ts.map +1 -1
  91. package/dist/do-runner/index.js +16 -3
  92. package/dist/do-runner/index.js.map +1 -1
  93. package/dist/do-runner/init.d.ts +82 -1
  94. package/dist/do-runner/init.d.ts.map +1 -1
  95. package/dist/do-runner/init.js +58 -3
  96. package/dist/do-runner/init.js.map +1 -1
  97. package/dist/do-runner/inventory.d.ts +294 -0
  98. package/dist/do-runner/inventory.d.ts.map +1 -0
  99. package/dist/do-runner/inventory.js +811 -0
  100. package/dist/do-runner/inventory.js.map +1 -0
  101. package/dist/do-runner/notification-predicate.d.ts +8 -0
  102. package/dist/do-runner/notification-predicate.d.ts.map +1 -0
  103. package/dist/do-runner/notification-predicate.js +9 -0
  104. package/dist/do-runner/notification-predicate.js.map +1 -0
  105. package/dist/do-runner/runtime.d.ts +83 -0
  106. package/dist/do-runner/runtime.d.ts.map +1 -1
  107. package/dist/do-runner/runtime.js +131 -4
  108. package/dist/do-runner/runtime.js.map +1 -1
  109. package/dist/do-runner/start-idempotency.d.ts +508 -0
  110. package/dist/do-runner/start-idempotency.d.ts.map +1 -0
  111. package/dist/do-runner/start-idempotency.js +886 -0
  112. package/dist/do-runner/start-idempotency.js.map +1 -0
  113. package/dist/goals/objective-routes.d.ts +14 -0
  114. package/dist/goals/objective-routes.d.ts.map +1 -1
  115. package/dist/goals/objective-routes.js +45 -24
  116. package/dist/goals/objective-routes.js.map +1 -1
  117. package/dist/host-kit/do-run-topology.d.ts +15 -0
  118. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  119. package/dist/host-kit/do-run-topology.js +22 -1
  120. package/dist/host-kit/do-run-topology.js.map +1 -1
  121. package/dist/host-kit/flowsafe-worker.d.ts +11 -0
  122. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  123. package/dist/host-kit/flowsafe-worker.js +343 -62
  124. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  125. package/dist/host-kit/host-approval-service.d.ts +20 -0
  126. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  127. package/dist/host-kit/host-approval-service.js +6 -0
  128. package/dist/host-kit/host-approval-service.js.map +1 -1
  129. package/dist/host-kit/index.d.ts +2 -2
  130. package/dist/host-kit/index.d.ts.map +1 -1
  131. package/dist/host-kit/index.js +1 -1
  132. package/dist/host-kit/index.js.map +1 -1
  133. package/dist/host-kit/run-route-error.d.ts +18 -0
  134. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  135. package/dist/host-kit/run-route-error.js +23 -0
  136. package/dist/host-kit/run-route-error.js.map +1 -1
  137. package/dist/host-kit/run-router.d.ts +58 -1
  138. package/dist/host-kit/run-router.d.ts.map +1 -1
  139. package/dist/host-kit/run-router.js +120 -11
  140. package/dist/host-kit/run-router.js.map +1 -1
  141. package/dist/host-kit/stream-router.d.ts.map +1 -1
  142. package/dist/host-kit/stream-router.js +18 -9
  143. package/dist/host-kit/stream-router.js.map +1 -1
  144. package/dist/schedules/router.d.ts +15 -0
  145. package/dist/schedules/router.d.ts.map +1 -1
  146. package/dist/schedules/router.js +47 -17
  147. package/dist/schedules/router.js.map +1 -1
  148. package/dist/schedules/tick.d.ts +13 -0
  149. package/dist/schedules/tick.d.ts.map +1 -1
  150. package/dist/schedules/tick.js +59 -39
  151. package/dist/schedules/tick.js.map +1 -1
  152. package/dist/signal-providers/host-do.d.ts +12 -1
  153. package/dist/signal-providers/host-do.d.ts.map +1 -1
  154. package/dist/signal-providers/host-do.js +28 -3
  155. package/dist/signal-providers/host-do.js.map +1 -1
  156. package/dist/signal-providers/webhook-route.d.ts +14 -0
  157. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  158. package/dist/signal-providers/webhook-route.js +28 -5
  159. package/dist/signal-providers/webhook-route.js.map +1 -1
  160. package/dist/signals/notification-dispatch.d.ts +13 -0
  161. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  162. package/dist/signals/notification-dispatch.js +20 -1
  163. package/dist/signals/notification-dispatch.js.map +1 -1
  164. package/dist/signals/notifications-d1.d.ts +8 -0
  165. package/dist/signals/notifications-d1.d.ts.map +1 -1
  166. package/dist/signals/notifications-d1.js +15 -9
  167. package/dist/signals/notifications-d1.js.map +1 -1
  168. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  169. package/dist/signals/thread-do-routes.js +86 -18
  170. package/dist/signals/thread-do-routes.js.map +1 -1
  171. package/package.json +1 -1
  172. package/scripts/seed-deployment-identity.mjs +22 -4
@@ -12,8 +12,9 @@
12
12
  import { APPROVAL_ROLES, createActorResolver, createApprovalRouter, createResourceOwnershipSchema, RESOURCE_OWNERSHIP_TABLE, trustAutomationPrincipal, } from '../approval-api/index.js';
13
13
  import { createAuditProxyDurableObjectBinding, createAuditProxyQueue, } from '../audit-export/index.js';
14
14
  import { credentialsMatch } from '../do-runner/deployment-identity.js';
15
- import { DEPLOYMENT_IDENTITY_HEADER, DeploymentIdentityError, deploymentIdentityHeaders, ensureDeploymentIdentityBindings, purgeExpiredBackgroundTasks, purgeExpiredNotifications, purgeExpiredScheduleTriggers, purgeExpiredThreadState, purgeExpiredThreads, purgeExpiredWorkflowRuns, sweepExpiredRunDeadlines, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from '../do-runner/index.js';
15
+ import { assertExecutionFenceState, DEPLOYMENT_IDENTITY_HEADER, DeploymentIdentityError, DeploymentInventory, DoStatusError, deploymentIdentityHeaders, ensureDeploymentIdentityBindings, executionFenceFor, executionFenceReadingPayload, InvalidInventoryRequestError, isInventoryCategory, purgeExpiredBackgroundTasks, purgeExpiredNotifications, purgeExpiredScheduleTriggers, purgeExpiredThreadState, purgeExpiredThreads, purgeExpiredWorkflowRuns, START_IDEMPOTENCY_TABLE, startIdempotencyFor, sweepExpiredRunDeadlines, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from '../do-runner/index.js';
16
16
  import { validateTablePrefix } from '../do-runner/table-prefix.js';
17
+ import { readBoundedBody } from '../http-body.js';
17
18
  import { abandonApprovalsForRun } from './approval-bridge.js';
18
19
  import { bearerActorAuthenticator } from './bearer-auth.js';
19
20
  import { createDoRunTopology, } from './do-run-topology.js';
@@ -39,6 +40,7 @@ function buildConfiguredApprovalService(config, env, topology, options) {
39
40
  notify: options.notify,
40
41
  allowSelfDecision: options.allowSelfDecision,
41
42
  stream: options.stream,
43
+ executionFence: options.executionFence,
42
44
  });
43
45
  }
44
46
  /**
@@ -55,6 +57,7 @@ export function createFlowsafeRunnerLifecycle(config, env, options = {}) {
55
57
  : undefined;
56
58
  const service = buildConfiguredApprovalService(config, env, topology, {
57
59
  store: approvalStoreFactoryFor(env.DB, storageTablePrefix).store(),
60
+ executionFence: executionFenceForEnv(env),
58
61
  waitUntil: options.waitUntil,
59
62
  notify: config.notify?.(env),
60
63
  allowSelfDecision,
@@ -142,6 +145,69 @@ function json(payload, status = 200) {
142
145
  }
143
146
  const MAINTENANCE_ADMIN_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
144
147
  const FLEET_SPEC_DIGEST_PATTERN = /^[a-f0-9]{64}$/;
148
+ /**
149
+ * The credential preamble EVERY /admin surface runs before it does anything.
150
+ *
151
+ * One function rather than a copy per route because this is the trust boundary
152
+ * itself (docs/security-threat-model.md, "The provisioning boundary"): it
153
+ * proves MAINTENANCE_ADMIN_SECRET is configured, proves it is DISTINCT from the
154
+ * deployment identity secret (sharing them would let a Worker-to-DO credential
155
+ * move the fence, and vice versa), and constant-time compares the request's
156
+ * Bearer token against it. A second copy is a second place for one of those
157
+ * three to be dropped in a hurry, and the inventory route lands here next.
158
+ *
159
+ * The surfaces differ in exactly ONE thing, which is why it is a parameter
160
+ * rather than a fork: what an ABSENT secret means. `/admin/execution-fence`
161
+ * always refuses — the fence is the control that stops a deployment executing,
162
+ * so an unauthenticated caller must never reach it. The maintenance routes
163
+ * delegate instead when the fleet requires capability tokens, because there the
164
+ * Durable Object verifies a signed capability and this Worker is only a relay;
165
+ * the longer credential cap applies to that path alone, since a capability
166
+ * token is not a shared secret.
167
+ */
168
+ async function authorizeAdminCredential(request, env, options) {
169
+ const { surface } = options;
170
+ const unavailable = (reason) => {
171
+ console.error(JSON.stringify({
172
+ type: 'config-error',
173
+ var: 'MAINTENANCE_ADMIN_SECRET',
174
+ reason,
175
+ }));
176
+ return {
177
+ authorized: false,
178
+ response: json({ error: `${surface} unavailable` }, 503),
179
+ };
180
+ };
181
+ const unauthenticated = () => ({
182
+ authorized: false,
183
+ response: json({ error: 'authentication required' }, 401),
184
+ });
185
+ const expected = env.MAINTENANCE_ADMIN_SECRET;
186
+ const delegating = expected === undefined && options.delegateWhenUnconfigured;
187
+ if (!delegating) {
188
+ if (expected === undefined ||
189
+ !MAINTENANCE_ADMIN_SECRET_PATTERN.test(expected)) {
190
+ return unavailable(`${surface} is not configured`);
191
+ }
192
+ if (await credentialsMatch(expected, env.DEPLOYMENT_IDENTITY_SECRET)) {
193
+ return unavailable('maintenance and deployment identity credentials must differ');
194
+ }
195
+ }
196
+ const credential = bearerCredential(request);
197
+ const maximumCredentialLength = delegating ? 2_048 : 256;
198
+ if (!credential || credential.length > maximumCredentialLength) {
199
+ return unauthenticated();
200
+ }
201
+ if (expected !== undefined &&
202
+ !(await credentialsMatch(credential, expected))) {
203
+ return unauthenticated();
204
+ }
205
+ return { authorized: true, credential, delegated: delegating };
206
+ }
207
+ /** The Bearer credential a request presents, if it presents a well-formed one. */
208
+ function bearerCredential(request) {
209
+ return request.headers.get('authorization')?.match(/^Bearer\s+(.+)$/i)?.[1];
210
+ }
145
211
  async function maintenanceAdminResponse(request, env) {
146
212
  const url = new URL(request.url);
147
213
  const operation = url.pathname === '/admin/ensure-maintenance'
@@ -155,44 +221,15 @@ async function maintenanceAdminResponse(request, env) {
155
221
  if (request.method !== expectedMethod) {
156
222
  return json({ error: 'method not allowed' }, 405);
157
223
  }
158
- const expected = env.MAINTENANCE_ADMIN_SECRET;
159
- if (expected === undefined &&
160
- env.FLEET_MAINTENANCE_CAPABILITIES !== 'required') {
161
- console.error(JSON.stringify({
162
- type: 'config-error',
163
- var: 'MAINTENANCE_ADMIN_SECRET',
164
- reason: 'maintenance administration is not configured',
165
- }));
166
- return json({ error: 'maintenance administration unavailable' }, 503);
167
- }
168
- if (expected !== undefined &&
169
- !MAINTENANCE_ADMIN_SECRET_PATTERN.test(expected)) {
170
- console.error(JSON.stringify({
171
- type: 'config-error',
172
- var: 'MAINTENANCE_ADMIN_SECRET',
173
- reason: 'maintenance administration is not configured',
174
- }));
175
- return json({ error: 'maintenance administration unavailable' }, 503);
176
- }
177
- if (expected !== undefined &&
178
- (await credentialsMatch(expected, env.DEPLOYMENT_IDENTITY_SECRET))) {
179
- console.error(JSON.stringify({
180
- type: 'config-error',
181
- var: 'MAINTENANCE_ADMIN_SECRET',
182
- reason: 'maintenance and deployment identity credentials must differ',
183
- }));
184
- return json({ error: 'maintenance administration unavailable' }, 503);
185
- }
186
- const actual = request.headers
187
- .get('authorization')
188
- ?.match(/^Bearer\s+(.+)$/i)?.[1];
189
- const maximumCredentialLength = expected === undefined ? 2_048 : 256;
190
- if (!actual || actual.length > maximumCredentialLength) {
191
- return json({ error: 'authentication required' }, 401);
192
- }
193
- if (expected !== undefined && !(await credentialsMatch(actual, expected))) {
194
- return json({ error: 'authentication required' }, 401);
195
- }
224
+ const gate = await authorizeAdminCredential(request, env, {
225
+ surface: 'maintenance administration',
226
+ // An unconfigured secret is survivable HERE and only here: a fleet that
227
+ // requires capability tokens authenticates at the maintenance DO, which
228
+ // verifies a signed capability this Worker only relays.
229
+ delegateWhenUnconfigured: env.FLEET_MAINTENANCE_CAPABILITIES === 'required',
230
+ });
231
+ if (!gate.authorized)
232
+ return gate.response;
196
233
  const deploymentSpecDigest = env.FLEET_SPEC_DIGEST;
197
234
  if (deploymentSpecDigest !== undefined &&
198
235
  !FLEET_SPEC_DIGEST_PATTERN.test(deploymentSpecDigest)) {
@@ -206,11 +243,18 @@ async function maintenanceAdminResponse(request, env) {
206
243
  const id = env.MAINTENANCE.idFromName(MAINTENANCE_INSTANCE_NAME);
207
244
  const response = await env.MAINTENANCE.get(id).fetch(`http://maintenance/${operation}`, {
208
245
  method: expectedMethod,
209
- headers: expected === undefined
210
- ? { authorization: `Bearer ${actual}` }
246
+ // The gate's own verdict, not a second reading of the env var it decided
247
+ // on: a delegated request carries a capability the maintenance DO
248
+ // verifies, so this Worker relays the credential unchanged; anything else
249
+ // was authenticated HERE and travels on the deployment identity.
250
+ headers: gate.delegated
251
+ ? { authorization: `Bearer ${gate.credential}` }
211
252
  : deploymentIdentityHeaders(env.DEPLOYMENT_IDENTITY_SECRET),
212
253
  });
213
- if (expected === undefined)
254
+ // Nothing to enrich on the delegated path: the digest check below belongs to
255
+ // the deployment this Worker authenticated for, and a relayed response is the
256
+ // maintenance DO's own answer.
257
+ if (gate.delegated)
214
258
  return response;
215
259
  if (!response.ok || deploymentSpecDigest === undefined)
216
260
  return response;
@@ -223,6 +267,203 @@ async function maintenanceAdminResponse(request, env) {
223
267
  deploymentSpecDigest,
224
268
  });
225
269
  }
270
+ /**
271
+ * This composer's env-shaped view of the ONE per-database fence memo
272
+ * (do-runner/execution-fence.ts). Every call site here holds an `env` rather
273
+ * than a binding, so the unwrapping happens once instead of at each of them;
274
+ * the identity guarantee — admin route, approval service, and runner runtime
275
+ * all on the same store for the same database — belongs to the shared memo.
276
+ */
277
+ function executionFenceForEnv(env) {
278
+ return executionFenceFor(env.DB);
279
+ }
280
+ /**
281
+ * The same env-shaped view of the ONE per-database start-reservation memo
282
+ * (do-runner/start-idempotency.ts), for the same reason: the run router
283
+ * reserves here, and the runtime inside the run object settles there, and both
284
+ * must be the store built from THIS env's binding.
285
+ */
286
+ function startIdempotencyForEnv(env) {
287
+ return startIdempotencyFor(env.DB);
288
+ }
289
+ const EXECUTION_FENCE_ADMIN_PATH = '/admin/execution-fence';
290
+ const EXECUTION_FENCE_ADMIN_MAX_BODY_BYTES = 4_096;
291
+ /**
292
+ * The deployment execution fence's control-plane surface, behind the SAME gate
293
+ * `maintenanceAdminResponse` uses (`authorizeAdminCredential`) — it is the same
294
+ * trust boundary (the provisioning TCB, docs/security-threat-model.md), and
295
+ * splitting the credential would only add a second secret an operator can get
296
+ * wrong.
297
+ *
298
+ * `GET` reports the state; `POST` moves it, compare-and-set on `expected`.
299
+ * Transition POLICY is the HOST's: this package enforces only the state
300
+ * vocabulary, the CAS, and the rule that entering 'proof-only' names a proof
301
+ * key. Which sequence of states a migration walks is the control plane's
302
+ * business, and hard-coding it here would freeze an operational procedure into
303
+ * a published package.
304
+ *
305
+ * Answers on a mis-provisioned deployment are NOT reachable: the identity gate
306
+ * 503s before this dispatch. Accepted — an operator whose bindings are wrong
307
+ * has a bigger problem than the fence, and relaxing the identity gate to serve
308
+ * this route would put an unverified database behind a control-plane write.
309
+ */
310
+ async function executionFenceAdminResponse(request, env) {
311
+ const url = new URL(request.url);
312
+ if (url.pathname !== EXECUTION_FENCE_ADMIN_PATH)
313
+ return null;
314
+ if (request.method !== 'GET' && request.method !== 'POST') {
315
+ return json({ error: 'method not allowed' }, 405);
316
+ }
317
+ const gate = await authorizeAdminCredential(request, env, {
318
+ surface: 'execution fence administration',
319
+ // Unconfigured is 503, never open: the fence is the control that stops a
320
+ // deployment executing, so an unauthenticated caller must never move it.
321
+ // There is no capability-token relay behind this route to delegate to.
322
+ delegateWhenUnconfigured: false,
323
+ });
324
+ if (!gate.authorized)
325
+ return gate.response;
326
+ const fence = executionFenceForEnv(env);
327
+ try {
328
+ if (request.method === 'GET') {
329
+ return json(executionFenceReadingPayload(await fence.read()));
330
+ }
331
+ const raw = await readBoundedBody(request, EXECUTION_FENCE_ADMIN_MAX_BODY_BYTES, 'execution fence body exceeds limit');
332
+ if (!raw.ok) {
333
+ return json({ error: 'a JSON object body is required' }, raw.reason === 'payload-too-large' ? 413 : 400);
334
+ }
335
+ let parsed;
336
+ try {
337
+ parsed = raw.text === '' ? undefined : JSON.parse(raw.text);
338
+ }
339
+ catch {
340
+ parsed = undefined;
341
+ }
342
+ if (parsed === null ||
343
+ typeof parsed !== 'object' ||
344
+ Array.isArray(parsed)) {
345
+ return json({ error: 'a JSON object body is required' }, 400);
346
+ }
347
+ const body = parsed;
348
+ const reading = await fence.transition({
349
+ expected: assertExecutionFenceState(body.expected, 'expected'),
350
+ next: assertExecutionFenceState(body.next, 'next'),
351
+ ...(body.proofKey === undefined ? {} : { proofKey: body.proofKey }),
352
+ });
353
+ return json({ state: reading.state });
354
+ }
355
+ catch (error) {
356
+ if (error instanceof DoStatusError) {
357
+ return json({
358
+ error: error.message,
359
+ ...(error.reason === undefined ? {} : { reason: error.reason }),
360
+ }, error.status);
361
+ }
362
+ console.error(JSON.stringify({
363
+ type: 'execution-fence-admin-error',
364
+ reason: error instanceof Error ? error.message : String(error),
365
+ }));
366
+ return json({ error: 'execution fence administration failed' }, 500);
367
+ }
368
+ }
369
+ const INVENTORY_ADMIN_PATH = '/admin/inventory';
370
+ /**
371
+ * The deployment's drain-proof surface uses the same credential helper as the
372
+ * fence and maintenance routes. Their absent-secret policies differ:
373
+ * maintenance routes may delegate to a fleet capability; fence and inventory
374
+ * routes never do.
375
+ *
376
+ * WHAT IT IS FOR. An operator holds the fence in `draining` and needs to prove,
377
+ * with no side effects, that this deployment holds no executable or resumable
378
+ * work before locking it for a migration. Without such a proof the only
379
+ * available answer is a wait-and-hope, and a suspended run that survives it
380
+ * gets resumed by two deployments at once.
381
+ *
382
+ * HOW TO READ THE ANSWER — the contract the index response also states, in
383
+ * full, because this is the part a hurried operator skips:
384
+ *
385
+ * Each result is a point-in-time observation, not a snapshot. Rows can enter
386
+ * or leave `work` categories while draining admits work. An empty result
387
+ * cannot over-count work, and keyset pagination never skips a row that
388
+ * existed before the sweep started.
389
+ *
390
+ * The proof is TWO consecutive full sweeps, at least one 60-second
391
+ * RUN_OWNER_RECOVERY_DELAY_MS cadence apart, in which every `work` category
392
+ * comes back empty. One sweep cannot cover the window in which a run object
393
+ * has journalled its recovery key but not yet written its D1 owner row; two,
394
+ * spaced that far, can.
395
+ *
396
+ * An empty sweep from `draining` contributes to the two-sweep proof. After
397
+ * the transition to `migration-locked`, an empty post-lock re-sweep is
398
+ * conclusive because the lock refuses new work. A non-empty one means work is
399
+ * still outstanding, either because it entered after the proof or because
400
+ * the lock parked it before it finished. Return to `draining` and repeat the
401
+ * proof.
402
+ *
403
+ * `standing` categories (schedules, provider subscriptions) are reported for
404
+ * reconciliation and are never required to be empty: they are configuration a
405
+ * migration carries across.
406
+ *
407
+ * GET only. Every query underneath is a bare SELECT that never creates schema,
408
+ * so running this against a deployment about to be copied does not change what
409
+ * is being copied.
410
+ */
411
+ async function inventoryAdminResponse(request, env, storageTablePrefix) {
412
+ const url = new URL(request.url);
413
+ if (url.pathname !== INVENTORY_ADMIN_PATH)
414
+ return null;
415
+ if (request.method !== 'GET') {
416
+ return json({ error: 'method not allowed' }, 405);
417
+ }
418
+ const gate = await authorizeAdminCredential(request, env, {
419
+ surface: 'deployment inventory',
420
+ // Unconfigured is 503, never open: this read enumerates every outstanding
421
+ // run, approval, and reservation on the deployment. There is no capability
422
+ // relay behind it to delegate to, either.
423
+ delegateWhenUnconfigured: false,
424
+ });
425
+ if (!gate.authorized)
426
+ return gate.response;
427
+ try {
428
+ const inventory = new DeploymentInventory(env.DB, {
429
+ ...(storageTablePrefix === undefined
430
+ ? {}
431
+ : { tablePrefix: storageTablePrefix }),
432
+ });
433
+ const category = url.searchParams.get('category');
434
+ if (category === null || category === '') {
435
+ return json(inventory.index());
436
+ }
437
+ if (!isInventoryCategory(category)) {
438
+ throw new InvalidInventoryRequestError(`unknown inventory category '${category}'`);
439
+ }
440
+ const rawLimit = url.searchParams.get('limit');
441
+ // Parsed here rather than coerced inside the store: `Number('abc')` is NaN
442
+ // and `Number('')` is 0, and both would otherwise reach the clamp as a
443
+ // number that means something the caller never asked for.
444
+ if (rawLimit !== null && !/^[0-9]{1,4}$/.test(rawLimit)) {
445
+ throw new InvalidInventoryRequestError('inventory limit must be a positive integer');
446
+ }
447
+ const cursor = url.searchParams.get('cursor');
448
+ return json(await inventory.read(category, {
449
+ ...(cursor === null ? {} : { cursor }),
450
+ ...(rawLimit === null ? {} : { limit: Number(rawLimit) }),
451
+ }));
452
+ }
453
+ catch (error) {
454
+ if (error instanceof DoStatusError) {
455
+ return json({
456
+ error: error.message,
457
+ ...(error.reason === undefined ? {} : { reason: error.reason }),
458
+ }, error.status);
459
+ }
460
+ console.error(JSON.stringify({
461
+ type: 'inventory-admin-error',
462
+ reason: error instanceof Error ? error.message : String(error),
463
+ }));
464
+ return json({ error: 'deployment inventory failed' }, 500);
465
+ }
466
+ }
226
467
  export function createFlowsafeWorker(config) {
227
468
  const storageTablePrefix = validateTablePrefix(config.storageTablePrefix, 'storageTablePrefix');
228
469
  // Authenticate before constructing request-scoped services.
@@ -233,6 +474,7 @@ export function createFlowsafeWorker(config) {
233
474
  deploymentTag: env.DEPLOYMENT_TENANT,
234
475
  buildService: (store) => buildConfiguredApprovalService(config, env, topology, {
235
476
  store,
477
+ executionFence: executionFenceForEnv(env),
236
478
  waitUntil,
237
479
  notify,
238
480
  stream,
@@ -303,6 +545,22 @@ export function createFlowsafeWorker(config) {
303
545
  // cannot leave unbounded run-ownership tombstones or expose a live row
304
546
  // without its authorization record.
305
547
  resourceOwnerTable: RESOURCE_OWNERSHIP_TABLE,
548
+ // Start reservations join the same transaction, for the same reason:
549
+ // an idempotency key must never be reaped while the run it names is
550
+ // still readable, or the next retry of that key would start a second
551
+ // run beside the live one. The horizon defaults to run retention —
552
+ // START_IDEMPOTENCY_RETENTION_DAYS is what a host sets when its callers
553
+ // retry for longer than it keeps run summaries.
554
+ startIdempotencyTable: START_IDEMPOTENCY_TABLE,
555
+ ...(env.START_IDEMPOTENCY_RETENTION_DAYS === undefined
556
+ ? {}
557
+ : {
558
+ startIdempotencyTtlMs: numberVar(env.START_IDEMPOTENCY_RETENTION_DAYS, 30, 'START_IDEMPOTENCY_RETENTION_DAYS', { allowZero: true }) *
559
+ 24 *
560
+ 60 *
561
+ 60 *
562
+ 1000,
563
+ }),
306
564
  });
307
565
  }
308
566
  catch (error) {
@@ -346,7 +604,7 @@ export function createFlowsafeWorker(config) {
346
604
  recordFailure('thread-retention-purge', error);
347
605
  }
348
606
  }
349
- // Background-task TTL cleanup (Track B, opt-in). Its OWN try/catch, like
607
+ // Background-task TTL cleanup (opt-in). Its OWN try/catch, like
350
608
  // every sibling duty: a wedged background-task purge must cost the
351
609
  // run-snapshot, approval, and thread purges nothing.
352
610
  let backgroundTasksPurged;
@@ -362,7 +620,7 @@ export function createFlowsafeWorker(config) {
362
620
  recordFailure('background-task-purge', error);
363
621
  }
364
622
  }
365
- // Track C notification TTL (opt-in). Its OWN try/catch, like every sibling
623
+ // Notification TTL cleanup (opt-in). Its OWN try/catch, like every sibling
366
624
  // duty. optionalNumberVar (GATES the duty; unset/garbage => do not delete).
367
625
  let notificationsPurged;
368
626
  const notificationRetentionDays = optionalNumberVar(env.NOTIFICATION_RETENTION_DAYS, 'NOTIFICATION_RETENTION_DAYS', { allowZero: true });
@@ -377,7 +635,7 @@ export function createFlowsafeWorker(config) {
377
635
  recordFailure('notification-purge', error);
378
636
  }
379
637
  }
380
- // Track C thread-state TTL (opt-in). Same isolation + opt-in posture.
638
+ // Thread-state TTL cleanup (opt-in). Same isolation + opt-in posture.
381
639
  let threadStatePurged;
382
640
  const threadStateRetentionDays = optionalNumberVar(env.THREAD_STATE_RETENTION_DAYS, 'THREAD_STATE_RETENTION_DAYS', { allowZero: true });
383
641
  if (threadStateRetentionDays !== undefined) {
@@ -391,7 +649,7 @@ export function createFlowsafeWorker(config) {
391
649
  recordFailure('thread-state-purge', error);
392
650
  }
393
651
  }
394
- // Track D schedule-trigger history TTL (opt-in). Same isolation + opt-in
652
+ // Schedule-trigger history TTL cleanup (opt-in). Same isolation + opt-in
395
653
  // posture. Only the fire HISTORY expires; schedule config rows are reaped
396
654
  // only at deployment teardown.
397
655
  let scheduleTriggersPurged;
@@ -434,7 +692,7 @@ export function createFlowsafeWorker(config) {
434
692
  ? { ok: true, value: undefined }
435
693
  : { ok: false, error: failures.join('; ') };
436
694
  }
437
- // Track D schedule tick — its OWN failure-isolated duty (own try/catch, own log
695
+ // Schedule tick — its OWN failure-isolated duty (own try/catch, own log
438
696
  // line). A wedged fire pass must cost the other duties nothing, and vice
439
697
  // versa (the same failure-isolation rationale).
440
698
  async function runScheduleTickDuty(env, trigger) {
@@ -519,12 +777,25 @@ export function createFlowsafeWorker(config) {
519
777
  const maintenanceAdmin = await maintenanceAdminResponse(request, env);
520
778
  if (maintenanceAdmin)
521
779
  return maintenanceAdmin;
780
+ // The execution fence's control plane, beside the maintenance admin
781
+ // routes and ahead of every tenant router: it must answer while the
782
+ // deployment is refusing tenant traffic, which is the whole state it
783
+ // exists to report and clear.
784
+ const fenceAdmin = await executionFenceAdminResponse(request, env);
785
+ if (fenceAdmin)
786
+ return fenceAdmin;
787
+ // Beside the fence for the same reason: the drain proof is read WHILE
788
+ // the deployment is refusing tenant traffic, so it must not sit behind
789
+ // a router that a drain is trying to empty.
790
+ const inventoryAdmin = await inventoryAdminResponse(request, env, storageTablePrefix);
791
+ if (inventoryAdmin)
792
+ return inventoryAdmin;
522
793
  const waitUntil = (promise) => ctx.waitUntil(promise);
523
794
  const topology = createDoRunTopology(env.RUNNER, env.DEPLOYMENT_IDENTITY_SECRET);
524
795
  const notify = config.notify?.(env);
525
796
  const selfDecision = parseSelfDecision(env);
526
797
  // Fetch-scope live fan-out sink: present iff a hub is bound (streaming is
527
- // opt-in, DL-019). Each publish rides ctx.waitUntil (DL-020) and is
798
+ // opt-in). Each publish rides ctx.waitUntil and is
528
799
  // contained — a failed fan-out logs and never fails the mutation.
529
800
  const hub = env.HUB;
530
801
  let streamSink;
@@ -550,7 +821,7 @@ export function createFlowsafeWorker(config) {
550
821
  if (agentResponse)
551
822
  return agentResponse;
552
823
  }
553
- // Optional stream stage (DL-015/DL-019): mounted only when BOTH the hub
824
+ // Optional stream stage: mounted only when BOTH the hub
554
825
  // binding and the ticket secret are present. Every route is under
555
826
  // /api/stream/, so it composes ahead of the approval router without
556
827
  // touching the /api/* run_worker_first entry.
@@ -566,29 +837,29 @@ export function createFlowsafeWorker(config) {
566
837
  if (streamResponse)
567
838
  return streamResponse;
568
839
  }
569
- // Optional Track C signal stage (P6): the host-built createSignalRouter,
570
- // closed over THIS request's resolver. `/api/threads/*` — composes ahead
571
- // of approvals/runs without overlap. Absent seam => unmounted.
840
+ // Optional signal stage: the host-built createSignalRouter closes over
841
+ // THIS request's resolver. `/api/threads/*` composes ahead of
842
+ // approvals/runs without overlap. Absent seam => unmounted.
572
843
  const signalRouter = config.buildSignalRouter?.(resolve, env);
573
844
  if (signalRouter) {
574
845
  const signalResponse = await signalRouter(request);
575
846
  if (signalResponse)
576
847
  return signalResponse;
577
848
  }
578
- // Optional Track F goal stage (P6-lite, DL-018): the host-built
579
- // createObjectiveRouter, closed over THIS request's resolver.
580
- // `/api/threads/:threadId/goal` — composes after signals (non-overlapping)
581
- // and ahead of approvals/runs. Absent seam ⇒ unmounted, byte-identical.
849
+ // Optional goal stage: the host-built createObjectiveRouter closes over
850
+ // THIS request's resolver. `/api/threads/:threadId/goal` composes after
851
+ // signals and ahead of approvals/runs. Absent seam => unmounted and
852
+ // byte-identical.
582
853
  const objectiveRouter = config.buildObjectiveRouter?.(resolve, env);
583
854
  if (objectiveRouter) {
584
855
  const objectiveResponse = await objectiveRouter(request);
585
856
  if (objectiveResponse)
586
857
  return objectiveResponse;
587
858
  }
588
- // Optional Track D schedule CRUD stage (DL-013): the host-built
589
- // createScheduleRouter, closed over THIS request's resolver. `/api/schedules/*`
590
- // — composes after goals (non-overlapping), ahead of approvals/runs. Absent
591
- // seam ⇒ unmounted, byte-identical.
859
+ // Optional schedule CRUD stage: the host-built createScheduleRouter
860
+ // closes over THIS request's resolver. `/api/schedules/*` composes
861
+ // after goals and ahead of approvals/runs. Absent seam => unmounted
862
+ // and byte-identical.
592
863
  const scheduleRouter = config.buildScheduleRouter?.(resolve, env);
593
864
  if (scheduleRouter) {
594
865
  const scheduleResponse = await scheduleRouter(request);
@@ -608,14 +879,24 @@ export function createFlowsafeWorker(config) {
608
879
  status: topology.status,
609
880
  resume: topology.resume,
610
881
  terminate: topology.terminate,
882
+ // Both halves come from this env's own bindings: the store from the
883
+ // per-database memo (so the runtime inside the run object settles the
884
+ // very rows this router reserved), and the probe from the same DO
885
+ // topology every other run operation travels through (so "is it
886
+ // live?" is asked of the one object that could be running it).
887
+ startIdempotency: {
888
+ store: startIdempotencyForEnv(env),
889
+ live: topology.startLiveness,
890
+ executionFence: executionFenceForEnv(env),
891
+ },
611
892
  beforeStart: beforeStart
612
893
  ? (context, workflowId, inputData) => beforeStart(context, env, workflowId, inputData)
613
894
  : undefined,
614
895
  beforeResume: beforeResume
615
896
  ? (context, workflowId, runId, body) => beforeResume(context, env, workflowId, runId, body)
616
897
  : undefined,
617
- // D4 self-healing, waitUntil-detached — the shared wrapper owns the
618
- // detach + reconcile-error logging.
898
+ // Self-healing approval reconciliation is waitUntil-detached; the
899
+ // shared wrapper owns the detach + reconcile-error logging.
619
900
  reconcileApprovals: reconcileApprovalsOnStatusDetached(config.systemPrincipalId, waitUntil),
620
901
  })(request);
621
902
  if (runResponse)