@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.
- package/CHANGELOG.md +25 -0
- package/README.md +15 -0
- package/deployment-identity-protocol.d.mts +45 -1
- package/deployment-identity-protocol.mjs +169 -5
- package/dist/agent-host/index.d.ts +1 -1
- package/dist/agent-host/index.d.ts.map +1 -1
- package/dist/agent-host/index.js.map +1 -1
- package/dist/agent-host/router.d.ts.map +1 -1
- package/dist/agent-host/router.js +6 -2
- package/dist/agent-host/router.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +11 -0
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +53 -1
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts +35 -1
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +103 -7
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +19 -4
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +58 -28
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +6 -3
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/principal-identity.d.ts +32 -0
- package/dist/approval-api/principal-identity.d.ts.map +1 -0
- package/dist/approval-api/principal-identity.js +69 -0
- package/dist/approval-api/principal-identity.js.map +1 -0
- package/dist/approval-api/principal.d.ts +9 -12
- package/dist/approval-api/principal.d.ts.map +1 -1
- package/dist/approval-api/principal.js +9 -45
- package/dist/approval-api/principal.js.map +1 -1
- package/dist/approval-api/router.d.ts.map +1 -1
- package/dist/approval-api/router.js +9 -1
- package/dist/approval-api/router.js.map +1 -1
- package/dist/approval-api/service.d.ts +19 -0
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +41 -10
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/types.d.ts +12 -0
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js +12 -0
- package/dist/approval-api/types.js.map +1 -1
- package/dist/background-tasks/host.d.ts +127 -14
- package/dist/background-tasks/host.d.ts.map +1 -1
- package/dist/background-tasks/host.js +579 -50
- package/dist/background-tasks/host.js.map +1 -1
- package/dist/background-tasks/index.d.ts +2 -2
- package/dist/background-tasks/index.d.ts.map +1 -1
- package/dist/background-tasks/index.js +11 -6
- package/dist/background-tasks/index.js.map +1 -1
- package/dist/background-tasks/routes.d.ts +19 -2
- package/dist/background-tasks/routes.d.ts.map +1 -1
- package/dist/background-tasks/routes.js +4 -4
- package/dist/background-tasks/routes.js.map +1 -1
- package/dist/deployment-identity-protocol.d.ts +2 -2
- package/dist/deployment-identity-protocol.d.ts.map +1 -1
- package/dist/deployment-identity-protocol.js +1 -1
- package/dist/deployment-identity-protocol.js.map +1 -1
- package/dist/do-runner/cause-chain.d.ts +53 -0
- package/dist/do-runner/cause-chain.d.ts.map +1 -0
- package/dist/do-runner/cause-chain.js +96 -0
- package/dist/do-runner/cause-chain.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +109 -5
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +289 -44
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/deployment-identity.d.ts +29 -5
- package/dist/do-runner/deployment-identity.d.ts.map +1 -1
- package/dist/do-runner/deployment-identity.js +23 -6
- package/dist/do-runner/deployment-identity.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts +4 -23
- package/dist/do-runner/do-error-response.d.ts.map +1 -1
- package/dist/do-runner/do-error-response.js +19 -24
- package/dist/do-runner/do-error-response.js.map +1 -1
- package/dist/do-runner/do-status-error.d.ts +37 -0
- package/dist/do-runner/do-status-error.d.ts.map +1 -0
- package/dist/do-runner/do-status-error.js +42 -0
- package/dist/do-runner/do-status-error.js.map +1 -0
- package/dist/do-runner/durable-object.d.ts +2 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +205 -19
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-fence.d.ts +335 -0
- package/dist/do-runner/execution-fence.d.ts.map +1 -0
- package/dist/do-runner/execution-fence.js +534 -0
- package/dist/do-runner/execution-fence.js.map +1 -0
- package/dist/do-runner/index.d.ts +10 -3
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +16 -3
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +82 -1
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js +58 -3
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/inventory.d.ts +294 -0
- package/dist/do-runner/inventory.d.ts.map +1 -0
- package/dist/do-runner/inventory.js +811 -0
- package/dist/do-runner/inventory.js.map +1 -0
- package/dist/do-runner/notification-predicate.d.ts +8 -0
- package/dist/do-runner/notification-predicate.d.ts.map +1 -0
- package/dist/do-runner/notification-predicate.js +9 -0
- package/dist/do-runner/notification-predicate.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +83 -0
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +131 -4
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/start-idempotency.d.ts +508 -0
- package/dist/do-runner/start-idempotency.d.ts.map +1 -0
- package/dist/do-runner/start-idempotency.js +886 -0
- package/dist/do-runner/start-idempotency.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +14 -0
- package/dist/goals/objective-routes.d.ts.map +1 -1
- package/dist/goals/objective-routes.js +45 -24
- package/dist/goals/objective-routes.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +15 -0
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +22 -1
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +11 -0
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +343 -62
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +20 -0
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +6 -0
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/index.d.ts +2 -2
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +1 -1
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/run-route-error.d.ts +18 -0
- package/dist/host-kit/run-route-error.d.ts.map +1 -1
- package/dist/host-kit/run-route-error.js +23 -0
- package/dist/host-kit/run-route-error.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +58 -1
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +120 -11
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/stream-router.d.ts.map +1 -1
- package/dist/host-kit/stream-router.js +18 -9
- package/dist/host-kit/stream-router.js.map +1 -1
- package/dist/schedules/router.d.ts +15 -0
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +47 -17
- package/dist/schedules/router.js.map +1 -1
- package/dist/schedules/tick.d.ts +13 -0
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +59 -39
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signal-providers/host-do.d.ts +12 -1
- package/dist/signal-providers/host-do.d.ts.map +1 -1
- package/dist/signal-providers/host-do.js +28 -3
- package/dist/signal-providers/host-do.js.map +1 -1
- package/dist/signal-providers/webhook-route.d.ts +14 -0
- package/dist/signal-providers/webhook-route.d.ts.map +1 -1
- package/dist/signal-providers/webhook-route.js +28 -5
- package/dist/signal-providers/webhook-route.js.map +1 -1
- package/dist/signals/notification-dispatch.d.ts +13 -0
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +20 -1
- package/dist/signals/notification-dispatch.js.map +1 -1
- package/dist/signals/notifications-d1.d.ts +8 -0
- package/dist/signals/notifications-d1.d.ts.map +1 -1
- package/dist/signals/notifications-d1.js +15 -9
- package/dist/signals/notifications-d1.js.map +1 -1
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +86 -18
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +1 -1
- 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
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
return
|
|
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
|
-
|
|
210
|
-
|
|
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
|
-
|
|
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 (
|
|
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
|
-
//
|
|
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
|
-
//
|
|
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
|
-
//
|
|
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
|
-
//
|
|
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
|
|
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
|
|
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
|
|
570
|
-
//
|
|
571
|
-
//
|
|
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
|
|
579
|
-
//
|
|
580
|
-
//
|
|
581
|
-
//
|
|
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
|
|
589
|
-
//
|
|
590
|
-
//
|
|
591
|
-
//
|
|
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
|
-
//
|
|
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)
|