refactor: hand off between IDE and agents through Git only
The IDE carried a second, Theia-internal coordination system: multi- client save barriers, a hash-chained snapshot store, IndexedDB draft recovery, transferable debugger-control leases that intercepted Theia's plugin RPC, Ed25519 actor assertions from the gateway, and an API gate that blocked every agent integration while any IDE workspace was open until a human imported a coordinated snapshot. It depended on Theia internals, made F5 debugging require five environment variables plus a gateway-signed header, and stalled agent runs. IDE and agents now hand off through Git commits (docs/architecture.md ADR-7). - Delete apps/ide/coordination, apps/ide/security, the policy extension's coordination/draft/DAP-guard/lifecycle-safety modules and the unused product.json; the policy extension keeps only the managed extension allow-list and scoped collaboration. - API: workspace snapshot import/match/check routes are gone. The project integration lease (one integrating run per project, fenced) moves to domain/integration-lease.ts and is still enforced on integrate/build transitions and build evidence. - Workspace lifecycle: pause/resume no longer requires a save barrier; automatic sleep needs 30 idle minutes and zero gateway connections, which the gateway now reports itself. The lifecycle/integration authorize relays and the gateway's assertion signing are removed; gateway edit roles match the contract roles. - Worker: no snapshot matching, workspace-input gate or local lock file during integration; runtime workspace-snapshot is removed. - Web: the snapshot import panel is removed from run detail. - Provisioner workspaces no longer mount coordination state or the gateway public key; local setup no longer generates gateway keys. The local Theia build under apps/ide/lib must be rebuilt to pick up the slimmer policy extension. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
20bc7cfeb7
commit
3931bf94f0
@ -28,7 +28,7 @@ import { activeBundle, resolveBundle } from './agent-bundles.js';
|
||||
import { Artifacts } from './artifacts.js';
|
||||
import { providerProxyConfigured } from './provider-proxy.js';
|
||||
import { assertVerificationProfile, verificationPolicyDigest } from './verification-policy.js';
|
||||
import { WorkspaceIntegration } from './workspace-integration.js';
|
||||
import { IntegrationLeases } from './integration-lease.js';
|
||||
|
||||
export const now = () => new Date().toISOString();
|
||||
export function record(tenantId: string): Entity {
|
||||
@ -96,13 +96,13 @@ export function executionLease(actor: Actor, run: Run, token: number) {
|
||||
|
||||
export class ControlPlane {
|
||||
readonly artifacts: Artifacts;
|
||||
readonly workspaceIntegration: WorkspaceIntegration;
|
||||
readonly integration: IntegrationLeases;
|
||||
constructor(
|
||||
readonly store: Store,
|
||||
readonly env = process.env,
|
||||
) {
|
||||
this.artifacts = new Artifacts(store, env);
|
||||
this.workspaceIntegration = new WorkspaceIntegration(store, env);
|
||||
this.integration = new IntegrationLeases(store, env);
|
||||
}
|
||||
async projects(actor: Actor) {
|
||||
return this.store.transaction(actor.tenantId, async tx =>
|
||||
@ -490,7 +490,7 @@ export class ControlPlane {
|
||||
if (!['worker', 'verifier', 'deployer'].includes(actor.kind))
|
||||
throw new DomainError('FORBIDDEN', 'Execution identity required', 403);
|
||||
if (['integrate', 'build'].includes(data.stage) && data.status === 'running')
|
||||
await this.workspaceIntegration.enforce(actor, id, data.leaseToken);
|
||||
await this.integration.enforce(actor, id, data.leaseToken);
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
let run = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, run, data.leaseToken);
|
||||
@ -556,8 +556,7 @@ export class ControlPlane {
|
||||
(data.type !== 'deployment' && actor.kind !== 'verifier')
|
||||
)
|
||||
throw new DomainError('FORBIDDEN', 'An independent verifier/deployer identity must submit evidence', 403);
|
||||
if (data.type === 'build' && data.passed)
|
||||
await this.workspaceIntegration.enforce(actor, data.runId, data.leaseToken ?? 0);
|
||||
if (data.type === 'build' && data.passed) await this.integration.enforce(actor, data.runId, data.leaseToken ?? 0);
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', data.runId);
|
||||
if (run.revision !== data.revision || terminal(run))
|
||||
|
||||
133
apps/api/src/domain/integration-lease.ts
Normal file
133
apps/api/src/domain/integration-lease.ts
Normal file
@ -0,0 +1,133 @@
|
||||
import { DomainError, type Actor, type Project, type Run } from '@wishforge/contracts';
|
||||
import type { Store } from '../db/store.js';
|
||||
import { executionLease, executionScope, must, projectAccess, touch } from './control-plane.js';
|
||||
|
||||
/**
|
||||
* Only one run per project may integrate into the target branch at a time. The
|
||||
* lease is held by the verifier of that run and is fenced by a per-project
|
||||
* counter, so a stale verifier can never advance the branch or record a build.
|
||||
*/
|
||||
export interface IntegrationLease {
|
||||
runId: string;
|
||||
generation: unknown;
|
||||
verifierId: string;
|
||||
leaseToken: number;
|
||||
fence: number;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
const LEASE_MS = 60_000;
|
||||
|
||||
function expiry(run: Run) {
|
||||
return new Date(Math.min(Date.now() + LEASE_MS, Date.parse(run.lease!.expiresAt))).toISOString();
|
||||
}
|
||||
|
||||
export class IntegrationLeases {
|
||||
constructor(
|
||||
private readonly store: Store,
|
||||
private readonly env = process.env,
|
||||
) {}
|
||||
|
||||
async acquire(actor: Actor, id: string, leaseToken: number) {
|
||||
if (actor.kind !== 'verifier') throw new DomainError('FORBIDDEN', 'Independent verifier required', 403);
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, run, leaseToken);
|
||||
const project = await projectAccess(tx, actor, run.projectId);
|
||||
const previous = project.integrationLease as IntegrationLease | undefined;
|
||||
if (previous && Date.parse(previous.expiresAt) > Date.now()) {
|
||||
const owner = await tx.get<Run>('run', previous.runId);
|
||||
const live =
|
||||
owner &&
|
||||
owner.executionGeneration === previous.generation &&
|
||||
owner.lease?.token === previous.leaseToken &&
|
||||
Date.parse(owner.lease.expiresAt) > Date.now();
|
||||
const mine =
|
||||
previous.runId === id &&
|
||||
previous.generation === run.executionGeneration &&
|
||||
previous.leaseToken === leaseToken &&
|
||||
previous.verifierId === actor.userId;
|
||||
if (live && !mine) throw new DomainError('INTEGRATION_BUSY', 'Another run owns the project integration queue');
|
||||
if (live) {
|
||||
previous.expiresAt = expiry(run);
|
||||
await tx.put('project', touch(project));
|
||||
return previous;
|
||||
}
|
||||
}
|
||||
const fence = Number(project.integrationFence ?? 0) + 1;
|
||||
const lease: IntegrationLease = {
|
||||
runId: id,
|
||||
generation: run.executionGeneration,
|
||||
verifierId: actor.userId,
|
||||
leaseToken,
|
||||
fence,
|
||||
expiresAt: expiry(run),
|
||||
};
|
||||
project.integrationFence = fence;
|
||||
project.integrationLease = lease;
|
||||
run.projectIntegrationFence = fence;
|
||||
await tx.put('project', touch(project));
|
||||
await tx.put('run', touch(run));
|
||||
return lease;
|
||||
});
|
||||
}
|
||||
|
||||
async renew(actor: Actor, id: string, leaseToken: number, fence: number) {
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, run, leaseToken);
|
||||
const project = await projectAccess(tx, actor, run.projectId);
|
||||
this.assertHeld(actor, run, project);
|
||||
const lock = project.integrationLease as IntegrationLease;
|
||||
if (lock.fence !== fence)
|
||||
throw new DomainError('STALE_INTEGRATION_FENCE', 'Project integration ownership changed');
|
||||
lock.expiresAt = expiry(run);
|
||||
await tx.put('project', touch(project));
|
||||
return lock;
|
||||
});
|
||||
}
|
||||
|
||||
async release(actor: Actor, id: string, leaseToken: number, fence: number) {
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionScope(actor, run);
|
||||
const project = await projectAccess(tx, actor, run.projectId);
|
||||
const lock = project.integrationLease as IntegrationLease | undefined;
|
||||
if (
|
||||
lock?.runId !== id ||
|
||||
lock.generation !== run.executionGeneration ||
|
||||
lock.verifierId !== actor.userId ||
|
||||
lock.leaseToken !== leaseToken ||
|
||||
lock.fence !== fence
|
||||
)
|
||||
return { released: false };
|
||||
delete project.integrationLease;
|
||||
await tx.put('project', touch(project));
|
||||
return { released: true };
|
||||
});
|
||||
}
|
||||
|
||||
/** Integration, build and build evidence require the live project lease of this exact execution. */
|
||||
async enforce(actor: Actor, id: string, leaseToken: number) {
|
||||
await this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, run, leaseToken);
|
||||
this.assertHeld(actor, run, await projectAccess(tx, actor, run.projectId));
|
||||
});
|
||||
}
|
||||
|
||||
private assertHeld(actor: Actor, run: Run, project: Project) {
|
||||
if (this.env.NODE_ENV !== 'production' && !run.executionGeneration) return;
|
||||
const lock = project.integrationLease as IntegrationLease | undefined;
|
||||
if (
|
||||
!lock ||
|
||||
lock.runId !== run.id ||
|
||||
lock.generation !== run.executionGeneration ||
|
||||
lock.verifierId !== actor.userId ||
|
||||
lock.leaseToken !== run.lease?.token ||
|
||||
lock.fence !== run.projectIntegrationFence ||
|
||||
Date.parse(lock.expiresAt) <= Date.now()
|
||||
)
|
||||
throw new DomainError('INTEGRATION_LEASE_REQUIRED', 'A live project integration lease is required');
|
||||
}
|
||||
}
|
||||
@ -1,443 +0,0 @@
|
||||
import { resolveGatewayTarget } from './gateway-target.js';
|
||||
import { DomainError, type Actor, type Entity, type Run } from '@wishforge/contracts';
|
||||
import type { Store } from '../db/store.js';
|
||||
import { executionLease, executionScope, must, projectAccess, touch } from './control-plane.js';
|
||||
import { digest, requireHuman, requireRole } from './policy.js';
|
||||
import { validateSnapshot, type WorkspaceSnapshot } from '../../../../packages/runtime/src/workspace-snapshot.js';
|
||||
|
||||
export interface WorkspaceInput extends WorkspaceSnapshot {
|
||||
workspaceId: string;
|
||||
workspaceVersion: number;
|
||||
sourceCommit: string;
|
||||
activityDigest: string;
|
||||
requirementRevision: number;
|
||||
importGeneration: unknown;
|
||||
importedBy: string;
|
||||
importedAt: string;
|
||||
}
|
||||
interface InputState {
|
||||
workspaceId: string;
|
||||
latestSnapshot: WorkspaceSnapshot | null;
|
||||
currentDiskDigest: string;
|
||||
activityDigest: string;
|
||||
dirty: boolean;
|
||||
activeClients: number;
|
||||
}
|
||||
interface MatchRecord {
|
||||
generation: unknown;
|
||||
leaseToken: number;
|
||||
inputDigest: string;
|
||||
targetCommit: string;
|
||||
matchedAt: string;
|
||||
}
|
||||
export interface IntegrationLease {
|
||||
runId: string;
|
||||
generation: unknown;
|
||||
verifierId: string;
|
||||
leaseToken: number;
|
||||
fence: number;
|
||||
expiresAt: string;
|
||||
}
|
||||
export class WorkspaceIntegration {
|
||||
constructor(
|
||||
private store: Store,
|
||||
private env = process.env,
|
||||
private fetcher: typeof fetch = fetch,
|
||||
) {}
|
||||
private async load(actor: Actor, id: string) {
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
await projectAccess(tx, actor, run.projectId);
|
||||
if (!['human', 'connector'].includes(actor.kind)) executionScope(actor, run);
|
||||
const workspaces = (await tx.list('workspace')).filter(
|
||||
w =>
|
||||
w.projectId === run.projectId &&
|
||||
w.status !== 'archived' &&
|
||||
(w.status === 'ready' || typeof w.upstreamUrl === 'string'),
|
||||
);
|
||||
return { run, workspaces, inputs: (run.workspaceInputs ?? []) as WorkspaceInput[] };
|
||||
});
|
||||
}
|
||||
private async gateway(tenantId: string) {
|
||||
const target = await resolveGatewayTarget(this.env, tenantId);
|
||||
if (!target)
|
||||
throw new DomainError(
|
||||
'WORKSPACE_GATE_UNAVAILABLE',
|
||||
'No authenticated workspace gateway is configured for this tenant',
|
||||
503,
|
||||
);
|
||||
return target;
|
||||
}
|
||||
private async state(run: Run, workspace: Entity): Promise<InputState> {
|
||||
if (workspace.status !== 'ready')
|
||||
throw new DomainError(
|
||||
'WORKSPACE_GATE_UNAVAILABLE',
|
||||
'Active workspace state is unavailable; integration is blocked',
|
||||
503,
|
||||
);
|
||||
const gateway = await this.gateway(run.tenantId);
|
||||
const response = await this.fetcher(new URL('/internal/integration-state', gateway.internalUrl), {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${gateway.token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
tenantId: run.tenantId,
|
||||
workspaceId: workspace.id,
|
||||
runId: run.id,
|
||||
generation: run.executionGeneration,
|
||||
revision: run.revision,
|
||||
}),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(15000),
|
||||
}).catch(() => {
|
||||
throw new DomainError(
|
||||
'WORKSPACE_GATE_UNAVAILABLE',
|
||||
'Workspace input service is unreachable; integration is blocked',
|
||||
503,
|
||||
);
|
||||
});
|
||||
if (!response.ok)
|
||||
throw new DomainError(
|
||||
'WORKSPACE_GATE_UNAVAILABLE',
|
||||
'Could not establish current workspace input state; integration is blocked',
|
||||
503,
|
||||
);
|
||||
const value = (await response.json().catch(() => {
|
||||
throw new DomainError(
|
||||
'WORKSPACE_GATE_UNAVAILABLE',
|
||||
'Workspace input service returned an unreadable receipt',
|
||||
503,
|
||||
);
|
||||
})) as InputState;
|
||||
if (
|
||||
!value ||
|
||||
value.workspaceId !== workspace.id ||
|
||||
typeof value.dirty !== 'boolean' ||
|
||||
!/^[a-f0-9]{64}$/.test(value.currentDiskDigest) ||
|
||||
!/^[a-f0-9]{64}$/.test(value.activityDigest)
|
||||
)
|
||||
throw new DomainError('WORKSPACE_GATE_UNAVAILABLE', 'Workspace returned an invalid input-state receipt', 503);
|
||||
return value;
|
||||
}
|
||||
async inspect(actor: Actor, id: string) {
|
||||
const loaded = await this.load(actor, id);
|
||||
return {
|
||||
required: loaded.workspaces.length > 0,
|
||||
requirementRevision: loaded.run.revision,
|
||||
generation: loaded.run.executionGeneration,
|
||||
workspaces: loaded.workspaces.map(w => ({ id: w.id, status: w.status })),
|
||||
snapshots: loaded.inputs.filter(
|
||||
input =>
|
||||
input.requirementRevision === loaded.run.revision && loaded.workspaces.some(w => w.id === input.workspaceId),
|
||||
),
|
||||
};
|
||||
}
|
||||
async importSnapshot(actor: Actor, id: string, workspaceId: string, sourceCommit: string, userAuthorization: string) {
|
||||
requireHuman(actor);
|
||||
requireRole(actor, ['owner', 'admin', 'developer']);
|
||||
if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(sourceCommit))
|
||||
throw new DomainError('INVALID_COMMIT', 'A full committed source SHA is required', 400);
|
||||
const before = await this.load(actor, id);
|
||||
const workspace = before.workspaces.find(w => w.id === workspaceId);
|
||||
if (!workspace || workspace.status !== 'ready')
|
||||
throw new DomainError('NOT_FOUND', 'Ready workspace not found', 404);
|
||||
const gateway = await this.gateway(actor.tenantId);
|
||||
const response = await this.fetcher(
|
||||
new URL(`/workspaces/${workspaceId}/_wishforge/integration/snapshot`, gateway.internalUrl),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { authorization: userAuthorization, 'content-type': 'application/json' },
|
||||
body: '{}',
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(45000),
|
||||
},
|
||||
);
|
||||
if (!response.ok)
|
||||
throw new DomainError(
|
||||
'WORKSPACE_SAVE_BARRIER_REQUIRED',
|
||||
'Every active editor must save and acknowledge before importing the workspace',
|
||||
409,
|
||||
);
|
||||
const state = (await response.json()) as InputState;
|
||||
if (
|
||||
state.workspaceId !== workspaceId ||
|
||||
state.dirty !== false ||
|
||||
!/^[a-f0-9]{64}$/.test(state.activityDigest) ||
|
||||
!state.latestSnapshot ||
|
||||
state.currentDiskDigest !== state.latestSnapshot.digest
|
||||
)
|
||||
throw new DomainError('WORKSPACE_INPUT_CHANGED', 'Workspace changed before its snapshot could be imported');
|
||||
const snapshot = state.latestSnapshot;
|
||||
validateSnapshot(snapshot);
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
await projectAccess(tx, actor, run.projectId);
|
||||
const current = await must(tx, 'workspace', workspaceId);
|
||||
if (
|
||||
run.revision !== before.run.revision ||
|
||||
run.projectId !== before.run.projectId ||
|
||||
current.version !== workspace.version
|
||||
)
|
||||
throw new DomainError('WORKSPACE_INPUT_CHANGED', 'Requirement or workspace changed while saving');
|
||||
const input: WorkspaceInput = {
|
||||
...snapshot,
|
||||
workspaceId,
|
||||
workspaceVersion: current.version,
|
||||
sourceCommit,
|
||||
activityDigest: state.activityDigest,
|
||||
requirementRevision: run.revision,
|
||||
importGeneration: run.executionGeneration,
|
||||
importedBy: actor.userId,
|
||||
importedAt: new Date().toISOString(),
|
||||
};
|
||||
run.workspaceInputs = [
|
||||
...((run.workspaceInputs ?? []) as WorkspaceInput[]).filter(item => item.workspaceId !== workspaceId),
|
||||
input,
|
||||
];
|
||||
delete run.workspaceInputMatch;
|
||||
await tx.put('run', touch(run));
|
||||
await tx.event(
|
||||
id,
|
||||
'workspace.snapshot-imported',
|
||||
'Saved workspace input imported; independent Git tree matching is still required',
|
||||
{ workspaceId, snapshotRevision: input.revision, snapshotDigest: input.digest, sourceCommit },
|
||||
);
|
||||
return {
|
||||
...input,
|
||||
trust: 'input-only',
|
||||
nextAction: 'Commit/push the saved tree to the integration target, then resume for independent matching',
|
||||
};
|
||||
});
|
||||
}
|
||||
private async fresh(actor: Actor, id: string) {
|
||||
const loaded = await this.load(actor, id);
|
||||
if (!loaded.workspaces.length) return loaded;
|
||||
for (const w of loaded.workspaces) {
|
||||
const input = loaded.inputs.find(i => i.workspaceId === w.id && i.requirementRevision === loaded.run.revision);
|
||||
if (!input)
|
||||
throw new DomainError(
|
||||
'WORKSPACE_SNAPSHOT_REQUIRED',
|
||||
'Import a fresh coordinated snapshot of each ready workspace before integration',
|
||||
);
|
||||
if (input.workspaceVersion !== w.version)
|
||||
throw new DomainError('WORKSPACE_INPUT_CHANGED', 'Workspace provisioning changed; import a new snapshot');
|
||||
const current = await this.state(loaded.run, w);
|
||||
if (
|
||||
current.dirty ||
|
||||
current.latestSnapshot?.id !== input.id ||
|
||||
current.latestSnapshot.revision !== input.revision ||
|
||||
current.currentDiskDigest !== input.digest ||
|
||||
current.activityDigest !== input.activityDigest
|
||||
)
|
||||
throw new DomainError(
|
||||
'WORKSPACE_INPUT_CHANGED',
|
||||
'Editor versions, membership, saved revision or source content changed; save, import and reverify',
|
||||
);
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
async recordMatch(
|
||||
actor: Actor,
|
||||
id: string,
|
||||
body: {
|
||||
leaseToken: number;
|
||||
targetCommit: string;
|
||||
snapshots: Array<{ workspaceId: string; sourceCommit: string; snapshotRevision: number; snapshotDigest: string }>;
|
||||
},
|
||||
) {
|
||||
if (actor.kind !== 'verifier') throw new DomainError('FORBIDDEN', 'Independent verifier identity required', 403);
|
||||
const scoped = await this.load(actor, id);
|
||||
executionLease(actor, scoped.run, body.leaseToken);
|
||||
const loaded = await this.fresh(actor, id);
|
||||
executionLease(actor, loaded.run, body.leaseToken);
|
||||
if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(body.targetCommit))
|
||||
throw new DomainError('INVALID_COMMIT', 'Full integration target SHA required', 400);
|
||||
const expected = loaded.inputs
|
||||
.filter(i => loaded.workspaces.some(w => w.id === i.workspaceId))
|
||||
.map(i => ({
|
||||
workspaceId: i.workspaceId,
|
||||
sourceCommit: i.sourceCommit,
|
||||
snapshotRevision: i.revision,
|
||||
snapshotDigest: i.digest,
|
||||
}))
|
||||
.sort((a, b) => a.workspaceId.localeCompare(b.workspaceId));
|
||||
if (digest(expected) !== digest([...body.snapshots].sort((a, b) => a.workspaceId.localeCompare(b.workspaceId))))
|
||||
throw new DomainError(
|
||||
'WORKSPACE_INPUT_CHANGED',
|
||||
'Verifier result does not bind the exact imported workspace inputs',
|
||||
);
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, run, body.leaseToken);
|
||||
this.assertProjectLease(actor, run, await projectAccess(tx, actor, run.projectId));
|
||||
if (run.revision !== loaded.run.revision || digest(run.workspaceInputs ?? []) !== digest(loaded.inputs))
|
||||
throw new DomainError('WORKSPACE_INPUT_CHANGED', 'Inputs changed while the verifier matched Git');
|
||||
run.workspaceInputMatch = {
|
||||
generation: run.executionGeneration,
|
||||
leaseToken: body.leaseToken,
|
||||
inputDigest: digest(loaded.inputs),
|
||||
targetCommit: body.targetCommit,
|
||||
matchedAt: new Date().toISOString(),
|
||||
} satisfies MatchRecord;
|
||||
await tx.put('run', touch(run));
|
||||
return { matched: true, inputDigest: digest(loaded.inputs) };
|
||||
});
|
||||
}
|
||||
async acquire(actor: Actor, id: string, leaseToken: number) {
|
||||
if (actor.kind !== 'verifier') throw new DomainError('FORBIDDEN', 'Independent verifier required', 403);
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, run, leaseToken);
|
||||
const project = await projectAccess(tx, actor, run.projectId);
|
||||
const previous = project.integrationLease as IntegrationLease | undefined;
|
||||
if (previous && Date.parse(previous.expiresAt) > Date.now()) {
|
||||
const owner = await tx.get<Run>('run', previous.runId);
|
||||
const live =
|
||||
owner &&
|
||||
owner.executionGeneration === previous.generation &&
|
||||
owner.lease?.token === previous.leaseToken &&
|
||||
Date.parse(owner.lease.expiresAt) > Date.now();
|
||||
if (
|
||||
live &&
|
||||
(previous.runId !== id ||
|
||||
previous.generation !== run.executionGeneration ||
|
||||
previous.leaseToken !== leaseToken ||
|
||||
previous.verifierId !== actor.userId)
|
||||
)
|
||||
throw new DomainError('INTEGRATION_BUSY', 'Another run owns the project integration queue');
|
||||
if (live) {
|
||||
previous.expiresAt = new Date(Math.min(Date.now() + 60000, Date.parse(run.lease!.expiresAt))).toISOString();
|
||||
await tx.put('project', touch(project));
|
||||
return previous;
|
||||
}
|
||||
}
|
||||
const fence = Number(project.integrationFence ?? 0) + 1;
|
||||
const lease: IntegrationLease = {
|
||||
runId: id,
|
||||
generation: run.executionGeneration,
|
||||
verifierId: actor.userId,
|
||||
leaseToken,
|
||||
fence,
|
||||
expiresAt: new Date(Math.min(Date.now() + 60000, Date.parse(run.lease!.expiresAt))).toISOString(),
|
||||
};
|
||||
project.integrationFence = fence;
|
||||
project.integrationLease = lease;
|
||||
run.projectIntegrationFence = fence;
|
||||
await tx.put('project', touch(project));
|
||||
await tx.put('run', touch(run));
|
||||
return lease;
|
||||
});
|
||||
}
|
||||
private assertProjectLease(actor: Actor, run: Run, project: Entity) {
|
||||
if (this.env.NODE_ENV !== 'production' && !run.executionGeneration) return;
|
||||
const lock = project.integrationLease as IntegrationLease | undefined;
|
||||
if (
|
||||
!lock ||
|
||||
lock.runId !== run.id ||
|
||||
lock.generation !== run.executionGeneration ||
|
||||
lock.verifierId !== actor.userId ||
|
||||
lock.leaseToken !== run.lease?.token ||
|
||||
lock.fence !== run.projectIntegrationFence ||
|
||||
Date.parse(lock.expiresAt) <= Date.now()
|
||||
)
|
||||
throw new DomainError(
|
||||
'INTEGRATION_LEASE_REQUIRED',
|
||||
'A live database-backed project integration lease is required',
|
||||
);
|
||||
}
|
||||
async renew(actor: Actor, id: string, leaseToken: number, fence: number) {
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, run, leaseToken);
|
||||
const project = await projectAccess(tx, actor, run.projectId);
|
||||
this.assertProjectLease(actor, run, project);
|
||||
const lock = project.integrationLease as IntegrationLease;
|
||||
if (!lock || lock.fence !== fence)
|
||||
throw new DomainError('STALE_INTEGRATION_FENCE', 'Project integration ownership changed');
|
||||
lock.expiresAt = new Date(Math.min(Date.now() + 60000, Date.parse(run.lease!.expiresAt))).toISOString();
|
||||
await tx.put('project', touch(project));
|
||||
return lock;
|
||||
});
|
||||
}
|
||||
async release(actor: Actor, id: string, leaseToken: number, fence: number) {
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionScope(actor, run);
|
||||
const project = await projectAccess(tx, actor, run.projectId);
|
||||
const lock = project.integrationLease as IntegrationLease | undefined;
|
||||
if (
|
||||
lock?.runId === id &&
|
||||
lock.generation === run.executionGeneration &&
|
||||
lock.verifierId === actor.userId &&
|
||||
lock.leaseToken === leaseToken &&
|
||||
lock.fence === fence
|
||||
) {
|
||||
delete project.integrationLease;
|
||||
await tx.put('project', touch(project));
|
||||
return { released: true };
|
||||
}
|
||||
return { released: false };
|
||||
});
|
||||
}
|
||||
async enforce(actor: Actor, id: string, leaseToken: number) {
|
||||
const before = await this.load(actor, id);
|
||||
executionLease(actor, before.run, leaseToken);
|
||||
try {
|
||||
await this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, run, leaseToken);
|
||||
this.assertProjectLease(actor, run, await projectAccess(tx, actor, run.projectId));
|
||||
});
|
||||
const loaded = await this.fresh(actor, id);
|
||||
await this.store.transaction(actor.tenantId, async tx => {
|
||||
const current = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, current, leaseToken);
|
||||
this.assertProjectLease(actor, current, await projectAccess(tx, actor, current.projectId));
|
||||
if (current.revision !== loaded.run.revision || digest(current.workspaceInputs ?? []) !== digest(loaded.inputs))
|
||||
throw new DomainError('WORKSPACE_INPUT_CHANGED', 'Workspace inputs changed during current-state checks');
|
||||
const active = (await tx.list('workspace')).filter(
|
||||
w =>
|
||||
w.projectId === current.projectId &&
|
||||
w.status !== 'archived' &&
|
||||
(w.status === 'ready' || typeof w.upstreamUrl === 'string'),
|
||||
);
|
||||
const versions = (list: Entity[]) =>
|
||||
list.map(w => ({ id: w.id, version: w.version })).sort((a, b) => a.id.localeCompare(b.id));
|
||||
if (digest(versions(active)) !== digest(versions(loaded.workspaces)))
|
||||
throw new DomainError(
|
||||
'WORKSPACE_INPUT_CHANGED',
|
||||
'Workspace membership or provisioning changed during current-state checks',
|
||||
);
|
||||
if (!active.length) return;
|
||||
const match = current.workspaceInputMatch as MatchRecord | undefined;
|
||||
if (
|
||||
!match ||
|
||||
match.generation !== current.executionGeneration ||
|
||||
match.leaseToken !== current.lease?.token ||
|
||||
match.inputDigest !== digest(loaded.inputs)
|
||||
)
|
||||
throw new DomainError(
|
||||
'WORKSPACE_GIT_MATCH_REQUIRED',
|
||||
'Independent verifier must match the imported snapshot to the committed integration input in this execution generation',
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof DomainError &&
|
||||
(error.code.startsWith('WORKSPACE_') || error.code.startsWith('INTEGRATION_'))
|
||||
)
|
||||
await this.store.transaction(actor.tenantId, async tx => {
|
||||
const run = await must<Run>(tx, 'run', id);
|
||||
executionLease(actor, run, leaseToken);
|
||||
if (['succeeded', 'failed', 'canceled', 'paused'].includes(run.status)) return;
|
||||
run.status = 'waiting';
|
||||
run.waitingReason = error.code.toLowerCase();
|
||||
if (run.lastActiveAt) run.activeMilliseconds += Math.max(0, Date.now() - Date.parse(run.lastActiveAt));
|
||||
run.lastActiveAt = undefined;
|
||||
if (run.lease) run.lease.expiresAt = new Date().toISOString();
|
||||
await tx.put('run', touch(run));
|
||||
await tx.event(id, 'run.waiting', error.message);
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -4,8 +4,8 @@ import { randomUUID } from 'node:crypto';
|
||||
import { DomainError, type Actor, type Entity } from '@wishforge/contracts';
|
||||
import type { OutboxItem, Store, Transaction } from '../db/store.js';
|
||||
import { idempotent, must, projectAccess, touch } from './control-plane.js';
|
||||
import { digest, requireHuman, requireRole } from './policy.js';
|
||||
import { validateSnapshot, type WorkspaceSnapshot } from '../../../../packages/runtime/src/workspace-snapshot.js';
|
||||
import { requireHuman, requireRole } from './policy.js';
|
||||
|
||||
export const WORKSPACE_IDLE_MS = 30 * 60_000;
|
||||
interface Lifecycle {
|
||||
revision: number;
|
||||
@ -14,20 +14,18 @@ interface Lifecycle {
|
||||
requestedAt: string;
|
||||
operationId: string;
|
||||
state: 'queued' | 'unknown' | 'observing' | 'complete';
|
||||
snapshotDigest?: string;
|
||||
}
|
||||
interface SleepState {
|
||||
interface GatewayActivity {
|
||||
workspaceId: string;
|
||||
gatewayConnections: number;
|
||||
known: boolean;
|
||||
activeClients: number;
|
||||
terminals: number;
|
||||
debugSessions: number;
|
||||
dirty: boolean;
|
||||
snapshotComplete: boolean;
|
||||
snapshotRevision: number;
|
||||
diskDigest: string;
|
||||
gatewayConnections: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause scales a provisioner-managed IDE workspace to zero; files persist on its
|
||||
* volume, unsaved editor buffers do not. Idle workspaces (no gateway connection
|
||||
* and no authorized activity for 30 minutes) are paused automatically.
|
||||
*/
|
||||
export class WorkspaceLifecycle {
|
||||
constructor(
|
||||
private store: Store,
|
||||
@ -48,113 +46,45 @@ export class WorkspaceLifecycle {
|
||||
private safe(w: Entity) {
|
||||
return { id: w.id, status: w.status, lifecycle: w.lifecycle, reason: w.reason, lastActivityAt: w.lastActivityAt };
|
||||
}
|
||||
private async configured(tenantId: string) {
|
||||
const [provisioner, gateway] = await Promise.all([
|
||||
resolveProvisionerTarget(this.env, tenantId),
|
||||
resolveGatewayTarget(this.env, tenantId),
|
||||
]);
|
||||
if (!provisioner || !gateway)
|
||||
private async provisioner(tenantId: string) {
|
||||
const provisioner = await resolveProvisionerTarget(this.env, tenantId);
|
||||
if (!provisioner)
|
||||
throw new DomainError(
|
||||
'WORKSPACE_LIFECYCLE_UNCONFIGURED',
|
||||
'Scoped workspace provisioner and gateway are required for this tenant',
|
||||
'A scoped workspace provisioner is required for this tenant',
|
||||
503,
|
||||
);
|
||||
return { provisioner, gateway };
|
||||
return provisioner;
|
||||
}
|
||||
async manual(actor: Actor, id: string, action: 'pause' | 'resume', key: string, authorization: string) {
|
||||
|
||||
async manual(actor: Actor, id: string, action: 'pause' | 'resume', key: string) {
|
||||
if (!key || key.length < 8 || key.length > 200)
|
||||
throw new DomainError('IDEMPOTENCY_REQUIRED', 'Provide an Idempotency-Key of 8–200 characters', 400);
|
||||
await this.provisioner(actor.tenantId);
|
||||
const request = { workspaceId: id, action };
|
||||
const before = await this.store.transaction(actor.tenantId, async tx => {
|
||||
const workspace = await this.access(tx, actor, id);
|
||||
const previous = await tx.idempotency(key);
|
||||
if (previous) {
|
||||
if (previous.digest !== digest(request))
|
||||
throw new DomainError('IDEMPOTENCY_CONFLICT', 'Key already identifies another workspace action');
|
||||
return { previous: previous.response, workspace };
|
||||
}
|
||||
return { workspace };
|
||||
});
|
||||
if ('previous' in before) return before.previous;
|
||||
const { gateway } = await this.configured(actor.tenantId);
|
||||
if (before.workspace.managedBy !== 'wishforge-provisioner')
|
||||
throw new DomainError(
|
||||
'WORKSPACE_LIFECYCLE_UNCONFIGURED',
|
||||
'This workspace does not have a managed lifecycle',
|
||||
503,
|
||||
);
|
||||
const desired = action === 'pause' ? 'paused' : 'running';
|
||||
if (before.workspace.status === (action === 'pause' ? 'paused' : 'ready'))
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const current = await this.access(tx, actor, id);
|
||||
return idempotent(tx, key, request, async () => {
|
||||
if (current.status !== before.workspace.status)
|
||||
throw new DomainError('WORKSPACE_OPERATION_CHANGED', 'Workspace changed before no-op confirmation');
|
||||
return this.safe(current);
|
||||
});
|
||||
});
|
||||
if (!['ready', 'paused', 'pausing', 'resuming', 'unknown'].includes(String(before.workspace.status)))
|
||||
throw new DomainError('WORKSPACE_NOT_READY', 'Workspace provisioning must be reconciled first');
|
||||
let snapshot: WorkspaceSnapshot | undefined;
|
||||
if (action === 'pause') {
|
||||
if (before.workspace.status !== 'ready')
|
||||
throw new DomainError('WORKSPACE_OPERATION_PENDING', 'Resolve the existing lifecycle operation before pausing');
|
||||
const response = await this.fetcher(
|
||||
new URL(`/workspaces/${id}/_wishforge/integration/snapshot`, gateway.internalUrl),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { authorization, 'content-type': 'application/json' },
|
||||
body: '{}',
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(45000),
|
||||
},
|
||||
).catch(() => {
|
||||
throw new DomainError(
|
||||
'WORKSPACE_SAVE_REQUIRED',
|
||||
'Could not confirm all editor saves; workspace remains running',
|
||||
);
|
||||
});
|
||||
if (!response.ok)
|
||||
throw new DomainError(
|
||||
'WORKSPACE_SAVE_REQUIRED',
|
||||
'Every active editor must acknowledge a saved snapshot before pausing',
|
||||
);
|
||||
const receipt = (await response.json()) as {
|
||||
workspaceId: string;
|
||||
dirty: boolean;
|
||||
latestSnapshot?: WorkspaceSnapshot;
|
||||
currentDiskDigest: string;
|
||||
};
|
||||
if (
|
||||
receipt.workspaceId !== id ||
|
||||
receipt.dirty !== false ||
|
||||
!receipt.latestSnapshot ||
|
||||
receipt.currentDiskDigest !== receipt.latestSnapshot.digest
|
||||
)
|
||||
throw new DomainError('WORKSPACE_SAVE_REQUIRED', 'Workspace changed while saving');
|
||||
validateSnapshot(receipt.latestSnapshot);
|
||||
snapshot = receipt.latestSnapshot;
|
||||
}
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const workspace = await this.access(tx, actor, id);
|
||||
return idempotent(tx, key, request, async () => {
|
||||
if (
|
||||
workspace.upstreamUrl !== before.workspace.upstreamUrl ||
|
||||
Number((workspace.lifecycle as Lifecycle | undefined)?.revision ?? 0) !==
|
||||
Number((before.workspace.lifecycle as Lifecycle | undefined)?.revision ?? 0)
|
||||
)
|
||||
throw new DomainError('WORKSPACE_OPERATION_CHANGED', 'Another lifecycle action took ownership');
|
||||
return this.queue(tx, workspace, desired, false, snapshot?.digest);
|
||||
if (workspace.managedBy !== 'wishforge-provisioner')
|
||||
throw new DomainError(
|
||||
'WORKSPACE_LIFECYCLE_UNCONFIGURED',
|
||||
'This workspace does not have a managed lifecycle',
|
||||
503,
|
||||
);
|
||||
if (workspace.status === (action === 'pause' ? 'paused' : 'ready')) return this.safe(workspace);
|
||||
if (action === 'pause' && workspace.status !== 'ready')
|
||||
throw new DomainError(
|
||||
'WORKSPACE_OPERATION_PENDING',
|
||||
'Resolve the existing lifecycle operation before pausing',
|
||||
);
|
||||
if (!['ready', 'paused', 'pausing', 'resuming', 'unknown'].includes(String(workspace.status)))
|
||||
throw new DomainError('WORKSPACE_NOT_READY', 'Workspace provisioning must be reconciled first');
|
||||
return this.queue(tx, workspace, action === 'pause' ? 'paused' : 'running', false);
|
||||
});
|
||||
});
|
||||
}
|
||||
private async queue(
|
||||
tx: Transaction,
|
||||
workspace: Entity,
|
||||
desired: Lifecycle['desired'],
|
||||
automatic: boolean,
|
||||
snapshotDigest?: string,
|
||||
) {
|
||||
|
||||
private async queue(tx: Transaction, workspace: Entity, desired: Lifecycle['desired'], automatic: boolean) {
|
||||
const revision = Number((workspace.lifecycle as Lifecycle | undefined)?.revision ?? 0) + 1;
|
||||
const operationId = randomUUID();
|
||||
workspace.lifecycle = {
|
||||
@ -164,10 +94,9 @@ export class WorkspaceLifecycle {
|
||||
requestedAt: new Date().toISOString(),
|
||||
operationId,
|
||||
state: 'queued',
|
||||
snapshotDigest,
|
||||
} satisfies Lifecycle;
|
||||
workspace.status = desired === 'paused' ? 'pausing' : 'resuming';
|
||||
workspace.reason = 'Waiting for the isolated workspace controller to confirm the requested state.';
|
||||
workspace.reason = 'Waiting for the workspace controller to confirm the requested state.';
|
||||
await tx.put('workspace', touch(workspace));
|
||||
await tx.enqueue(
|
||||
'workspace.reconcile',
|
||||
@ -176,44 +105,26 @@ export class WorkspaceLifecycle {
|
||||
);
|
||||
return this.safe(workspace);
|
||||
}
|
||||
private async safety(workspace: Entity): Promise<SleepState> {
|
||||
|
||||
/** Idle only when the gateway positively reports no open connection to the workspace. */
|
||||
private async idle(workspace: Entity): Promise<boolean> {
|
||||
const gateway = await resolveGatewayTarget(this.env, workspace.tenantId);
|
||||
if (!gateway) throw new DomainError('WORKSPACE_ACTIVITY_UNKNOWN', 'Tenant gateway is unavailable');
|
||||
if (!gateway) return false;
|
||||
const response = await this.fetcher(new URL('/internal/lifecycle-state', gateway.internalUrl), {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${gateway.token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ tenantId: workspace.tenantId, workspaceId: workspace.id }),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!response.ok) throw new DomainError('WORKSPACE_ACTIVITY_UNKNOWN', 'Workspace activity cannot be established');
|
||||
const value = (await response.json()) as SleepState;
|
||||
if (
|
||||
value.workspaceId !== workspace.id ||
|
||||
value.known !== true ||
|
||||
value.gatewayConnections !== 0 ||
|
||||
value.activeClients !== 0 ||
|
||||
value.terminals !== 0 ||
|
||||
value.debugSessions !== 0 ||
|
||||
value.dirty !== false ||
|
||||
value.snapshotComplete !== true ||
|
||||
!Number.isSafeInteger(value.snapshotRevision) ||
|
||||
value.snapshotRevision < 1 ||
|
||||
!/^[a-f0-9]{64}$/.test(value.diskDigest)
|
||||
)
|
||||
throw new DomainError(
|
||||
'WORKSPACE_NOT_IDLE',
|
||||
'Workspace has active or unknown work, or lacks a complete saved snapshot',
|
||||
);
|
||||
return value;
|
||||
}).catch(() => undefined);
|
||||
if (!response?.ok) return false;
|
||||
const value = (await response.json().catch(() => undefined)) as GatewayActivity | undefined;
|
||||
return value?.workspaceId === workspace.id && value.known === true && value.gatewayConnections === 0;
|
||||
}
|
||||
|
||||
async scheduleIdle(tenantId: string) {
|
||||
if (this.env.WF_WORKSPACE_AUTO_SLEEP === 'false') return;
|
||||
try {
|
||||
await this.configured(tenantId);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!(await resolveProvisionerTarget(this.env, tenantId).catch(() => undefined))) return;
|
||||
const cutoff = Date.now() - WORKSPACE_IDLE_MS;
|
||||
const candidates = await this.store.transaction(tenantId, async tx =>
|
||||
(await tx.list('workspace')).filter(
|
||||
@ -225,23 +136,15 @@ export class WorkspaceLifecycle {
|
||||
),
|
||||
);
|
||||
for (const before of candidates) {
|
||||
try {
|
||||
const receipt = await this.safety(before);
|
||||
await this.store.transaction(tenantId, async tx => {
|
||||
const w = await must(tx, 'workspace', before.id);
|
||||
if (
|
||||
w.status !== 'ready' ||
|
||||
w.lastActivityAt !== before.lastActivityAt ||
|
||||
Date.parse(String(w.lastActivityAt)) > cutoff
|
||||
)
|
||||
return;
|
||||
await this.queue(tx, w, 'paused', true, receipt.diskDigest);
|
||||
});
|
||||
} catch {
|
||||
/* Unknown or active work is never automatically stopped. */
|
||||
}
|
||||
if (!(await this.idle(before))) continue;
|
||||
await this.store.transaction(tenantId, async tx => {
|
||||
const w = await must(tx, 'workspace', before.id);
|
||||
if (w.status !== 'ready' || w.lastActivityAt !== before.lastActivityAt) return;
|
||||
await this.queue(tx, w, 'paused', true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async reconcile(tenantId: string, item: OutboxItem) {
|
||||
const workspace = await this.store.transaction(tenantId, tx =>
|
||||
must(tx, 'workspace', String(item.payload.workspaceId)),
|
||||
@ -252,7 +155,8 @@ export class WorkspaceLifecycle {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { provisioner } = await this.configured(tenantId);
|
||||
const provisioner = await this.provisioner(tenantId);
|
||||
// Give a user who reconnects right after an automatic decision a chance to keep the workspace.
|
||||
if (operation.automatic && Date.now() - Date.parse(operation.requestedAt) < 5000) {
|
||||
await this.store.transaction(tenantId, tx => tx.defer(item.id, 5));
|
||||
return;
|
||||
@ -272,23 +176,14 @@ export class WorkspaceLifecycle {
|
||||
['running', 'paused'].includes(state.desired) &&
|
||||
['ready', 'paused', 'pending'].includes(state.status);
|
||||
if (!valid() || state.revision > operation.revision) throw new Error('WORKSPACE_OBSERVE_UNKNOWN');
|
||||
if (state.revision < operation.revision && operation.automatic) {
|
||||
try {
|
||||
const receipt = await this.safety(workspace);
|
||||
if (
|
||||
receipt.diskDigest !== operation.snapshotDigest ||
|
||||
Date.now() - Date.parse(String(workspace.lastActivityAt)) < WORKSPACE_IDLE_MS
|
||||
)
|
||||
throw new Error('ACTIVITY_CHANGED');
|
||||
} catch {
|
||||
await this.store.transaction(tenantId, async tx => {
|
||||
const current = await must(tx, 'workspace', workspace.id);
|
||||
if ((current.lifecycle as Lifecycle | undefined)?.operationId !== item.id) return;
|
||||
await this.queue(tx, current, 'running', false);
|
||||
await tx.acknowledge(item.id);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (state.revision < operation.revision && operation.automatic && !(await this.idle(workspace))) {
|
||||
await this.store.transaction(tenantId, async tx => {
|
||||
const current = await must(tx, 'workspace', workspace.id);
|
||||
if ((current.lifecycle as Lifecycle | undefined)?.operationId !== item.id) return;
|
||||
await this.queue(tx, current, 'running', false);
|
||||
await tx.acknowledge(item.id);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (state.revision < operation.revision) {
|
||||
await this.store.transaction(tenantId, async tx => {
|
||||
@ -333,7 +228,8 @@ export class WorkspaceLifecycle {
|
||||
if (complete) await tx.acknowledge(item.id);
|
||||
else await tx.defer(item.id, 10);
|
||||
});
|
||||
} catch {
|
||||
} catch (error) {
|
||||
console.error(`Workspace ${workspace.id} lifecycle reconcile: ${error instanceof Error ? error.message : error}`);
|
||||
await this.store.transaction(tenantId, async tx => {
|
||||
const current = await must(tx, 'workspace', workspace.id);
|
||||
if ((current.lifecycle as Lifecycle | undefined)?.operationId !== item.id) return;
|
||||
|
||||
@ -51,6 +51,8 @@ export class Services {
|
||||
type AuthRequest = Request & { actor: Actor };
|
||||
const ok = <T>(data: T) => ({ data });
|
||||
const key = (req: Request) => req.header('Idempotency-Key');
|
||||
const leaseBody = z.object({ leaseToken: z.number().int().positive() }).strict();
|
||||
const fencedBody = z.object({ leaseToken: z.number().int().positive(), fence: z.number().int().positive() }).strict();
|
||||
|
||||
@Catch()
|
||||
export class Errors implements ExceptionFilter {
|
||||
@ -550,6 +552,30 @@ export class InternalController {
|
||||
) {
|
||||
return ok(await this.s.control.meter(r.actor, id, b));
|
||||
}
|
||||
@Post('runs/:id/integration-lease/acquire') async acquireIntegration(
|
||||
@Req() r: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() b: unknown,
|
||||
) {
|
||||
const { leaseToken } = leaseBody.parse(b);
|
||||
return ok(await this.s.control.integration.acquire(r.actor, id, leaseToken));
|
||||
}
|
||||
@Post('runs/:id/integration-lease/renew') async renewIntegration(
|
||||
@Req() r: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() b: unknown,
|
||||
) {
|
||||
const { leaseToken, fence } = fencedBody.parse(b);
|
||||
return ok(await this.s.control.integration.renew(r.actor, id, leaseToken, fence));
|
||||
}
|
||||
@Post('runs/:id/integration-lease/release') async releaseIntegration(
|
||||
@Req() r: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() b: unknown,
|
||||
) {
|
||||
const { leaseToken, fence } = fencedBody.parse(b);
|
||||
return ok(await this.s.control.integration.release(r.actor, id, leaseToken, fence));
|
||||
}
|
||||
@Post('evidence') async evidence(@Req() r: AuthRequest, @Body() b: unknown) {
|
||||
return ok(await this.s.control.evidence(r.actor, b));
|
||||
}
|
||||
|
||||
@ -13,9 +13,8 @@ import { auditContext } from './audit-context.js';
|
||||
import { observability } from './telemetry.js';
|
||||
import { ProviderProxy } from './domain/provider-proxy.js';
|
||||
import { once } from 'node:events';
|
||||
import { WorkspaceLifecycleController, WorkspaceLifecycleInternalController } from './workspace-lifecycle-http.js';
|
||||
import { WorkspaceLifecycleController } from './workspace-lifecycle-http.js';
|
||||
import { WorkspaceLifecycleWorker } from './workspace-lifecycle-worker.js';
|
||||
import { WorkspaceInputController, WorkspaceIntegrationController } from './workspace-integration-http.js';
|
||||
import { ResourceReconciliationWorker } from './resource-reconciliation-worker.js';
|
||||
|
||||
export async function bootstrap() {
|
||||
@ -28,15 +27,7 @@ export async function bootstrap() {
|
||||
const service = new Services(new ControlPlane(store));
|
||||
const telemetry = await observability();
|
||||
@Module({
|
||||
controllers: [
|
||||
ApiController,
|
||||
InternalController,
|
||||
WorkspaceInputController,
|
||||
WorkspaceIntegrationController,
|
||||
WorkspaceLifecycleController,
|
||||
WorkspaceLifecycleInternalController,
|
||||
WorkspaceLaunchController,
|
||||
],
|
||||
controllers: [ApiController, InternalController, WorkspaceLifecycleController, WorkspaceLaunchController],
|
||||
providers: [{ provide: Services, useValue: service }],
|
||||
})
|
||||
class AppModule {}
|
||||
@ -131,10 +122,7 @@ export async function bootstrap() {
|
||||
if (addressed !== actor.runId)
|
||||
throw new DomainError('FORBIDDEN', 'Execution token is scoped to a single run', 403);
|
||||
}
|
||||
if (
|
||||
actor.userId === 'workspace-gateway' &&
|
||||
!/^\/workspaces\/[^/]+\/(authorize|integration-authorize|lifecycle-authorize)$/.test(req.path)
|
||||
)
|
||||
if (actor.userId === 'workspace-gateway' && !/^\/workspaces\/[^/]+\/authorize$/.test(req.path))
|
||||
throw new DomainError('FORBIDDEN', 'Gateway identity is limited to workspace authorization', 403);
|
||||
if (actor.userId.startsWith('runner:') && !req.path.startsWith('/runner/'))
|
||||
throw new DomainError('FORBIDDEN', 'Runner identity is limited to assigned deployment tasks', 403);
|
||||
|
||||
@ -1,141 +0,0 @@
|
||||
import { Body, Controller, Get, Inject, Param, Post, Req } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { DomainError, type Actor, type Run } from '@wishforge/contracts';
|
||||
import { Services } from './http.js';
|
||||
import { must } from './domain/control-plane.js';
|
||||
type AuthRequest = Request & { actor: Actor };
|
||||
const lease = z.object({ leaseToken: z.number().int().positive() }).strict();
|
||||
const fenced = z.object({ leaseToken: z.number().int().positive(), fence: z.number().int().positive() }).strict();
|
||||
@Controller('v1')
|
||||
export class WorkspaceInputController {
|
||||
constructor(@Inject(Services) private s: Services) {}
|
||||
@Get('runs/:id/workspace-input') async inspect(@Req() req: AuthRequest, @Param('id') id: string) {
|
||||
return { data: await this.s.control.workspaceIntegration.inspect(req.actor, id) };
|
||||
}
|
||||
@Post('runs/:id/workspaces/:workspaceId/import-snapshot') async import(
|
||||
@Req() req: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Param('workspaceId') workspaceId: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
const input = z
|
||||
.object({
|
||||
sourceCommit: z.string().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/),
|
||||
confirmation: z.literal('saved-workspace-committed'),
|
||||
})
|
||||
.strict()
|
||||
.parse(body);
|
||||
return {
|
||||
data: await this.s.control.workspaceIntegration.importSnapshot(
|
||||
req.actor,
|
||||
id,
|
||||
workspaceId,
|
||||
input.sourceCommit,
|
||||
req.header('Authorization') ?? '',
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
@Controller('internal')
|
||||
export class WorkspaceIntegrationController {
|
||||
constructor(@Inject(Services) private s: Services) {}
|
||||
@Get('runs/:id/workspace-input') async inspect(@Req() req: AuthRequest, @Param('id') id: string) {
|
||||
return { data: await this.s.control.workspaceIntegration.inspect(req.actor, id) };
|
||||
}
|
||||
@Post('runs/:id/workspace-input/match') async match(
|
||||
@Req() req: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
const input = z
|
||||
.object({
|
||||
leaseToken: z.number().int().positive(),
|
||||
targetCommit: z.string(),
|
||||
snapshots: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
workspaceId: z.string(),
|
||||
sourceCommit: z.string(),
|
||||
snapshotRevision: z.number().int().positive(),
|
||||
snapshotDigest: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
})
|
||||
.strict(),
|
||||
)
|
||||
.max(20),
|
||||
})
|
||||
.strict()
|
||||
.parse(body);
|
||||
return { data: await this.s.control.workspaceIntegration.recordMatch(req.actor, id, input) };
|
||||
}
|
||||
@Post('runs/:id/workspace-input/check') async check(
|
||||
@Req() req: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
await this.s.control.workspaceIntegration.enforce(req.actor, id, lease.parse(body).leaseToken);
|
||||
return { data: { allowed: true } };
|
||||
}
|
||||
@Post('runs/:id/integration-lease/acquire') async acquire(
|
||||
@Req() req: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
return { data: await this.s.control.workspaceIntegration.acquire(req.actor, id, lease.parse(body).leaseToken) };
|
||||
}
|
||||
@Post('runs/:id/integration-lease/renew') async renew(
|
||||
@Req() req: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
const data = fenced.parse(body);
|
||||
return { data: await this.s.control.workspaceIntegration.renew(req.actor, id, data.leaseToken, data.fence) };
|
||||
}
|
||||
@Post('runs/:id/integration-lease/release') async release(
|
||||
@Req() req: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
const data = fenced.parse(body);
|
||||
return { data: await this.s.control.workspaceIntegration.release(req.actor, id, data.leaseToken, data.fence) };
|
||||
}
|
||||
@Post('workspaces/:id/integration-authorize') async authorize(
|
||||
@Req() req: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
if (req.actor.userId !== 'workspace-gateway')
|
||||
throw new DomainError('FORBIDDEN', 'Workspace gateway identity required', 403);
|
||||
const input = z
|
||||
.object({ runId: z.string(), revision: z.number().int().positive(), generation: z.string().optional() })
|
||||
.strict()
|
||||
.parse(body);
|
||||
return {
|
||||
data: await this.s.control.store.transaction(req.actor.tenantId, async tx => {
|
||||
const workspace = await must(tx, 'workspace', id),
|
||||
run = await must<Run>(tx, 'run', input.runId);
|
||||
if (
|
||||
workspace.projectId !== run.projectId ||
|
||||
workspace.status !== 'ready' ||
|
||||
!workspace.upstreamUrl ||
|
||||
run.revision !== input.revision ||
|
||||
run.executionGeneration !== input.generation ||
|
||||
run.status !== 'running' ||
|
||||
!run.lease ||
|
||||
Date.parse(run.lease.expiresAt) <= Date.now()
|
||||
)
|
||||
throw new DomainError('WORKSPACE_INPUT_UNAVAILABLE', 'Workspace is not a live integration input', 409);
|
||||
return {
|
||||
tenantId: req.actor.tenantId,
|
||||
workspaceId: id,
|
||||
projectId: run.projectId,
|
||||
upstreamUrl: workspace.upstreamUrl,
|
||||
userId: `integration:${run.id}`,
|
||||
role: 'admin',
|
||||
purpose: 'integration-state',
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -1,9 +1,8 @@
|
||||
import { Body, Controller, Inject, Param, Post, Req } from '@nestjs/common';
|
||||
import { z } from 'zod';
|
||||
import type { Request } from 'express';
|
||||
import { DomainError, type Actor } from '@wishforge/contracts';
|
||||
import type { Actor } from '@wishforge/contracts';
|
||||
import { Services } from './http.js';
|
||||
import { must } from './domain/control-plane.js';
|
||||
import { WorkspaceLifecycle } from './domain/workspace-lifecycle.js';
|
||||
type AuthRequest = Request & { actor: Actor };
|
||||
@Controller('v1/workspaces')
|
||||
@ -20,36 +19,7 @@ export class WorkspaceLifecycleController {
|
||||
id,
|
||||
input.action,
|
||||
req.header('Idempotency-Key') ?? '',
|
||||
req.header('Authorization') ?? '',
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
@Controller('internal/workspaces')
|
||||
export class WorkspaceLifecycleInternalController {
|
||||
constructor(@Inject(Services) private s: Services) {}
|
||||
@Post(':id/lifecycle-authorize') async authorize(@Req() req: AuthRequest, @Param('id') id: string) {
|
||||
if (req.actor.userId !== 'workspace-gateway')
|
||||
throw new DomainError('FORBIDDEN', 'Workspace gateway identity required', 403);
|
||||
return {
|
||||
data: await this.s.control.store.transaction(req.actor.tenantId, async tx => {
|
||||
const w = await must(tx, 'workspace', id);
|
||||
if (
|
||||
!['ready', 'pausing', 'unknown'].includes(String(w.status)) ||
|
||||
!w.upstreamUrl ||
|
||||
w.managedBy !== 'wishforge-provisioner'
|
||||
)
|
||||
throw new DomainError('WORKSPACE_NOT_READY', 'Workspace activity cannot be established', 503);
|
||||
return {
|
||||
tenantId: req.actor.tenantId,
|
||||
workspaceId: id,
|
||||
projectId: w.projectId,
|
||||
upstreamUrl: w.upstreamUrl,
|
||||
userId: 'lifecycle-inspector',
|
||||
role: 'admin',
|
||||
purpose: 'workspace-lifecycle',
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,11 +5,8 @@ ENV PUPPETEER_SKIP_DOWNLOAD=true
|
||||
COPY package.json package-lock.json ./
|
||||
COPY policy ./policy
|
||||
COPY collaboration ./collaboration
|
||||
COPY coordination ./coordination
|
||||
COPY security ./security
|
||||
RUN npm ci --no-audit --no-fund
|
||||
COPY scripts ./scripts
|
||||
COPY product.json ./product.json
|
||||
RUN npm run plugins:download && npm run build:production && mkdir /workspace && chown -R node:node /workspace && chmod -R go-w /opt/wishforge-ide
|
||||
USER node
|
||||
ENV NODE_ENV=production WISHFORGE_IDE_HOST=0.0.0.0 WISHFORGE_IDE_PORT=4300 WISHFORGE_WORKSPACE_PATH=/workspace
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
# Workspace coordination engine
|
||||
|
||||
`require('./index.cjs')` exports `Coordinator` and `CoordinationError`. It uses only Node built-ins. Run `node --test apps/ide/coordination/test/*.test.cjs` from the repository root.
|
||||
|
||||
Create one coordinator per workspace backend with `new Coordinator({ workspaceRoot, stateDirectory, now?, limits? })`. Both paths and optional limits come from trusted provisioning configuration. The state directory must be outside the source tree, on the same local filesystem throughout the backend's lifetime, and should be inaccessible to workspace writers in a hardened deployment. The current Theia integration runs backend and terminal under the same UID, so that privilege separation is **not** provided by a separate directory or PVC. Its own and its object/manifest directory modes are `0700`, which does not exclude same-UID terminal processes. The engine never writes source files or overwrites editor drafts.
|
||||
|
||||
The caller must authenticate each RPC/HTTP request and supply `actorId` from its trusted session. These methods do not authenticate an arbitrary actor string. Only authorized workspace participants should receive state or call methods. `revoke(actorId)` removes the actor's registered clients, invalidates affected pending barriers, and destroys its debug lease; gateway ACL enforcement must also reject subsequent calls and close revoked connections.
|
||||
|
||||
## Save barrier API
|
||||
|
||||
- `register(actorId, clientId, { documents: [{ uri, version, dirty }], dirty? })` registers/heartbeats a tab. Heartbeats expire after 30 seconds. A client ID cannot change actor. File URIs must be inside the workspace; relative paths are normalized. Other editor URI schemes are opaque document IDs and are never read as filesystem paths. All dirty editors, including unsaved untitled buffers, must be reported.
|
||||
- `unregister(actorId, clientId)` removes only the caller's tab and invalidates barriers containing that tab, preserving the actor's other tabs. Invoke it on connection close.
|
||||
- `beginBarrier(actorId)` requires an active client of the creator and freezes active clients, their document version vectors, and a digest of disk content. Returns `{ id, actorId, status, expiresAt, diskDigest, participants }`. Only one pending barrier is allowed, with a 30-second deadline.
|
||||
- `acknowledge(actorId, barrierId, clientId, payload)` accepts only that client's authenticated actor. The caller invokes the editor's `saveAll`, reports its full clean vector via `register`, then acknowledges with the same vector. All participants must acknowledge; no coordinator or other actor can acknowledge on their behalf.
|
||||
- `await commitBarrier(actorId, barrierId)` is restricted to the creator. It rejects unacknowledged, expired, dirty, changed-version or revoked participants. New clients or edits invalidate a pending barrier. Disk changes since barrier creation also invalidate it, so if saving changed disk the caller starts a fresh barrier after all saves complete. Retrying a committed barrier returns the same snapshot and revision, including after restart. Every client must register again before participating in new barriers after backend restart.
|
||||
|
||||
Commit returns `{ schemaVersion: 1, id, revision, previousId, workspace, digest, files: [{ path, sha256, size, mode }], createdAt, actorId, barrierId }`. It snapshots regular files under the configured root, rejects symlinks and special files, and excludes generated/runtime directory names `.git`, `node_modules`, `dist`, `build`, `coverage`, `.next`, `.cache`, `src-gen`, `.wishforge`, `.wishforge-runtime`, `.runtime`, `.coordination`. These names are excluded at any depth. New project-specific generated paths require explicit policy updates, not a client-supplied arbitrary path list.
|
||||
|
||||
Resource caps default to `limits: { maxFileBytes: 33554432, maxTotalBytes: 268435456, maxFiles: 20000 }` (32 MiB per file, 256 MiB total and 20,000 files). Overrides must be positive safe integers and cannot come from editor RPC input. Scans reject over-limit source with `SNAPSHOT_LIMIT` before opening the offending file, recheck the open descriptor's size, and read only the validated bounded length so concurrent growth cannot cause an unbounded allocation. Total bytes count every included path, including duplicate content; empty files count toward `maxFiles`. Excluded runtime paths consume no quota. Begin and final verification scans do not retain content blobs. Immediately after the final scan, commit rechecks barrier expiry and all participant heartbeats, acknowledgement, clean state and version vectors; elapsed scanning time does not extend the 30-second deadlines.
|
||||
|
||||
Each manifest refers to SHA-256-addressed blobs in `objects/`. Manifests and blobs are created without replacement and made read-only; the journal head is atomically replaced and fsynced. Recovery verifies the manifest chain and referenced content and reconstructs the head if a crash occurred after the immutable manifest commit but before the journal update. Partial temporary files and unreferenced blobs are not committed snapshots. Corruption fails closed. This is a local filesystem integrity proof, not production immutable storage, an OS-level filesystem freeze, or a guarantee against a privileged process rewriting state. External filesystem writers must also be gated by the caller; the engine detects changes with two full content scans but cannot lock arbitrary external writers.
|
||||
|
||||
## Debug controller API
|
||||
|
||||
- `debugAcquire(actorId)` returns `{ actorId, token, expiresAt }`; only one live lease exists and its token has 256 bits of randomness.
|
||||
- `debugAcquire(actorId, token)` renews the current lease for 30 seconds. A same-actor caller without the token cannot silently take over another tab.
|
||||
- `assertDebugController(actorId, token)` must guard every mutating debug request, not just the UI buttons. It validates owner, token and expiry.
|
||||
- `debugTransfer(actorId, token, targetActorId)` requires an active registered target and rotates the token. The trusted backend must deliver the new token only to the target actor's connection.
|
||||
- `debugRelease(actorId, token)` releases ownership. `state()` exposes controller owner/deadline, never the token.
|
||||
|
||||
Client membership, barriers and debug leases are intentionally ephemeral. A restarted backend requires fresh registration and debug acquisition, so old tokens or acknowledgements cannot authorize new actions. Durable state is the verified snapshot revision chain and exact saved contents. Only one active backend should own a workspace; the local writer lock guards commit/recovery operations, not distributed live membership. The backend integration is responsible for periodic heartbeats, save requests to all participants, and sending updated state.
|
||||
|
||||
The current backend integration is a cooperative-client control, not an adversarial terminal sandbox. A same-UID terminal can tamper with writable state or replace the backend; a hardened deployment needs a separately privileged coordination service reached directly through the gateway and independently controlled debugger processes. Workspace snapshots are not independent release evidence.
|
||||
@ -1,669 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createHash, randomBytes } = require('node:crypto');
|
||||
const { fileURLToPath } = require('node:url');
|
||||
|
||||
const EXCLUDED = new Set([
|
||||
'.git',
|
||||
'node_modules',
|
||||
'dist',
|
||||
'build',
|
||||
'coverage',
|
||||
'.next',
|
||||
'.cache',
|
||||
'src-gen',
|
||||
'.wishforge',
|
||||
'.wishforge-runtime',
|
||||
'.runtime',
|
||||
'.coordination',
|
||||
]);
|
||||
const CLIENT_TTL_MS = 30_000;
|
||||
const BARRIER_TTL_MS = 30_000;
|
||||
const DEBUG_LEASE_MS = 30_000;
|
||||
const DEFAULT_SNAPSHOT_LIMITS = Object.freeze({
|
||||
maxFileBytes: 32 * 1024 * 1024,
|
||||
maxTotalBytes: 256 * 1024 * 1024,
|
||||
maxFiles: 20_000,
|
||||
});
|
||||
|
||||
class CoordinationError extends Error {
|
||||
constructor(code, message) {
|
||||
super(message);
|
||||
this.name = 'CoordinationError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
function fail(code, message) {
|
||||
throw new CoordinationError(code, message);
|
||||
}
|
||||
function sha(value) {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
function clone(value) {
|
||||
return JSON.parse(JSON.stringify(value));
|
||||
}
|
||||
function inside(root, target) {
|
||||
return target === root || target.startsWith(root + path.sep);
|
||||
}
|
||||
function identifier(value, name) {
|
||||
if (typeof value !== 'string' || value.length < 1 || value.length > 256 || /[\u0000-\u001f]/.test(value))
|
||||
fail('INVALID_INPUT', `Invalid ${name}`);
|
||||
return value;
|
||||
}
|
||||
function directorySync(directory) {
|
||||
const fd = fs.openSync(directory, fs.constants.O_RDONLY);
|
||||
try {
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
function atomicFile(destination, value, immutable = false) {
|
||||
const temporary = destination + '.' + randomBytes(16).toString('hex') + '.tmp';
|
||||
const fd = fs.openSync(temporary, 'wx', 0o600);
|
||||
try {
|
||||
fs.writeFileSync(fd, value);
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
try {
|
||||
if (immutable) {
|
||||
fs.chmodSync(temporary, 0o400);
|
||||
fs.linkSync(temporary, destination); // Unlike rename, this must never replace a committed object.
|
||||
fs.unlinkSync(temporary);
|
||||
} else fs.renameSync(temporary, destination);
|
||||
directorySync(path.dirname(destination));
|
||||
} finally {
|
||||
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
||||
}
|
||||
}
|
||||
function ensurePrivateDirectory(directory) {
|
||||
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
||||
if (fs.lstatSync(directory).isSymbolicLink() || !fs.statSync(directory).isDirectory())
|
||||
fail('UNSAFE_STATE_PATH', 'State path must be a real directory');
|
||||
fs.chmodSync(directory, 0o700);
|
||||
}
|
||||
function prospectiveRealPath(directory) {
|
||||
let existing = directory;
|
||||
const missing = [];
|
||||
while (!fs.existsSync(existing)) {
|
||||
const parent = path.dirname(existing);
|
||||
if (parent === existing) fail('UNSAFE_STATE_PATH', 'State directory has no existing ancestor');
|
||||
missing.unshift(path.basename(existing));
|
||||
existing = parent;
|
||||
}
|
||||
return path.join(fs.realpathSync(existing), ...missing);
|
||||
}
|
||||
|
||||
class Coordinator {
|
||||
constructor({ workspaceRoot, stateDirectory, now = Date.now, limits = {} }) {
|
||||
if (typeof workspaceRoot !== 'string' || typeof stateDirectory !== 'string' || typeof now !== 'function')
|
||||
fail('INVALID_INPUT', 'Workspace, state directory and clock are required');
|
||||
if (
|
||||
!limits ||
|
||||
typeof limits !== 'object' ||
|
||||
Array.isArray(limits) ||
|
||||
Object.keys(limits).some(key => !Object.hasOwn(DEFAULT_SNAPSHOT_LIMITS, key))
|
||||
)
|
||||
fail('INVALID_INPUT', 'Invalid snapshot limits');
|
||||
this.limits = Object.freeze({ ...DEFAULT_SNAPSHOT_LIMITS, ...limits });
|
||||
for (const [key, value] of Object.entries(this.limits))
|
||||
if (!Number.isSafeInteger(value) || value <= 0) fail('INVALID_INPUT', `${key} must be a positive safe integer`);
|
||||
this.requestedWorkspaceRoot = path.resolve(workspaceRoot);
|
||||
this.workspaceRoot = fs.realpathSync(workspaceRoot);
|
||||
if (!fs.statSync(this.workspaceRoot).isDirectory()) fail('INVALID_INPUT', 'Workspace root must be a directory');
|
||||
const requested = path.resolve(stateDirectory);
|
||||
if (inside(this.workspaceRoot, requested) || inside(requested, this.workspaceRoot))
|
||||
fail('UNSAFE_STATE_PATH', 'State directory must be separate from the source workspace');
|
||||
if (fs.existsSync(requested) && fs.lstatSync(requested).isSymbolicLink())
|
||||
fail('UNSAFE_STATE_PATH', 'State directory must not be a symlink');
|
||||
this.stateDirectory = prospectiveRealPath(requested);
|
||||
if (inside(this.workspaceRoot, this.stateDirectory) || inside(this.stateDirectory, this.workspaceRoot))
|
||||
fail('UNSAFE_STATE_PATH', 'State directory must be separate from the source workspace');
|
||||
ensurePrivateDirectory(this.stateDirectory);
|
||||
this.objectsDirectory = path.join(this.stateDirectory, 'objects');
|
||||
this.snapshotsDirectory = path.join(this.stateDirectory, 'snapshots');
|
||||
ensurePrivateDirectory(this.objectsDirectory);
|
||||
ensurePrivateDirectory(this.snapshotsDirectory);
|
||||
this.now = now;
|
||||
this.clients = new Map();
|
||||
this.barriers = new Map();
|
||||
this.debugLease = null;
|
||||
this._withLock(() => this._recover());
|
||||
}
|
||||
|
||||
_withLock(action) {
|
||||
const lock = path.join(this.stateDirectory, 'writer.lock');
|
||||
let fd;
|
||||
try {
|
||||
fd = fs.openSync(lock, 'wx', 0o600);
|
||||
} catch (error) {
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
// A crashed writer leaves a lock. Never steal a live or undecodable lock.
|
||||
let previous;
|
||||
try {
|
||||
previous = JSON.parse(fs.readFileSync(lock, 'utf8'));
|
||||
} catch {
|
||||
fail('STATE_BUSY', 'State writer lock requires operator inspection');
|
||||
}
|
||||
if (!Number.isSafeInteger(previous.pid) || previous.pid <= 0) fail('STATE_BUSY', 'State writer lock is invalid');
|
||||
try {
|
||||
process.kill(previous.pid, 0);
|
||||
fail('STATE_BUSY', 'Another coordinator is writing state');
|
||||
} catch (probe) {
|
||||
if (probe.code !== 'ESRCH') throw probe;
|
||||
}
|
||||
fs.unlinkSync(lock);
|
||||
try {
|
||||
fd = fs.openSync(lock, 'wx', 0o600);
|
||||
} catch {
|
||||
fail('STATE_BUSY', 'Another coordinator is writing state');
|
||||
}
|
||||
}
|
||||
try {
|
||||
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid }));
|
||||
fs.fsyncSync(fd);
|
||||
return action();
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
fs.unlinkSync(lock);
|
||||
}
|
||||
}
|
||||
|
||||
_recover() {
|
||||
const snapshots = fs
|
||||
.readdirSync(this.snapshotsDirectory)
|
||||
.filter(name => /^\d{12}\.json$/.test(name))
|
||||
.sort();
|
||||
let revision = 0;
|
||||
let latest = null;
|
||||
const commits = new Map();
|
||||
for (const name of snapshots) {
|
||||
const file = path.join(this.snapshotsDirectory, name);
|
||||
if (!fs.lstatSync(file).isFile()) fail('STATE_CORRUPT', 'Snapshot is not a regular file');
|
||||
const snapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
const { id, ...body } = snapshot;
|
||||
if (
|
||||
snapshot.schemaVersion !== 1 ||
|
||||
snapshot.workspace !== this.workspaceRoot ||
|
||||
snapshot.revision !== revision + 1 ||
|
||||
snapshot.previousId !== (latest?.id ?? null) ||
|
||||
id !== sha(JSON.stringify(body)) ||
|
||||
name !== `${String(snapshot.revision).padStart(12, '0')}.json`
|
||||
)
|
||||
fail('STATE_CORRUPT', 'Snapshot chain failed integrity verification');
|
||||
if (!Array.isArray(snapshot.files) || snapshot.digest !== sha(JSON.stringify(snapshot.files)))
|
||||
fail('STATE_CORRUPT', 'Snapshot manifest failed integrity verification');
|
||||
for (const item of snapshot.files) {
|
||||
if (
|
||||
typeof item.path !== 'string' ||
|
||||
path.posix.isAbsolute(item.path) ||
|
||||
item.path.split('/').some(part => part === '..' || part === '' || part === '.') ||
|
||||
!/^[a-f0-9]{64}$/.test(item.sha256)
|
||||
)
|
||||
fail('STATE_CORRUPT', 'Snapshot contains an unsafe file entry');
|
||||
const object = path.join(this.objectsDirectory, item.sha256);
|
||||
if (!fs.lstatSync(object).isFile()) fail('STATE_CORRUPT', 'Snapshot object is not a regular file');
|
||||
const bytes = fs.readFileSync(object);
|
||||
if (bytes.length !== item.size || sha(bytes) !== item.sha256)
|
||||
fail('STATE_CORRUPT', 'Snapshot content failed integrity verification');
|
||||
}
|
||||
revision = snapshot.revision;
|
||||
latest = snapshot;
|
||||
if (commits.has(snapshot.barrierId)) fail('STATE_CORRUPT', 'Save barrier has multiple committed revisions');
|
||||
commits.set(snapshot.barrierId, snapshot);
|
||||
}
|
||||
const journalPath = path.join(this.stateDirectory, 'journal.json');
|
||||
if (fs.existsSync(journalPath)) {
|
||||
if (!fs.lstatSync(journalPath).isFile()) fail('STATE_CORRUPT', 'Journal is not a regular file');
|
||||
const journal = JSON.parse(fs.readFileSync(journalPath, 'utf8'));
|
||||
if (
|
||||
journal.schemaVersion !== 1 ||
|
||||
journal.workspace !== this.workspaceRoot ||
|
||||
!Number.isSafeInteger(journal.revision) ||
|
||||
journal.revision > revision ||
|
||||
journal.revision < 0 ||
|
||||
(journal.revision === revision && journal.latestId !== (latest?.id ?? null))
|
||||
)
|
||||
fail('STATE_CORRUPT', 'Journal does not match committed snapshots');
|
||||
}
|
||||
this.revision = revision;
|
||||
this.latestSnapshot = latest;
|
||||
this.commits = commits;
|
||||
// A committed immutable manifest is the transaction record. Repair a stale/missing head after crash.
|
||||
atomicFile(
|
||||
journalPath,
|
||||
JSON.stringify({ schemaVersion: 1, workspace: this.workspaceRoot, revision, latestId: latest?.id ?? null }),
|
||||
);
|
||||
}
|
||||
|
||||
_documents(payload) {
|
||||
if (
|
||||
!payload ||
|
||||
!Array.isArray(payload.documents) ||
|
||||
payload.documents.length > 10_000 ||
|
||||
(payload.dirty !== undefined && typeof payload.dirty !== 'boolean')
|
||||
)
|
||||
fail('INVALID_INPUT', 'A document version vector is required');
|
||||
const seen = new Set();
|
||||
const documents = payload.documents
|
||||
.map(document => {
|
||||
if (
|
||||
!document ||
|
||||
typeof document.uri !== 'string' ||
|
||||
document.uri.length < 1 ||
|
||||
document.uri.length > 8192 ||
|
||||
/[\u0000-\u001f]/.test(document.uri) ||
|
||||
!Number.isSafeInteger(document.version) ||
|
||||
document.version < 0 ||
|
||||
typeof document.dirty !== 'boolean'
|
||||
)
|
||||
fail('INVALID_INPUT', 'Invalid document version');
|
||||
let uri = document.uri;
|
||||
if (uri.startsWith('file:')) {
|
||||
let target;
|
||||
try {
|
||||
target = fileURLToPath(uri);
|
||||
} catch {
|
||||
fail('INVALID_INPUT', 'Invalid file URI');
|
||||
}
|
||||
// macOS /var and /tmp aliases, or a provisioned root alias, refer to the same configured workspace.
|
||||
if (inside(this.requestedWorkspaceRoot, path.resolve(target)))
|
||||
target = path.resolve(this.workspaceRoot, path.relative(this.requestedWorkspaceRoot, target));
|
||||
if (!inside(this.workspaceRoot, path.resolve(target)))
|
||||
fail('OUTSIDE_WORKSPACE', 'Document is outside this workspace');
|
||||
uri = path.relative(this.workspaceRoot, target).split(path.sep).join('/');
|
||||
} else if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(uri)) {
|
||||
const target = path.resolve(this.workspaceRoot, uri);
|
||||
if (!inside(this.workspaceRoot, target)) fail('OUTSIDE_WORKSPACE', 'Document is outside this workspace');
|
||||
uri = path.relative(this.workspaceRoot, target).split(path.sep).join('/');
|
||||
}
|
||||
// Non-file editor URIs (including collaboration and untitled documents) are opaque IDs, never paths to read.
|
||||
if (seen.has(uri)) fail('INVALID_INPUT', 'Duplicate document URI');
|
||||
seen.add(uri);
|
||||
return { uri, version: document.version, dirty: document.dirty };
|
||||
})
|
||||
.sort((left, right) => left.uri.localeCompare(right.uri));
|
||||
return { documents, dirty: payload.dirty === true || documents.some(document => document.dirty) };
|
||||
}
|
||||
|
||||
_versions(documents) {
|
||||
return JSON.stringify(documents.map(({ uri, version }) => ({ uri, version })));
|
||||
}
|
||||
_invalidate(reason) {
|
||||
for (const barrier of this.barriers.values())
|
||||
if (barrier.status === 'pending') {
|
||||
barrier.status = 'invalid';
|
||||
barrier.reason = reason;
|
||||
}
|
||||
}
|
||||
_activeClients() {
|
||||
return [...this.clients.values()].filter(client => this.now() - client.lastSeen < CLIENT_TTL_MS);
|
||||
}
|
||||
|
||||
register(actorId, clientId, payload) {
|
||||
identifier(actorId, 'actor ID');
|
||||
identifier(clientId, 'client ID');
|
||||
const existing = this.clients.get(clientId);
|
||||
if (existing && existing.actorId !== actorId) fail('CLIENT_OWNERSHIP', 'Client belongs to another actor');
|
||||
const normalized = this._documents(payload);
|
||||
for (const barrier of this.barriers.values()) {
|
||||
if (barrier.status !== 'pending') continue;
|
||||
const participant = barrier.participants.find(item => item.clientId === clientId);
|
||||
if (
|
||||
!participant ||
|
||||
this._versions(normalized.documents) !== this._versions(participant.documents) ||
|
||||
normalized.dirty
|
||||
) {
|
||||
barrier.status = 'invalid';
|
||||
barrier.reason = 'Client membership or document version changed';
|
||||
}
|
||||
}
|
||||
const client = { actorId, clientId, ...normalized, lastSeen: this.now() };
|
||||
this.clients.set(clientId, client);
|
||||
return clone(client);
|
||||
}
|
||||
|
||||
unregister(actorId, clientId) {
|
||||
identifier(actorId, 'actor ID');
|
||||
identifier(clientId, 'client ID');
|
||||
const client = this.clients.get(clientId);
|
||||
if (!client) return { unregistered: true };
|
||||
if (client.actorId !== actorId) fail('CLIENT_OWNERSHIP', 'Client belongs to another actor');
|
||||
this.clients.delete(clientId);
|
||||
for (const barrier of this.barriers.values())
|
||||
if (barrier.status === 'pending' && barrier.participants.some(item => item.clientId === clientId)) {
|
||||
barrier.status = 'invalid';
|
||||
barrier.reason = 'Participant disconnected';
|
||||
}
|
||||
return { unregistered: true };
|
||||
}
|
||||
|
||||
_capture(retainBlobs = true) {
|
||||
const files = [];
|
||||
const blobs = new Map();
|
||||
let totalBytes = 0;
|
||||
const checkSize = size => {
|
||||
if (size > BigInt(this.limits.maxFileBytes)) fail('SNAPSHOT_LIMIT', 'Snapshot file exceeds maxFileBytes');
|
||||
if (size + BigInt(totalBytes) > BigInt(this.limits.maxTotalBytes))
|
||||
fail('SNAPSHOT_LIMIT', 'Snapshot exceeds maxTotalBytes');
|
||||
};
|
||||
const walk = (directory, relative = '') => {
|
||||
for (const name of fs.readdirSync(directory).sort()) {
|
||||
if (EXCLUDED.has(name)) continue;
|
||||
const absolute = path.join(directory, name);
|
||||
const entry = fs.lstatSync(absolute);
|
||||
if (entry.isSymbolicLink()) fail('UNSAFE_WORKSPACE_PATH', 'Snapshots reject symbolic links');
|
||||
const logical = relative ? relative + '/' + name : name;
|
||||
if (entry.isDirectory()) {
|
||||
if (!inside(this.workspaceRoot, fs.realpathSync(absolute)))
|
||||
fail('UNSAFE_WORKSPACE_PATH', 'Directory escaped the workspace');
|
||||
walk(absolute, logical);
|
||||
} else if (entry.isFile()) {
|
||||
if (files.length >= this.limits.maxFiles) fail('SNAPSHOT_LIMIT', 'Snapshot exceeds maxFiles');
|
||||
if (!Number.isSafeInteger(entry.size) || entry.size < 0)
|
||||
fail('SNAPSHOT_LIMIT', 'Snapshot file has unsupported size');
|
||||
checkSize(BigInt(entry.size));
|
||||
// Check both the path and open descriptor; O_NOFOLLOW rejects last-component symlink races.
|
||||
if (!inside(this.workspaceRoot, fs.realpathSync(absolute)))
|
||||
fail('UNSAFE_WORKSPACE_PATH', 'File escaped the workspace');
|
||||
const fd = fs.openSync(absolute, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
||||
let bytes;
|
||||
try {
|
||||
const before = fs.fstatSync(fd, { bigint: true });
|
||||
if (!before.isFile() || before.ino !== BigInt(entry.ino) || before.dev !== BigInt(entry.dev))
|
||||
fail('DISK_CHANGED', 'File changed while reading');
|
||||
checkSize(before.size);
|
||||
// A file may grow after fstat. Never let readFileSync allocate from
|
||||
// that mutable size; read only the already-validated bounded length.
|
||||
bytes = Buffer.alloc(Number(before.size));
|
||||
let read = 0;
|
||||
while (read < bytes.length) {
|
||||
const count = fs.readSync(fd, bytes, read, bytes.length - read, null);
|
||||
if (!count) break;
|
||||
read += count;
|
||||
}
|
||||
const extra = fs.readSync(fd, Buffer.alloc(1), 0, 1, null);
|
||||
const after = fs.fstatSync(fd, { bigint: true });
|
||||
checkSize(after.size);
|
||||
if (
|
||||
read !== bytes.length ||
|
||||
extra !== 0 ||
|
||||
before.ino !== after.ino ||
|
||||
before.size !== after.size ||
|
||||
before.mtimeNs !== after.mtimeNs ||
|
||||
before.ctimeNs !== after.ctimeNs ||
|
||||
after.size !== BigInt(bytes.length)
|
||||
)
|
||||
fail('DISK_CHANGED', 'File changed while reading');
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
totalBytes += bytes.length;
|
||||
const digest = sha(bytes);
|
||||
if (retainBlobs) blobs.set(digest, bytes);
|
||||
files.push({ path: logical, sha256: digest, size: bytes.length, mode: entry.mode & 0o777 });
|
||||
} else fail('UNSAFE_WORKSPACE_PATH', 'Snapshots support regular files and directories only');
|
||||
}
|
||||
};
|
||||
walk(this.workspaceRoot);
|
||||
return { files, digest: sha(JSON.stringify(files)), blobs };
|
||||
}
|
||||
|
||||
beginBarrier(actorId) {
|
||||
identifier(actorId, 'actor ID');
|
||||
for (const barrier of this.barriers.values())
|
||||
if (barrier.status === 'pending' && this.now() < barrier.expiresAt)
|
||||
fail('BARRIER_BUSY', 'A save barrier is already pending');
|
||||
const active = this._activeClients();
|
||||
if (!active.some(client => client.actorId === actorId))
|
||||
fail('CLIENT_REQUIRED', 'Register an active client before starting a barrier');
|
||||
const disk = this._capture(false);
|
||||
const barrier = {
|
||||
id: randomBytes(24).toString('hex'),
|
||||
actorId,
|
||||
status: 'pending',
|
||||
createdAt: this.now(),
|
||||
expiresAt: this.now() + BARRIER_TTL_MS,
|
||||
diskDigest: disk.digest,
|
||||
participants: active.map(client => ({
|
||||
actorId: client.actorId,
|
||||
clientId: client.clientId,
|
||||
documents: clone(client.documents),
|
||||
acknowledged: false,
|
||||
})),
|
||||
};
|
||||
this.barriers.set(barrier.id, barrier);
|
||||
// Bound ephemeral metadata without discarding an in-flight barrier.
|
||||
if (this.barriers.size > 100)
|
||||
for (const [id, previous] of this.barriers)
|
||||
if (previous.status !== 'pending' || previous.expiresAt <= this.now()) {
|
||||
this.barriers.delete(id);
|
||||
break;
|
||||
}
|
||||
return clone(barrier);
|
||||
}
|
||||
|
||||
_barrier(id) {
|
||||
const barrier = this.barriers.get(id);
|
||||
if (!barrier) fail('BARRIER_NOT_FOUND', 'Save barrier does not exist');
|
||||
if (barrier.status !== 'pending') fail('BARRIER_INVALID', barrier.reason || 'Save barrier is no longer pending');
|
||||
if (this.now() >= barrier.expiresAt) {
|
||||
barrier.status = 'expired';
|
||||
fail('BARRIER_EXPIRED', 'Save barrier expired');
|
||||
}
|
||||
return barrier;
|
||||
}
|
||||
|
||||
acknowledge(actorId, barrierId, clientId, payload) {
|
||||
identifier(actorId, 'actor ID');
|
||||
identifier(clientId, 'client ID');
|
||||
const barrier = this._barrier(barrierId);
|
||||
const participant = barrier.participants.find(item => item.clientId === clientId);
|
||||
const client = this.clients.get(clientId);
|
||||
if (!participant || !client || participant.actorId !== actorId || client.actorId !== actorId)
|
||||
fail('CLIENT_OWNERSHIP', 'Only the participant may acknowledge its own saved documents');
|
||||
const normalized = this._documents(payload);
|
||||
if (normalized.dirty || client.dirty)
|
||||
fail('DIRTY_DOCUMENTS', 'All documents must be saved and registered clean before acknowledgement');
|
||||
if (
|
||||
this._versions(normalized.documents) !== this._versions(participant.documents) ||
|
||||
this._versions(client.documents) !== this._versions(participant.documents)
|
||||
) {
|
||||
barrier.status = 'invalid';
|
||||
barrier.reason = 'Document version changed';
|
||||
fail('VERSION_CHANGED', barrier.reason);
|
||||
}
|
||||
if (this.now() - client.lastSeen >= CLIENT_TTL_MS) fail('CLIENT_EXPIRED', 'Client heartbeat expired');
|
||||
participant.acknowledged = true;
|
||||
return clone(barrier);
|
||||
}
|
||||
|
||||
_assertParticipants(barrier) {
|
||||
for (const participant of barrier.participants) {
|
||||
const client = this.clients.get(participant.clientId);
|
||||
if (!participant.acknowledged) fail('ACK_REQUIRED', 'Every frozen participant must acknowledge saving');
|
||||
if (!client || client.actorId !== participant.actorId || this.now() - client.lastSeen >= CLIENT_TTL_MS)
|
||||
fail('CLIENT_EXPIRED', 'A participant disconnected or expired');
|
||||
if (client.dirty) fail('DIRTY_DOCUMENTS', 'A participant has unsaved documents');
|
||||
if (this._versions(client.documents) !== this._versions(participant.documents))
|
||||
fail('VERSION_CHANGED', 'A participant changed document versions');
|
||||
}
|
||||
}
|
||||
|
||||
async commitBarrier(actorId, barrierId) {
|
||||
identifier(actorId, 'actor ID');
|
||||
const committed = this.commits.get(barrierId);
|
||||
if (committed) {
|
||||
if (committed.actorId !== actorId)
|
||||
fail('BARRIER_OWNERSHIP', 'Only the barrier creator may retrieve its committed result');
|
||||
return clone(committed);
|
||||
}
|
||||
const barrier = this._barrier(barrierId);
|
||||
if (barrier.actorId !== actorId) fail('BARRIER_OWNERSHIP', 'Only the barrier creator may commit it');
|
||||
this._assertParticipants(barrier);
|
||||
return this._withLock(() => {
|
||||
this._recover();
|
||||
const recovered = this.commits.get(barrierId);
|
||||
if (recovered) {
|
||||
if (recovered.actorId !== actorId)
|
||||
fail('BARRIER_OWNERSHIP', 'Only the barrier creator may retrieve its committed result');
|
||||
barrier.status = 'committed';
|
||||
barrier.snapshotId = recovered.id;
|
||||
barrier.revision = recovered.revision;
|
||||
return clone(recovered);
|
||||
}
|
||||
const disk = this._capture();
|
||||
if (disk.digest !== barrier.diskDigest) {
|
||||
barrier.status = 'invalid';
|
||||
barrier.reason = 'Disk changed during save barrier';
|
||||
fail('DISK_CHANGED', barrier.reason);
|
||||
}
|
||||
for (const [digest, bytes] of disk.blobs) {
|
||||
const object = path.join(this.objectsDirectory, digest);
|
||||
if (fs.existsSync(object)) {
|
||||
if (!fs.lstatSync(object).isFile() || sha(fs.readFileSync(object)) !== digest)
|
||||
fail('STATE_CORRUPT', 'Existing content-addressed object is invalid');
|
||||
} else atomicFile(object, bytes, true);
|
||||
}
|
||||
// Re-read immediately before committing; saved snapshot content is never read from mutable source later.
|
||||
if (this._capture(false).digest !== disk.digest) {
|
||||
barrier.status = 'invalid';
|
||||
barrier.reason = 'Disk changed while materializing snapshot';
|
||||
fail('DISK_CHANGED', barrier.reason);
|
||||
}
|
||||
this._barrier(barrierId);
|
||||
this._assertParticipants(barrier);
|
||||
const body = {
|
||||
schemaVersion: 1,
|
||||
workspace: this.workspaceRoot,
|
||||
revision: this.revision + 1,
|
||||
previousId: this.latestSnapshot?.id ?? null,
|
||||
digest: disk.digest,
|
||||
files: disk.files,
|
||||
createdAt: this.now(),
|
||||
actorId,
|
||||
barrierId,
|
||||
};
|
||||
const snapshot = { id: sha(JSON.stringify(body)), ...body };
|
||||
atomicFile(
|
||||
path.join(this.snapshotsDirectory, `${String(snapshot.revision).padStart(12, '0')}.json`),
|
||||
JSON.stringify(snapshot),
|
||||
true,
|
||||
);
|
||||
this.revision = snapshot.revision;
|
||||
this.latestSnapshot = snapshot;
|
||||
atomicFile(
|
||||
path.join(this.stateDirectory, 'journal.json'),
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
workspace: this.workspaceRoot,
|
||||
revision: this.revision,
|
||||
latestId: snapshot.id,
|
||||
}),
|
||||
);
|
||||
this.commits.set(barrierId, snapshot);
|
||||
barrier.status = 'committed';
|
||||
barrier.snapshotId = snapshot.id;
|
||||
barrier.revision = snapshot.revision;
|
||||
return clone(snapshot);
|
||||
});
|
||||
}
|
||||
|
||||
_liveDebugLease() {
|
||||
if (this.debugLease && this.now() >= this.debugLease.expiresAt) this.debugLease = null;
|
||||
return this.debugLease;
|
||||
}
|
||||
debugAcquire(actorId, token) {
|
||||
identifier(actorId, 'actor ID');
|
||||
const current = this._liveDebugLease();
|
||||
if (current) {
|
||||
if (current.actorId !== actorId || current.token !== token)
|
||||
fail('DEBUG_BUSY', 'Debug control is held by a live lease');
|
||||
current.expiresAt = this.now() + DEBUG_LEASE_MS;
|
||||
return clone(current);
|
||||
}
|
||||
this.debugLease = { actorId, token: randomBytes(32).toString('hex'), expiresAt: this.now() + DEBUG_LEASE_MS };
|
||||
return clone(this.debugLease);
|
||||
}
|
||||
assertDebugController(actorId, token) {
|
||||
const lease = this._liveDebugLease();
|
||||
if (!lease || lease.actorId !== actorId || typeof token !== 'string' || token !== lease.token)
|
||||
fail('DEBUG_FORBIDDEN', 'An active debug controller lease is required');
|
||||
return { actorId, expiresAt: lease.expiresAt };
|
||||
}
|
||||
debugTransfer(actorId, token, targetActorId) {
|
||||
identifier(targetActorId, 'target actor ID');
|
||||
this.assertDebugController(actorId, token);
|
||||
if (!this._activeClients().some(client => client.actorId === targetActorId))
|
||||
fail('CLIENT_REQUIRED', 'Target controller must have an active registered client');
|
||||
this.debugLease = {
|
||||
actorId: targetActorId,
|
||||
token: randomBytes(32).toString('hex'),
|
||||
expiresAt: this.now() + DEBUG_LEASE_MS,
|
||||
};
|
||||
return clone(this.debugLease);
|
||||
}
|
||||
debugRelease(actorId, token) {
|
||||
this.assertDebugController(actorId, token);
|
||||
this.debugLease = null;
|
||||
return { released: true };
|
||||
}
|
||||
revoke(actorId) {
|
||||
identifier(actorId, 'actor ID');
|
||||
for (const [id, client] of this.clients) if (client.actorId === actorId) this.clients.delete(id);
|
||||
for (const barrier of this.barriers.values())
|
||||
if (
|
||||
barrier.status === 'pending' &&
|
||||
(barrier.actorId === actorId || barrier.participants.some(item => item.actorId === actorId))
|
||||
) {
|
||||
barrier.status = 'invalid';
|
||||
barrier.reason = 'Participant access revoked';
|
||||
}
|
||||
if (this.debugLease?.actorId === actorId) this.debugLease = null;
|
||||
return { revoked: true };
|
||||
}
|
||||
state() {
|
||||
const lease = this._liveDebugLease();
|
||||
return clone({
|
||||
schemaVersion: 1,
|
||||
revision: this.revision,
|
||||
latestSnapshot: this.latestSnapshot,
|
||||
clients: this._activeClients(),
|
||||
barriers: [...this.barriers.values()].map(barrier => ({
|
||||
...barrier,
|
||||
status: barrier.status === 'pending' && this.now() >= barrier.expiresAt ? 'expired' : barrier.status,
|
||||
})),
|
||||
debugController: lease ? { actorId: lease.actorId, expiresAt: lease.expiresAt } : null,
|
||||
});
|
||||
}
|
||||
inputState() {
|
||||
const state = this.state();
|
||||
const clients = state.clients
|
||||
.map(({ actorId, clientId, documents, dirty }) => ({ actorId, clientId, documents, dirty }))
|
||||
.sort((a, b) => a.clientId.localeCompare(b.clientId));
|
||||
const snapshot = state.latestSnapshot;
|
||||
return {
|
||||
latestSnapshot: snapshot
|
||||
? { id: snapshot.id, revision: snapshot.revision, digest: snapshot.digest, files: snapshot.files }
|
||||
: null,
|
||||
currentDiskDigest: this._capture(false).digest,
|
||||
activityDigest: sha(JSON.stringify(clients)),
|
||||
dirty: clients.some(client => client.dirty),
|
||||
activeClients: clients.length,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
Coordinator,
|
||||
CoordinationError,
|
||||
EXCLUDED: Object.freeze([...EXCLUDED]),
|
||||
CLIENT_TTL_MS,
|
||||
BARRIER_TTL_MS,
|
||||
DEBUG_LEASE_MS,
|
||||
DEFAULT_SNAPSHOT_LIMITS,
|
||||
};
|
||||
@ -1,12 +0,0 @@
|
||||
{
|
||||
"name": "@wishforge/ide-coordination",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"main": "index.cjs",
|
||||
"scripts": {
|
||||
"test": "node --test test/*.test.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
@ -1,499 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
const { Coordinator, CLIENT_TTL_MS, DEBUG_LEASE_MS, BARRIER_TTL_MS, DEFAULT_SNAPSHOT_LIMITS } = require('../index.cjs');
|
||||
|
||||
function fixture(t, extraOptions = {}) {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'wishforge-coordination-'));
|
||||
const workspaceRoot = path.join(directory, 'source');
|
||||
const stateDirectory = path.join(directory, 'coordination');
|
||||
fs.mkdirSync(workspaceRoot);
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'export const answer = 42;\n');
|
||||
let time = 1_000;
|
||||
const options = { workspaceRoot, stateDirectory, now: () => time, ...extraOptions };
|
||||
const coordinator = new Coordinator(options);
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
return {
|
||||
directory,
|
||||
workspaceRoot,
|
||||
stateDirectory,
|
||||
coordinator,
|
||||
options,
|
||||
advance: ms => {
|
||||
time += ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
const clean = (version = 1) => ({ documents: [{ uri: 'app.ts', version, dirty: false }] });
|
||||
const dirty = (version = 1) => ({ documents: [{ uri: 'app.ts', version, dirty: true }] });
|
||||
function code(expected) {
|
||||
return error => error.code === expected;
|
||||
}
|
||||
function acknowledged(coordinator, actor = 'alice', client = 'alice-tab') {
|
||||
coordinator.register(actor, client, clean());
|
||||
const barrier = coordinator.beginBarrier(actor);
|
||||
coordinator.acknowledge(actor, barrier.id, client, clean());
|
||||
return barrier;
|
||||
}
|
||||
|
||||
test('saved immutable manifest records exact content and revision outside source without writing drafts', async t => {
|
||||
const { coordinator: engine, workspaceRoot, stateDirectory } = fixture(t);
|
||||
const original = fs.readFileSync(path.join(workspaceRoot, 'app.ts'));
|
||||
for (const name of ['.git', 'node_modules', 'dist', 'build', '.next', 'src-gen', '.wishforge-runtime']) {
|
||||
fs.mkdirSync(path.join(workspaceRoot, name));
|
||||
fs.writeFileSync(path.join(workspaceRoot, name, 'excluded'), 'runtime output');
|
||||
}
|
||||
fs.mkdirSync(path.join(workspaceRoot, 'src'));
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'src', 'main.py'), 'print(42)\n');
|
||||
const snapshot = await engine.commitBarrier('alice', acknowledged(engine).id);
|
||||
assert.equal(snapshot.revision, 1);
|
||||
assert.deepEqual(
|
||||
snapshot.files.map(file => file.path),
|
||||
['app.ts', 'src/main.py'],
|
||||
);
|
||||
assert.deepEqual(fs.readFileSync(path.join(workspaceRoot, 'app.ts')), original);
|
||||
const manifestPath = path.join(
|
||||
stateDirectory,
|
||||
'snapshots',
|
||||
fs.readdirSync(path.join(stateDirectory, 'snapshots'))[0],
|
||||
);
|
||||
const savedManifest = fs.readFileSync(manifestPath);
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'new content after snapshot');
|
||||
assert.deepEqual(fs.readFileSync(path.join(stateDirectory, 'objects', snapshot.files[0].sha256)), original);
|
||||
assert.deepEqual(fs.readFileSync(manifestPath), savedManifest);
|
||||
assert.equal(fs.statSync(stateDirectory).mode & 0o777, 0o700);
|
||||
assert.equal(fs.statSync(path.join(stateDirectory, 'objects')).mode & 0o777, 0o700);
|
||||
assert.equal(fs.statSync(manifestPath).mode & 0o777, 0o400);
|
||||
snapshot.files[0].path = 'mutated-client-copy';
|
||||
assert.equal(engine.state().latestSnapshot.files[0].path, 'app.ts');
|
||||
});
|
||||
|
||||
test('constructor limits have bounded defaults and reject nonpositive or unsafe configuration', t => {
|
||||
const { coordinator: engine, options } = fixture(t);
|
||||
assert.deepEqual(engine.limits, {
|
||||
maxFileBytes: 32 * 1024 * 1024,
|
||||
maxTotalBytes: 256 * 1024 * 1024,
|
||||
maxFiles: 20_000,
|
||||
});
|
||||
assert.deepEqual(engine.limits, DEFAULT_SNAPSHOT_LIMITS);
|
||||
for (const key of Object.keys(DEFAULT_SNAPSHOT_LIMITS))
|
||||
for (const value of [0, -1, 1.5, NaN, Infinity, '32', null, undefined, Number.MAX_SAFE_INTEGER + 1]) {
|
||||
assert.throws(() => new Coordinator({ ...options, limits: { [key]: value } }), code('INVALID_INPUT'));
|
||||
}
|
||||
for (const limits of [null, [], 'limits', { unknownLimit: 1 }, { toString: 1 }])
|
||||
assert.throws(() => new Coordinator({ ...options, limits }), code('INVALID_INPUT'));
|
||||
});
|
||||
|
||||
test('single-file resource limit rejects before opening source for reading', t => {
|
||||
const { coordinator: engine, workspaceRoot } = fixture(t, { limits: { maxFileBytes: 8 } });
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), '123456789');
|
||||
engine.register('alice', 'a', clean());
|
||||
const open = fs.openSync;
|
||||
let sourceOpened = false;
|
||||
fs.openSync = (file, ...args) => {
|
||||
if (typeof file === 'string' && file.endsWith('/app.ts')) sourceOpened = true;
|
||||
return open(file, ...args);
|
||||
};
|
||||
try {
|
||||
assert.throws(() => engine.beginBarrier('alice'), code('SNAPSHOT_LIMIT'));
|
||||
} finally {
|
||||
fs.openSync = open;
|
||||
}
|
||||
assert.equal(sourceOpened, false);
|
||||
assert.equal(engine.state().revision, 0);
|
||||
});
|
||||
|
||||
test('source growth after fd stat is read only into the bounded allocation then rejected', t => {
|
||||
const { coordinator: engine, workspaceRoot } = fixture(t, { limits: { maxFileBytes: 3 } });
|
||||
const source = path.join(workspaceRoot, 'app.ts');
|
||||
fs.writeFileSync(source, 'abc');
|
||||
engine.register('alice', 'a', clean());
|
||||
const read = fs.readSync;
|
||||
let grew = false;
|
||||
const allocations = [];
|
||||
fs.readSync = (fd, buffer, ...args) => {
|
||||
allocations.push(buffer.length);
|
||||
if (!grew) {
|
||||
grew = true;
|
||||
fs.appendFileSync(source, 'defghijklmnop');
|
||||
}
|
||||
return read(fd, buffer, ...args);
|
||||
};
|
||||
try {
|
||||
assert.throws(() => engine.beginBarrier('alice'), code('SNAPSHOT_LIMIT'));
|
||||
} finally {
|
||||
fs.readSync = read;
|
||||
}
|
||||
assert.equal(grew, true);
|
||||
assert.deepEqual(allocations, [3, 1]);
|
||||
assert.equal(engine.state().revision, 0);
|
||||
});
|
||||
|
||||
test('aggregate bytes and file count caps reject duplicate content and empty files', t => {
|
||||
const bytes = fixture(t, { limits: { maxFileBytes: 8, maxTotalBytes: 9 } });
|
||||
fs.writeFileSync(path.join(bytes.workspaceRoot, 'app.ts'), '12345');
|
||||
fs.writeFileSync(path.join(bytes.workspaceRoot, 'second.ts'), '12345');
|
||||
bytes.coordinator.register('alice', 'a', clean());
|
||||
assert.throws(() => bytes.coordinator.beginBarrier('alice'), code('SNAPSHOT_LIMIT'));
|
||||
const count = fixture(t, { limits: { maxFiles: 1 } });
|
||||
fs.writeFileSync(path.join(count.workspaceRoot, 'app.ts'), '');
|
||||
fs.writeFileSync(path.join(count.workspaceRoot, 'second.ts'), '');
|
||||
count.coordinator.register('alice', 'a', clean());
|
||||
assert.throws(() => count.coordinator.beginBarrier('alice'), code('SNAPSHOT_LIMIT'));
|
||||
});
|
||||
|
||||
test('exact configured limits permit a snapshot while excluded runtime files do not consume caps', async t => {
|
||||
const { coordinator: engine, workspaceRoot } = fixture(t, {
|
||||
limits: { maxFileBytes: 5, maxTotalBytes: 10, maxFiles: 2 },
|
||||
});
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), '12345');
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'second.ts'), '67890');
|
||||
fs.mkdirSync(path.join(workspaceRoot, 'node_modules'));
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'node_modules', 'large'), 'excluded-runtime-file');
|
||||
const snapshot = await engine.commitBarrier('alice', acknowledged(engine).id);
|
||||
assert.equal(snapshot.files.length, 2);
|
||||
assert.equal(
|
||||
snapshot.files.reduce((total, file) => total + file.size, 0),
|
||||
10,
|
||||
);
|
||||
});
|
||||
|
||||
test('commit checks barrier expiry again after the final filesystem scan', async t => {
|
||||
const { coordinator: engine, advance, stateDirectory } = fixture(t);
|
||||
const barrier = acknowledged(engine);
|
||||
const capture = engine._capture.bind(engine);
|
||||
let captures = 0;
|
||||
engine._capture = (...args) => {
|
||||
const result = capture(...args);
|
||||
if (++captures === 2) advance(BARRIER_TTL_MS);
|
||||
return result;
|
||||
};
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_EXPIRED'));
|
||||
assert.equal(engine.state().revision, 0);
|
||||
assert.deepEqual(fs.readdirSync(path.join(stateDirectory, 'snapshots')), []);
|
||||
});
|
||||
|
||||
test('commit checks stale participant heartbeats after scanning even when barrier itself remains valid', async t => {
|
||||
const { coordinator: engine, advance, stateDirectory } = fixture(t);
|
||||
engine.register('alice', 'a', clean());
|
||||
advance(10_000);
|
||||
const barrier = engine.beginBarrier('alice');
|
||||
engine.acknowledge('alice', barrier.id, 'a', clean());
|
||||
const capture = engine._capture.bind(engine);
|
||||
let captures = 0;
|
||||
engine._capture = (...args) => {
|
||||
const result = capture(...args);
|
||||
if (++captures === 2) advance(CLIENT_TTL_MS - 10_000);
|
||||
return result;
|
||||
};
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('CLIENT_EXPIRED'));
|
||||
assert.equal(engine.state().revision, 0);
|
||||
assert.deepEqual(fs.readdirSync(path.join(stateDirectory, 'snapshots')), []);
|
||||
});
|
||||
|
||||
test('all concurrent participants must acknowledge their own clean saved version', async t => {
|
||||
const { coordinator: engine } = fixture(t);
|
||||
engine.register('alice', 'a', clean());
|
||||
engine.register('bob', 'b', dirty());
|
||||
const barrier = engine.beginBarrier('alice');
|
||||
assert.throws(() => engine.acknowledge('alice', barrier.id, 'b', clean()), code('CLIENT_OWNERSHIP'));
|
||||
assert.throws(() => engine.acknowledge('bob', barrier.id, 'b', clean()), code('DIRTY_DOCUMENTS'));
|
||||
engine.acknowledge('alice', barrier.id, 'a', clean());
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('ACK_REQUIRED'));
|
||||
engine.register('bob', 'b', clean());
|
||||
engine.acknowledge('bob', barrier.id, 'b', clean());
|
||||
await assert.rejects(engine.commitBarrier('bob', barrier.id), code('BARRIER_OWNERSHIP'));
|
||||
const snapshot = await engine.commitBarrier('alice', barrier.id);
|
||||
assert.equal(snapshot.revision, 1);
|
||||
});
|
||||
|
||||
test('dirty buffers or version drift after acknowledgement invalidate the barrier permanently', async t => {
|
||||
const { coordinator: engine } = fixture(t);
|
||||
const barrier = acknowledged(engine);
|
||||
engine.register('alice', 'alice-tab', dirty(1));
|
||||
engine.register('alice', 'alice-tab', clean(1));
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID'));
|
||||
const second = acknowledged(engine);
|
||||
engine.register('alice', 'alice-tab', clean(2));
|
||||
await assert.rejects(engine.commitBarrier('alice', second.id), code('BARRIER_INVALID'));
|
||||
assert.equal(engine.state().revision, 0);
|
||||
});
|
||||
|
||||
test('dirty edit before acknowledgement cannot be hidden by a later clean heartbeat', async t => {
|
||||
const { coordinator: engine } = fixture(t);
|
||||
engine.register('alice', 'a', clean());
|
||||
const barrier = engine.beginBarrier('alice');
|
||||
engine.register('alice', 'a', dirty());
|
||||
engine.register('alice', 'a', clean());
|
||||
assert.throws(() => engine.acknowledge('alice', barrier.id, 'a', clean()), code('BARRIER_INVALID'));
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID'));
|
||||
});
|
||||
|
||||
test('new client joins cannot bypass the frozen participant set and client IDs cannot change actor', async t => {
|
||||
const { coordinator: engine } = fixture(t);
|
||||
const barrier = acknowledged(engine);
|
||||
assert.throws(() => engine.register('bob', 'alice-tab', clean()), code('CLIENT_OWNERSHIP'));
|
||||
engine.register('bob', 'bob-tab', dirty());
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID'));
|
||||
});
|
||||
|
||||
test('unregister invalidates that client barrier without revoking other actor tabs', async t => {
|
||||
const { coordinator: engine } = fixture(t);
|
||||
engine.register('alice', 'a', clean());
|
||||
engine.register('alice', 'another-tab', clean());
|
||||
engine.register('bob', 'b', clean());
|
||||
const barrier = engine.beginBarrier('alice');
|
||||
assert.throws(() => engine.unregister('bob', 'a'), code('CLIENT_OWNERSHIP'));
|
||||
engine.unregister('alice', 'a');
|
||||
assert.deepEqual(
|
||||
engine.state().clients.map(client => client.clientId),
|
||||
['another-tab', 'b'],
|
||||
);
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID'));
|
||||
assert.deepEqual(engine.unregister('alice', 'a'), { unregistered: true });
|
||||
});
|
||||
|
||||
test('an acknowledgement may not forge document version or omit frozen documents', t => {
|
||||
const { coordinator: engine } = fixture(t);
|
||||
engine.register('alice', 'a', clean());
|
||||
let barrier = engine.beginBarrier('alice');
|
||||
assert.throws(() => engine.acknowledge('alice', barrier.id, 'a', clean(0)), code('VERSION_CHANGED'));
|
||||
barrier = engine.beginBarrier('alice');
|
||||
assert.throws(() => engine.acknowledge('alice', barrier.id, 'a', { documents: [] }), code('VERSION_CHANGED'));
|
||||
});
|
||||
|
||||
test('disk mutation after barrier start refuses snapshot even with clean unchanged editor versions', async t => {
|
||||
const { coordinator: engine, workspaceRoot, stateDirectory } = fixture(t);
|
||||
const barrier = acknowledged(engine);
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'changed by external process');
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('DISK_CHANGED'));
|
||||
assert.equal(engine.state().revision, 0);
|
||||
assert.deepEqual(fs.readdirSync(path.join(stateDirectory, 'snapshots')), []);
|
||||
});
|
||||
|
||||
test('mutation while snapshot blobs are materialized is detected by the second capture', async t => {
|
||||
const { coordinator: engine, workspaceRoot } = fixture(t);
|
||||
const barrier = acknowledged(engine);
|
||||
const capture = engine._capture.bind(engine);
|
||||
let calls = 0;
|
||||
engine._capture = () => {
|
||||
const captured = capture();
|
||||
if (++calls === 1) fs.writeFileSync(path.join(workspaceRoot, 'new-after-read.ts'), 'race');
|
||||
return captured;
|
||||
};
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('DISK_CHANGED'));
|
||||
assert.equal(engine.state().revision, 0);
|
||||
});
|
||||
|
||||
test('snapshot revisions and exact content recover after restart and stale journal repair', async t => {
|
||||
const { coordinator: engine, workspaceRoot, stateDirectory, options } = fixture(t);
|
||||
const first = await engine.commitBarrier('alice', acknowledged(engine).id);
|
||||
const oldJournal = fs.readFileSync(path.join(stateDirectory, 'journal.json'));
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'revision two');
|
||||
const second = await engine.commitBarrier('alice', acknowledged(engine).id);
|
||||
assert.equal(second.previousId, first.id);
|
||||
fs.writeFileSync(path.join(stateDirectory, 'journal.json'), oldJournal);
|
||||
fs.writeFileSync(path.join(stateDirectory, 'journal.json.crash.tmp'), 'partial JSON');
|
||||
fs.writeFileSync(path.join(stateDirectory, 'snapshots', 'uncommitted.tmp'), 'partial JSON');
|
||||
const recovered = new Coordinator(options);
|
||||
assert.equal(recovered.state().revision, 2);
|
||||
assert.equal(recovered.state().latestSnapshot.id, second.id);
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(stateDirectory, 'journal.json'))).latestId, second.id);
|
||||
assert.deepEqual(recovered.state().clients, []);
|
||||
assert.deepEqual(recovered.state().barriers, []);
|
||||
const third = await recovered.commitBarrier('alice', acknowledged(recovered).id);
|
||||
assert.equal(third.revision, 3);
|
||||
assert.equal(third.previousId, second.id);
|
||||
});
|
||||
|
||||
test('commit response loss is safely retried once before and after backend restart', async t => {
|
||||
const { coordinator: engine, options } = fixture(t);
|
||||
const barrier = acknowledged(engine);
|
||||
const snapshot = await engine.commitBarrier('alice', barrier.id);
|
||||
assert.deepEqual(await engine.commitBarrier('alice', barrier.id), snapshot);
|
||||
const recovered = new Coordinator(options);
|
||||
assert.deepEqual(await recovered.commitBarrier('alice', barrier.id), snapshot);
|
||||
assert.equal(recovered.state().revision, 1);
|
||||
await assert.rejects(recovered.commitBarrier('bob', barrier.id), code('BARRIER_OWNERSHIP'));
|
||||
});
|
||||
|
||||
test('crash after manifest persistence but before journal update recovers a single committed snapshot', async t => {
|
||||
const { coordinator: engine, options, stateDirectory } = fixture(t);
|
||||
const barrier = acknowledged(engine);
|
||||
const rename = fs.renameSync;
|
||||
let journalWrites = 0;
|
||||
fs.renameSync = (from, to) => {
|
||||
if (to === path.join(engine.stateDirectory, 'journal.json') && ++journalWrites === 2)
|
||||
throw Object.assign(new Error('injected journal disk failure'), { code: 'EIO' });
|
||||
return rename(from, to);
|
||||
};
|
||||
try {
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), /injected journal disk failure/);
|
||||
} finally {
|
||||
fs.renameSync = rename;
|
||||
}
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(stateDirectory, 'journal.json'))).revision, 0);
|
||||
const recovered = new Coordinator(options);
|
||||
const snapshot = await recovered.commitBarrier('alice', barrier.id);
|
||||
assert.equal(snapshot.revision, 1);
|
||||
assert.equal(recovered.state().revision, 1);
|
||||
assert.equal(fs.readdirSync(path.join(stateDirectory, 'snapshots')).filter(name => name.endsWith('.json')).length, 1);
|
||||
});
|
||||
|
||||
test('recovery refuses content-addressed object tampering and never reconstructs it from newer source', async t => {
|
||||
const { coordinator: engine, stateDirectory, options } = fixture(t);
|
||||
const snapshot = await engine.commitBarrier('alice', acknowledged(engine).id);
|
||||
const object = path.join(stateDirectory, 'objects', snapshot.files[0].sha256);
|
||||
fs.chmodSync(object, 0o600);
|
||||
fs.writeFileSync(object, 'tampered');
|
||||
assert.throws(() => new Coordinator(options), code('STATE_CORRUPT'));
|
||||
});
|
||||
|
||||
test('rejects state inside source, symlink escapes and file URIs outside workspace', t => {
|
||||
const { coordinator: engine, workspaceRoot, directory } = fixture(t);
|
||||
assert.throws(
|
||||
() => new Coordinator({ workspaceRoot, stateDirectory: path.join(workspaceRoot, '.state') }),
|
||||
code('UNSAFE_STATE_PATH'),
|
||||
);
|
||||
assert.throws(() => new Coordinator({ workspaceRoot, stateDirectory: directory }), code('UNSAFE_STATE_PATH'));
|
||||
fs.symlinkSync(workspaceRoot, path.join(directory, 'source-alias'));
|
||||
assert.throws(
|
||||
() => new Coordinator({ workspaceRoot, stateDirectory: path.join(directory, 'source-alias', 'should-not-create') }),
|
||||
code('UNSAFE_STATE_PATH'),
|
||||
);
|
||||
assert.equal(fs.existsSync(path.join(workspaceRoot, 'should-not-create')), false);
|
||||
assert.throws(
|
||||
() =>
|
||||
engine.register('alice', 'a', {
|
||||
documents: [{ uri: pathToFileURL(path.join(directory, 'outside')).href, version: 1, dirty: false }],
|
||||
}),
|
||||
code('OUTSIDE_WORKSPACE'),
|
||||
);
|
||||
assert.throws(
|
||||
() => engine.register('alice', 'a', { documents: [{ uri: '../outside', version: 1, dirty: false }] }),
|
||||
code('OUTSIDE_WORKSPACE'),
|
||||
);
|
||||
engine.register('alice', 'a', clean());
|
||||
fs.writeFileSync(path.join(directory, 'secret'), 'not in source');
|
||||
fs.symlinkSync(path.join(directory, 'secret'), path.join(workspaceRoot, 'escape'));
|
||||
assert.throws(() => engine.beginBarrier('alice'), code('UNSAFE_WORKSPACE_PATH'));
|
||||
fs.unlinkSync(path.join(workspaceRoot, 'escape'));
|
||||
fs.symlinkSync(path.join(directory), path.join(workspaceRoot, 'escape-directory'));
|
||||
assert.throws(() => engine.beginBarrier('alice'), code('UNSAFE_WORKSPACE_PATH'));
|
||||
});
|
||||
|
||||
test('document input validation normalizes file URIs and refuses duplicate vectors', t => {
|
||||
const { coordinator: engine, workspaceRoot } = fixture(t);
|
||||
assert.throws(
|
||||
() => engine.register('alice', 'a', { documents: [{ uri: 'app.ts', version: NaN, dirty: false }] }),
|
||||
code('INVALID_INPUT'),
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
engine.register('alice', 'a', {
|
||||
documents: [
|
||||
{ uri: 'app.ts', version: 1, dirty: false },
|
||||
{ uri: pathToFileURL(path.join(workspaceRoot, 'app.ts')).href, version: 1, dirty: false },
|
||||
],
|
||||
}),
|
||||
code('INVALID_INPUT'),
|
||||
);
|
||||
const client = engine.register('alice', 'a', {
|
||||
documents: [
|
||||
{ uri: pathToFileURL(path.join(workspaceRoot, 'app.ts')).href, version: 1, dirty: false },
|
||||
{ uri: 'untitled:unsaved', version: 0, dirty: true },
|
||||
],
|
||||
});
|
||||
assert.equal(client.documents[0].uri, 'app.ts');
|
||||
assert.equal(client.dirty, true);
|
||||
});
|
||||
|
||||
test('expired clients and barriers cannot silently disappear into a successful snapshot', async t => {
|
||||
const { coordinator: engine, advance } = fixture(t);
|
||||
const barrier = acknowledged(engine);
|
||||
assert.throws(() => engine.beginBarrier('alice'), code('BARRIER_BUSY'));
|
||||
advance(CLIENT_TTL_MS);
|
||||
assert.deepEqual(engine.state().clients, []);
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_EXPIRED'));
|
||||
assert.throws(() => engine.beginBarrier('alice'), code('CLIENT_REQUIRED'));
|
||||
});
|
||||
|
||||
test('debug controller tokens are exclusive, redacted, renewable and expire exactly at deadline', t => {
|
||||
const { coordinator: engine, advance } = fixture(t);
|
||||
const lease = engine.debugAcquire('alice');
|
||||
assert.match(lease.token, /^[a-f0-9]{64}$/);
|
||||
assert.equal(engine.state().debugController.actorId, 'alice');
|
||||
assert.equal('token' in engine.state().debugController, false);
|
||||
assert.throws(() => engine.debugAcquire('bob'), code('DEBUG_BUSY'));
|
||||
assert.throws(() => engine.debugAcquire('alice'), code('DEBUG_BUSY'));
|
||||
assert.throws(() => engine.assertDebugController('bob', lease.token), code('DEBUG_FORBIDDEN'));
|
||||
advance(10_000);
|
||||
const renewed = engine.debugAcquire('alice', lease.token);
|
||||
assert.equal(renewed.token, lease.token);
|
||||
assert.equal(renewed.expiresAt, lease.expiresAt + 10_000);
|
||||
advance(DEBUG_LEASE_MS);
|
||||
assert.throws(() => engine.assertDebugController('alice', lease.token), code('DEBUG_FORBIDDEN'));
|
||||
const replacement = engine.debugAcquire('bob');
|
||||
assert.notEqual(replacement.token, lease.token);
|
||||
assert.throws(() => engine.debugRelease('alice', lease.token), code('DEBUG_FORBIDDEN'));
|
||||
engine.debugRelease('bob', replacement.token);
|
||||
assert.equal(engine.state().debugController, null);
|
||||
});
|
||||
|
||||
test('debug transfer rotates token and requires live target; revoke invalidates controller and barriers', async t => {
|
||||
const { coordinator: engine } = fixture(t);
|
||||
engine.register('alice', 'a', clean());
|
||||
engine.register('bob', 'b', clean());
|
||||
const lease = engine.debugAcquire('alice');
|
||||
assert.throws(() => engine.debugTransfer('alice', lease.token, 'unconnected'), code('CLIENT_REQUIRED'));
|
||||
const transferred = engine.debugTransfer('alice', lease.token, 'bob');
|
||||
assert.notEqual(transferred.token, lease.token);
|
||||
assert.throws(() => engine.assertDebugController('alice', lease.token), code('DEBUG_FORBIDDEN'));
|
||||
assert.throws(() => engine.assertDebugController('bob', lease.token), code('DEBUG_FORBIDDEN'));
|
||||
engine.assertDebugController('bob', transferred.token);
|
||||
const barrier = engine.beginBarrier('alice');
|
||||
engine.acknowledge('alice', barrier.id, 'a', clean());
|
||||
engine.acknowledge('bob', barrier.id, 'b', clean());
|
||||
engine.revoke('bob');
|
||||
assert.throws(() => engine.assertDebugController('bob', transferred.token), code('DEBUG_FORBIDDEN'));
|
||||
assert.equal(
|
||||
engine.state().clients.some(client => client.actorId === 'bob'),
|
||||
false,
|
||||
);
|
||||
await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID'));
|
||||
});
|
||||
|
||||
test('restart invalidates all prior debug tokens and barriers without overwriting source', async t => {
|
||||
const { coordinator: engine, options, workspaceRoot } = fixture(t);
|
||||
const barrier = acknowledged(engine);
|
||||
const lease = engine.debugAcquire('alice');
|
||||
const recovered = new Coordinator(options);
|
||||
await assert.rejects(recovered.commitBarrier('alice', barrier.id), code('BARRIER_NOT_FOUND'));
|
||||
assert.throws(() => recovered.assertDebugController('alice', lease.token), code('DEBUG_FORBIDDEN'));
|
||||
assert.equal(fs.readFileSync(path.join(workspaceRoot, 'app.ts'), 'utf8'), 'export const answer = 42;\n');
|
||||
});
|
||||
|
||||
test('integration state tracks dirty documents, membership and disk without treating heartbeats as edits', async t => {
|
||||
const { coordinator: engine, workspaceRoot, advance } = fixture(t);
|
||||
await engine.commitBarrier('alice', acknowledged(engine).id);
|
||||
const before = engine.inputState();
|
||||
assert.equal(before.currentDiskDigest, before.latestSnapshot.digest);
|
||||
advance(1000);
|
||||
engine.register('alice', 'alice-tab', clean());
|
||||
assert.equal(engine.inputState().activityDigest, before.activityDigest);
|
||||
engine.register('alice', 'alice-tab', dirty(2));
|
||||
assert.equal(engine.inputState().dirty, true);
|
||||
assert.notEqual(engine.inputState().activityDigest, before.activityDigest);
|
||||
engine.register('alice', 'alice-tab', clean());
|
||||
engine.register('bob', 'bob-tab', clean());
|
||||
assert.notEqual(engine.inputState().activityDigest, before.activityDigest);
|
||||
engine.unregister('bob', 'bob-tab');
|
||||
fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'changed on disk');
|
||||
assert.notEqual(engine.inputState().currentDiskDigest, before.currentDiskDigest);
|
||||
assert.equal(engine.inputState().latestSnapshot.digest, before.latestSnapshot.digest);
|
||||
});
|
||||
@ -1,5 +1,4 @@
|
||||
import { createGateway } from './server.mjs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const production = process.env.NODE_ENV === 'production';
|
||||
const publicUrl = process.env.WF_IDE_PUBLIC_URL ?? 'http://127.0.0.1:4400';
|
||||
@ -14,9 +13,6 @@ const gateway = createGateway({
|
||||
.filter(Boolean),
|
||||
allowedServiceNamespace: process.env.WF_IDE_ALLOWED_SERVICE_NAMESPACE,
|
||||
allowedCollaborationOrigins: (process.env.WF_COLLABORATION_ALLOWED_UPSTREAM_ORIGINS ?? '').split(',').filter(Boolean),
|
||||
assertionPrivateKey: process.env.WF_IDE_GATEWAY_PRIVATE_KEY_FILE
|
||||
? readFileSync(process.env.WF_IDE_GATEWAY_PRIVATE_KEY_FILE, 'utf8')
|
||||
: undefined,
|
||||
});
|
||||
gateway.server.listen(
|
||||
Number(process.env.WF_IDE_GATEWAY_PORT ?? 4400),
|
||||
|
||||
@ -2,11 +2,11 @@ import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { WebSocket, WebSocketServer } from 'ws';
|
||||
import assertions from '../security/assertions.cjs';
|
||||
|
||||
const COOKIE = 'WF_IDE_SESSION';
|
||||
const ID = /^[a-zA-Z0-9_-]{1,128}$/;
|
||||
const EDIT_ROLES = new Set(['owner', 'admin', 'maintainer', 'developer', 'editor']);
|
||||
// The roles defined by @wishforge/contracts that may edit, use terminals and debug.
|
||||
const EDIT_ROLES = new Set(['owner', 'admin', 'developer']);
|
||||
class HttpError extends Error {
|
||||
constructor(status, message) {
|
||||
super(message);
|
||||
@ -177,8 +177,6 @@ export function createGateway(config) {
|
||||
headers['x-forwarded-proto'] = publicUrl.protocol.slice(0, -1);
|
||||
headers['x-wishforge-tenant'] = grant.tenantId;
|
||||
headers['x-wishforge-workspace'] = grant.workspaceId;
|
||||
if (config.assertionPrivateKey)
|
||||
headers['x-wishforge-actor-assertion'] = assertions.signAssertion(config.assertionPrivateKey, grant);
|
||||
const token = upstreamTokens.get(grant.upstream.href);
|
||||
if (token) headers.cookie = `theia-connection-token=${token}`;
|
||||
return headers;
|
||||
@ -215,77 +213,24 @@ export function createGateway(config) {
|
||||
res.end('ok');
|
||||
return;
|
||||
}
|
||||
if (
|
||||
['/internal/integration-state', '/internal/lifecycle-state'].includes(url.pathname) &&
|
||||
req.method === 'POST'
|
||||
) {
|
||||
const lifecycle = url.pathname === '/internal/lifecycle-state';
|
||||
// The control plane asks whether a workspace is idle before pausing it automatically.
|
||||
// Only this gateway knows how many browser connections are open.
|
||||
if (url.pathname === '/internal/lifecycle-state' && req.method === 'POST') {
|
||||
const supplied = req.headers.authorization?.startsWith('Bearer ') ? req.headers.authorization.slice(7) : '';
|
||||
const expected = Buffer.from(config.serviceToken),
|
||||
actual = Buffer.from(supplied);
|
||||
if (actual.length !== expected.length || !timingSafeEqual(actual, expected) || !config.assertionPrivateKey)
|
||||
throw new HttpError(401, 'Integration service authentication required');
|
||||
if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
|
||||
throw new HttpError(401, 'Service authentication required');
|
||||
const body = await readJson(req);
|
||||
if (
|
||||
body.tenantId !== config.tenantId ||
|
||||
!ID.test(body.workspaceId ?? '') ||
|
||||
(!lifecycle && !ID.test(body.runId ?? ''))
|
||||
)
|
||||
throw new HttpError(400, 'Invalid integration scope');
|
||||
const authorized = await fetchImpl(
|
||||
`${config.apiOrigin}/internal/workspaces/${body.workspaceId}/${lifecycle ? 'lifecycle-authorize' : 'integration-authorize'}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${config.serviceToken}`,
|
||||
'content-type': 'application/json',
|
||||
'X-WishForge-Tenant': config.tenantId,
|
||||
},
|
||||
body: JSON.stringify(
|
||||
lifecycle ? {} : { runId: body.runId, generation: body.generation, revision: body.revision },
|
||||
),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(3000),
|
||||
},
|
||||
);
|
||||
if (!authorized.ok) throw new HttpError(403, 'Integration scope denied');
|
||||
const payload = await authorized.json();
|
||||
const grant = payload.data ?? payload;
|
||||
if (
|
||||
grant.tenantId !== config.tenantId ||
|
||||
grant.workspaceId !== body.workspaceId ||
|
||||
grant.purpose !== (lifecycle ? 'workspace-lifecycle' : 'integration-state')
|
||||
)
|
||||
throw new HttpError(403, 'Integration grant mismatch');
|
||||
const target = new URL(grant.upstreamUrl);
|
||||
const managed =
|
||||
serviceNamespace &&
|
||||
target.protocol === 'http:' &&
|
||||
target.port === '3000' &&
|
||||
new RegExp(`^wf-ide-[a-f0-9]{24}\\.${serviceNamespace}\\.svc(?:\\.cluster\\.local)?$`).test(target.hostname);
|
||||
if (
|
||||
(!upstreamOrigins.has(target.origin) && !managed) ||
|
||||
target.username ||
|
||||
target.password ||
|
||||
target.search ||
|
||||
target.hash
|
||||
)
|
||||
throw new HttpError(502, 'Integration upstream denied');
|
||||
const response = await fetchImpl(
|
||||
new URL(lifecycle ? '/_wishforge/lifecycle/state' : '/_wishforge/integration/state', target),
|
||||
{
|
||||
headers: { 'x-wishforge-actor-assertion': assertions.signAssertion(config.assertionPrivateKey, grant) },
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(10000),
|
||||
},
|
||||
);
|
||||
if (!response.ok) throw new HttpError(503, 'Workspace input state unavailable');
|
||||
if (body.tenantId !== config.tenantId || !ID.test(body.workspaceId ?? ''))
|
||||
throw new HttpError(400, 'Invalid workspace scope');
|
||||
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
||||
const receipt = await response.json();
|
||||
res.end(
|
||||
JSON.stringify(
|
||||
lifecycle ? { ...receipt, gatewayConnections: workspaceSockets.get(body.workspaceId)?.size ?? 0 } : receipt,
|
||||
),
|
||||
JSON.stringify({
|
||||
workspaceId: body.workspaceId,
|
||||
known: true,
|
||||
gatewayConnections: workspaceSockets.get(body.workspaceId)?.size ?? 0,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -4,15 +4,13 @@ import http from 'node:http';
|
||||
import { once } from 'node:events';
|
||||
import { WebSocket, WebSocketServer } from 'ws';
|
||||
import { createGateway } from '../server.mjs';
|
||||
import { generateKeyPairSync } from 'node:crypto';
|
||||
import assertions from '../../security/assertions.cjs';
|
||||
|
||||
async function listen(server) {
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
return `http://127.0.0.1:${server.address().port}`;
|
||||
}
|
||||
async function fixture(t, options = {}) {
|
||||
async function fixture(t) {
|
||||
const state = { revoked: false, role: 'developer', calls: [], receivedHeaders: undefined };
|
||||
const upstream = http.createServer((req, res) => {
|
||||
state.receivedHeaders = req.headers;
|
||||
@ -37,14 +35,7 @@ async function fixture(t, options = {}) {
|
||||
for await (const part of req) raw += part;
|
||||
const body = JSON.parse(raw);
|
||||
state.calls.push({ path: req.url, headers: req.headers, body });
|
||||
if (
|
||||
state.revoked ||
|
||||
(req.url.endsWith('/lifecycle-authorize')
|
||||
? false
|
||||
: req.url.endsWith('/integration-authorize')
|
||||
? body.runId !== 'run-1'
|
||||
: body.userToken !== 'user-token')
|
||||
) {
|
||||
if (state.revoked || body.userToken !== 'user-token') {
|
||||
res.writeHead(403);
|
||||
res.end();
|
||||
return;
|
||||
@ -58,11 +49,6 @@ async function fixture(t, options = {}) {
|
||||
workspaceId: 'w1',
|
||||
userId: 'authenticated-user',
|
||||
role: state.role,
|
||||
purpose: req.url.endsWith('/lifecycle-authorize')
|
||||
? 'workspace-lifecycle'
|
||||
: req.url.endsWith('/integration-authorize')
|
||||
? 'integration-state'
|
||||
: undefined,
|
||||
upstreamUrl: state.upstreamUrl,
|
||||
collaborationUpstreamUrl: state.collaborationUpstreamUrl,
|
||||
},
|
||||
@ -81,7 +67,6 @@ async function fixture(t, options = {}) {
|
||||
serviceToken: 'gateway-secret',
|
||||
allowedUpstreamOrigins: [upstreamUrl],
|
||||
allowedCollaborationOrigins: [upstreamUrl],
|
||||
assertionPrivateKey: options.privateKey,
|
||||
reauthorizeMs: 50,
|
||||
});
|
||||
gateway.server.listen(Number(new URL(publicUrl).port), '127.0.0.1');
|
||||
@ -178,20 +163,15 @@ test('preserves the upstream Theia process token server-side without forwarding
|
||||
assert.equal(f.state.receivedHeaders.cookie, 'theia-connection-token=server-only-process-token');
|
||||
});
|
||||
|
||||
test('gateway signs the API-authorized actor and strips forged workspace identity headers', async t => {
|
||||
const pair = generateKeyPairSync('ed25519');
|
||||
const f = await fixture(t, { privateKey: pair.privateKey.export({ type: 'pkcs8', format: 'pem' }) });
|
||||
test('strips caller-supplied workspace identity headers before reaching Theia', async t => {
|
||||
const f = await fixture(t);
|
||||
const s = await f.session();
|
||||
const response = await fetch(`${f.publicUrl}/workspaces/w1/`, {
|
||||
headers: { cookie: s.cookie, 'x-wishforge-actor-assertion': 'forged', 'x-wishforge-user': 'attacker' },
|
||||
headers: { cookie: s.cookie, 'x-wishforge-tenant': 'tenant-b', 'x-wishforge-user': 'attacker' },
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
const who = assertions.verifyAssertion(
|
||||
pair.publicKey.export({ type: 'spki', format: 'pem' }),
|
||||
f.state.receivedHeaders['x-wishforge-actor-assertion'],
|
||||
{ tenantId: 'tenant-a', workspaceId: 'w1' },
|
||||
);
|
||||
assert.equal(who.actorId, 'authenticated-user');
|
||||
assert.equal(f.state.receivedHeaders['x-wishforge-tenant'], 'tenant-a');
|
||||
assert.equal(f.state.receivedHeaders['x-wishforge-workspace'], 'w1');
|
||||
assert.equal(f.state.receivedHeaders['x-wishforge-user'], undefined);
|
||||
});
|
||||
|
||||
@ -245,62 +225,19 @@ test(
|
||||
},
|
||||
);
|
||||
|
||||
test('integration state relay is service authenticated, scope checked and purpose restricted', async t => {
|
||||
const pair = generateKeyPairSync('ed25519');
|
||||
const f = await fixture(t, { privateKey: pair.privateKey.export({ type: 'pkcs8', format: 'pem' }) });
|
||||
const request = (token, extra = {}) =>
|
||||
fetch(`${f.publicUrl}/internal/integration-state`, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
tenantId: 'tenant-a',
|
||||
workspaceId: 'w1',
|
||||
runId: 'run-1',
|
||||
revision: 1,
|
||||
generation: 'generation-one',
|
||||
...extra,
|
||||
}),
|
||||
});
|
||||
assert.equal((await request('user-token')).status, 401);
|
||||
assert.equal((await request('gateway-secret', { tenantId: 'tenant-b' })).status, 400);
|
||||
assert.equal((await request('gateway-secret', { runId: 'other-run' })).status, 403);
|
||||
const response = await request('gateway-secret');
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(await response.json(), { path: '/_wishforge/integration/state' });
|
||||
const token = f.state.receivedHeaders['x-wishforge-actor-assertion'];
|
||||
const key = pair.publicKey.export({ type: 'spki', format: 'pem' });
|
||||
assert.equal(
|
||||
assertions.verifyAssertion(key, token, { tenantId: 'tenant-a', workspaceId: 'w1', purpose: 'integration-state' })
|
||||
.purpose,
|
||||
'integration-state',
|
||||
);
|
||||
assert.throws(() => assertions.verifyAssertion(key, token, { tenantId: 'tenant-a', workspaceId: 'w1' }), /PURPOSE/);
|
||||
f.state.upstreamUrl = 'http://169.254.169.254/';
|
||||
assert.equal((await request('gateway-secret')).status, 502);
|
||||
f.state.revoked = true;
|
||||
assert.equal((await request('gateway-secret')).status, 403);
|
||||
});
|
||||
|
||||
test('lifecycle inspection is read-only scoped and accounts for every live workspace socket', async t => {
|
||||
const pair = generateKeyPairSync('ed25519');
|
||||
const f = await fixture(t, { privateKey: pair.privateKey.export({ type: 'pkcs8', format: 'pem' }) });
|
||||
const inspect = () =>
|
||||
test('lifecycle inspection is service authenticated, scoped, and counts every live workspace socket', async t => {
|
||||
const f = await fixture(t);
|
||||
const inspect = (token = 'gateway-secret', tenantId = 'tenant-a') =>
|
||||
fetch(`${f.publicUrl}/internal/lifecycle-state`, {
|
||||
method: 'POST',
|
||||
headers: { authorization: 'Bearer gateway-secret', 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ tenantId: 'tenant-a', workspaceId: 'w1' }),
|
||||
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ tenantId, workspaceId: 'w1' }),
|
||||
});
|
||||
assert.equal((await inspect('user-token')).status, 401);
|
||||
assert.equal((await inspect('gateway-secret', 'tenant-b')).status, 400);
|
||||
let response = await inspect();
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(await response.json(), { path: '/_wishforge/lifecycle/state', gatewayConnections: 0 });
|
||||
const key = pair.publicKey.export({ type: 'spki', format: 'pem' });
|
||||
const token = f.state.receivedHeaders['x-wishforge-actor-assertion'];
|
||||
assert.equal(
|
||||
assertions.verifyAssertion(key, token, { tenantId: 'tenant-a', workspaceId: 'w1', purpose: 'workspace-lifecycle' })
|
||||
.purpose,
|
||||
'workspace-lifecycle',
|
||||
);
|
||||
assert.throws(() => assertions.verifyAssertion(key, token, { tenantId: 'tenant-a', workspaceId: 'w1' }), /PURPOSE/);
|
||||
assert.deepEqual(await response.json(), { workspaceId: 'w1', known: true, gatewayConnections: 0 });
|
||||
const session = await f.session();
|
||||
const ws = new WebSocket(`${f.publicUrl.replace('http:', 'ws:')}/workspaces/w1/services`, {
|
||||
origin: f.publicUrl,
|
||||
|
||||
@ -9,7 +9,7 @@
|
||||
"build": "theia build --mode development",
|
||||
"build:production": "theia build --mode production",
|
||||
"start": "node scripts/start.mjs",
|
||||
"test": "node --test gateway/test/*.test.mjs provisioner/test/*.test.mjs coordination/test/*.test.cjs security/test/*.test.cjs policy/test/*.test.cjs collaboration/test/client-factory.test.cjs",
|
||||
"test": "node --test gateway/test/*.test.mjs provisioner/test/*.test.mjs policy/test/*.test.cjs collaboration/test/client-factory.test.cjs",
|
||||
"plugins:download": "theia download:plugins && node scripts/download-python-debugger.mjs && node scripts/verify-managed-plugins.mjs",
|
||||
"plugins:download:python": "node scripts/download-python-debugger.mjs",
|
||||
"plugins:verify": "node scripts/verify-managed-plugins.mjs"
|
||||
|
||||
@ -1,299 +1,7 @@
|
||||
const { ContainerModule, injectable, inject } = require('@theia/core/shared/inversify');
|
||||
const { ConnectionContainerModule } = require('@theia/core/lib/node/messaging/connection-container-module');
|
||||
const { MainChannel, DefaultMessagingService } = require('@theia/core/lib/node/messaging/default-messaging-service');
|
||||
const { DebugService } = require('@theia/debug/lib/common/debug-service');
|
||||
const { DebugServiceImpl } = require('@theia/debug/lib/node/debug-service-impl');
|
||||
const { DebugAdapterSessionManager } = require('@theia/debug/lib/node/debug-adapter-session-manager');
|
||||
const { ForwardingDebugChannel } = require('@theia/debug/lib/common/debug-service');
|
||||
const { HostedPluginProcess } = require('@theia/plugin-ext/lib/hosted/node/hosted-plugin-process');
|
||||
const { ProcessManager } = require('@theia/process/lib/node/process-manager');
|
||||
const { sleepReceipt } = require('./lifecycle-safety.cjs');
|
||||
const { BackendApplicationContribution } = require('@theia/core/lib/node/backend-application');
|
||||
const { filterPluginRpc, guardDebugChannel } = require('./plugin-dap-guard.cjs');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { randomUUID, createHash } = require('node:crypto');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
const { verifyAssertion } = require('../security/assertions.cjs');
|
||||
const { Coordinator } = require('../coordination/index.cjs');
|
||||
const Context = Symbol('WishForgeConnectionContext'),
|
||||
Service = Symbol('WishForgeCoordinatorService');
|
||||
const connections = new Map();
|
||||
let engine;
|
||||
let snapshotPending = false;
|
||||
let hostedDebugTouched = false;
|
||||
function coordinator() {
|
||||
if (!engine) {
|
||||
for (const name of [
|
||||
'WISHFORGE_WORKSPACE_PATH',
|
||||
'WF_COORDINATION_STATE_DIR',
|
||||
'WF_WORKSPACE_ID',
|
||||
'WF_TENANT_ID',
|
||||
'WF_IDE_GATEWAY_PUBLIC_KEY_FILE',
|
||||
])
|
||||
if (!process.env[name]) throw new Error(`COORDINATION_UNCONFIGURED: ${name}`);
|
||||
engine = new Coordinator({
|
||||
workspaceRoot: process.env.WISHFORGE_WORKSPACE_PATH,
|
||||
stateDirectory: process.env.WF_COORDINATION_STATE_DIR,
|
||||
});
|
||||
}
|
||||
return engine;
|
||||
}
|
||||
function actor(channel) {
|
||||
coordinator();
|
||||
return verifyAssertion(
|
||||
fs.readFileSync(process.env.WF_IDE_GATEWAY_PUBLIC_KEY_FILE, 'utf8'),
|
||||
channel.socket?.request?.headers?.['x-wishforge-actor-assertion'],
|
||||
{ tenantId: process.env.WF_TENANT_ID, workspaceId: process.env.WF_WORKSPACE_ID },
|
||||
);
|
||||
}
|
||||
function checkControl(context) {
|
||||
const who = actor(context.channel);
|
||||
coordinator().assertDebugController(who.actorId, context.debugToken);
|
||||
return who;
|
||||
}
|
||||
const timeout = promise =>
|
||||
Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(new Error('EDITOR_ACK_TIMEOUT')), 10000))]);
|
||||
class CoordinationService {
|
||||
constructor(context) {
|
||||
this.context = context;
|
||||
}
|
||||
register(documents) {
|
||||
const who = actor(this.context.channel);
|
||||
this.context.actorId = who.actorId;
|
||||
coordinator().register(who.actorId, this.context.id, { documents });
|
||||
return {
|
||||
actorId: who.actorId,
|
||||
clientId: this.context.id,
|
||||
workspaceId: who.workspaceId,
|
||||
workspaceRoot: process.env.WISHFORGE_WORKSPACE_PATH,
|
||||
state: coordinator().state(),
|
||||
};
|
||||
}
|
||||
status() {
|
||||
actor(this.context.channel);
|
||||
return coordinator().state();
|
||||
}
|
||||
async snapshot() {
|
||||
const who = actor(this.context.channel);
|
||||
const participants = [...connections.values()];
|
||||
if (snapshotPending) throw new Error('BARRIER_BUSY');
|
||||
snapshotPending = true;
|
||||
const requestClient = `snapshot-request-${randomUUID()}`;
|
||||
const prepared = [];
|
||||
try {
|
||||
for (const entry of participants) {
|
||||
const identity = actor(entry.channel);
|
||||
const documents = await timeout(entry.frontend.prepareSnapshot());
|
||||
coordinator().register(identity.actorId, entry.id, { documents });
|
||||
prepared.push({ entry, identity, documents });
|
||||
}
|
||||
coordinator().register(who.actorId, requestClient, { documents: [] });
|
||||
const barrier = coordinator().beginBarrier(who.actorId);
|
||||
coordinator().acknowledge(who.actorId, barrier.id, requestClient, { documents: [] });
|
||||
for (const { entry, identity, documents } of prepared) {
|
||||
const confirmed = await timeout(entry.frontend.confirmSnapshot(documents));
|
||||
coordinator().acknowledge(identity.actorId, barrier.id, entry.id, { documents: confirmed });
|
||||
}
|
||||
return await coordinator().commitBarrier(who.actorId, barrier.id);
|
||||
} finally {
|
||||
coordinator().unregister(who.actorId, requestClient);
|
||||
await Promise.allSettled(participants.map(entry => timeout(entry.frontend.releaseSnapshot())));
|
||||
snapshotPending = false;
|
||||
}
|
||||
}
|
||||
readSaved(relative) {
|
||||
actor(this.context.channel);
|
||||
const root = fs.realpathSync(process.env.WISHFORGE_WORKSPACE_PATH);
|
||||
if (typeof relative !== 'string' || !relative || path.isAbsolute(relative))
|
||||
throw new Error('INVALID_DOCUMENT_PATH');
|
||||
const file = fs.realpathSync(path.resolve(root, relative));
|
||||
if (!file.startsWith(root + path.sep) || fs.statSync(file).size > 4 * 1024 * 1024)
|
||||
throw new Error('DOCUMENT_SCOPE');
|
||||
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
||||
let content;
|
||||
try {
|
||||
const info = fs.fstatSync(fd);
|
||||
if (!info.isFile() || info.size > 4 * 1024 * 1024) throw new Error('DOCUMENT_SCOPE');
|
||||
content = fs.readFileSync(fd, 'utf8');
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
return { content, digest: createHash('sha256').update(content).digest('hex'), uri: pathToFileURL(file).href };
|
||||
}
|
||||
acquireDebug() {
|
||||
const who = actor(this.context.channel);
|
||||
this.context.actorId = who.actorId;
|
||||
const lease = coordinator().debugAcquire(who.actorId, this.context.debugToken);
|
||||
this.context.debugToken = lease.token;
|
||||
return { actorId: lease.actorId, expiresAt: lease.expiresAt };
|
||||
}
|
||||
releaseDebug() {
|
||||
const who = actor(this.context.channel);
|
||||
if (this.context.debugToken) coordinator().debugRelease(who.actorId, this.context.debugToken);
|
||||
this.context.debugToken = undefined;
|
||||
return true;
|
||||
}
|
||||
async transferDebug(targetClientId) {
|
||||
const who = actor(this.context.channel);
|
||||
const target = connections.get(targetClientId);
|
||||
if (!target) throw new Error('TARGET_NOT_CONNECTED');
|
||||
const identity = actor(target.channel);
|
||||
const lease = coordinator().debugTransfer(who.actorId, this.context.debugToken, identity.actorId);
|
||||
target.debugToken = lease.token;
|
||||
this.context.debugToken = undefined;
|
||||
target.frontend.debugGranted().catch(() => {});
|
||||
return { actorId: identity.actorId, clientId: target.id };
|
||||
}
|
||||
peers() {
|
||||
actor(this.context.channel);
|
||||
return [...connections.values()].map(entry => ({ clientId: entry.id, actorId: actor(entry.channel).actorId }));
|
||||
}
|
||||
}
|
||||
class IntegrationHttp {
|
||||
configure(app) {
|
||||
const identity = (req, purpose) =>
|
||||
verifyAssertion(
|
||||
fs.readFileSync(process.env.WF_IDE_GATEWAY_PUBLIC_KEY_FILE, 'utf8'),
|
||||
req.headers['x-wishforge-actor-assertion'],
|
||||
{ tenantId: process.env.WF_TENANT_ID, workspaceId: process.env.WF_WORKSPACE_ID, purpose },
|
||||
);
|
||||
app.get('/_wishforge/lifecycle/state', (req, res) => {
|
||||
try {
|
||||
identity(req, 'workspace-lifecycle');
|
||||
res.set('Cache-Control', 'no-store').json({
|
||||
workspaceId: process.env.WF_WORKSPACE_ID,
|
||||
...sleepReceipt({
|
||||
coordinator: coordinator(),
|
||||
processManager: this.processManager,
|
||||
debugManager: this.debugManager,
|
||||
snapshotPending,
|
||||
hostedDebugTouched,
|
||||
}),
|
||||
});
|
||||
} catch {
|
||||
res.status(409).json({ error: 'WORKSPACE_ACTIVITY_UNKNOWN' });
|
||||
}
|
||||
});
|
||||
app.get('/_wishforge/integration/state', (req, res) => {
|
||||
try {
|
||||
identity(req, 'integration-state');
|
||||
res
|
||||
.set('Cache-Control', 'no-store')
|
||||
.json({ workspaceId: process.env.WF_WORKSPACE_ID, ...coordinator().inputState() });
|
||||
} catch {
|
||||
res.status(409).json({ error: 'WORKSPACE_INPUT_UNAVAILABLE' });
|
||||
}
|
||||
});
|
||||
app.post('/_wishforge/integration/snapshot', async (req, res) => {
|
||||
try {
|
||||
identity(req, 'interactive');
|
||||
const service = new CoordinationService({ channel: { socket: { request: req } } });
|
||||
await service.snapshot();
|
||||
res
|
||||
.set('Cache-Control', 'no-store')
|
||||
.json({ workspaceId: process.env.WF_WORKSPACE_ID, ...coordinator().inputState() });
|
||||
} catch (error) {
|
||||
res.status(409).json({ error: 'WORKSPACE_SAVE_BARRIER_REQUIRED', message: error.message });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
injectable()(IntegrationHttp);
|
||||
inject(ProcessManager)(IntegrationHttp.prototype, 'processManager');
|
||||
inject(DebugAdapterSessionManager)(IntegrationHttp.prototype, 'debugManager');
|
||||
|
||||
// Native debug adapters: no command reaches the adapter without the server lease.
|
||||
class ScopedMessagingService extends DefaultMessagingService {
|
||||
getConnectionChannelHandlers(channel) {
|
||||
const handlers = super.getConnectionChannelHandlers(channel);
|
||||
handlers.push('/services/debug-adapter/:id', ({ id }, wsChannel) => {
|
||||
try {
|
||||
const context = channel.wishforgeContext;
|
||||
const session = this.container.get(DebugAdapterSessionManager).find(id);
|
||||
if (!session || !context) {
|
||||
wsChannel.close();
|
||||
return;
|
||||
}
|
||||
session.start(guardDebugChannel(new ForwardingDebugChannel(wsChannel), () => checkControl(context)));
|
||||
} catch {
|
||||
wsChannel.close();
|
||||
}
|
||||
});
|
||||
return handlers;
|
||||
}
|
||||
}
|
||||
injectable()(ScopedMessagingService);
|
||||
class ScopedDebugService extends DebugServiceImpl {
|
||||
async createDebugSession(...args) {
|
||||
checkControl(this.context);
|
||||
return super.createDebugSession(...args);
|
||||
}
|
||||
async terminateDebugSession(...args) {
|
||||
checkControl(this.context);
|
||||
return super.terminateDebugSession(...args);
|
||||
}
|
||||
dispose() {
|
||||
super.terminateDebugSession().catch(() => {});
|
||||
}
|
||||
}
|
||||
injectable()(ScopedDebugService);
|
||||
inject(Context)(ScopedDebugService.prototype, 'context');
|
||||
|
||||
// VS Code/js-debug adapters use a different channel inside hosted-plugin RPC.
|
||||
// Gate those requests on the backend before any payload reaches the plugin host.
|
||||
class ScopedHostedPluginProcess extends HostedPluginProcess {
|
||||
onMessage(hostId, payload) {
|
||||
try {
|
||||
const result = filterPluginRpc(payload, () => {
|
||||
checkControl(this.context);
|
||||
hostedDebugTouched = true;
|
||||
});
|
||||
if (result.denied) this.logger.warn('WishForge debug control denied', result.denied);
|
||||
if (result.replies) this.client?.postMessage(hostId, result.replies);
|
||||
if (result.forwarded) super.onMessage(hostId, result.forwarded);
|
||||
} catch (error) {
|
||||
this.logger.error('WishForge rejected malformed plugin RPC', error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
injectable()(ScopedHostedPluginProcess);
|
||||
inject(Context)(ScopedHostedPluginProcess.prototype, 'context');
|
||||
const { ContainerModule } = require('@theia/core/shared/inversify');
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
exports.default = new ContainerModule((bind, _unbind, _isBound, rebind) => {
|
||||
|
||||
// Only operator-pinned, digest-verified extensions may be installed (see managed-plugins.cjs).
|
||||
exports.default = new ContainerModule((_bind, _unbind, _isBound, rebind) => {
|
||||
require('./plugin-install-policy.cjs').bindManagedPlugins(rebind);
|
||||
bind(IntegrationHttp).toSelf().inSingletonScope();
|
||||
bind(BackendApplicationContribution).toService(IntegrationHttp);
|
||||
rebind(DefaultMessagingService).to(ScopedMessagingService).inSingletonScope();
|
||||
bind(ConnectionContainerModule).toConstantValue(
|
||||
ConnectionContainerModule.create(({ bind, rebind, bindBackendService }) => {
|
||||
bind(Context)
|
||||
.toDynamicValue(ctx => {
|
||||
const channel = ctx.container.get(MainChannel);
|
||||
const context = { id: randomUUID(), channel };
|
||||
channel.wishforgeContext = context;
|
||||
channel.onClose(() => {
|
||||
connections.delete(context.id);
|
||||
try {
|
||||
if (context.actorId) {
|
||||
coordinator().unregister(context.actorId, context.id);
|
||||
if (context.debugToken) coordinator().debugRelease(context.actorId, context.debugToken);
|
||||
}
|
||||
} catch {}
|
||||
});
|
||||
return context;
|
||||
})
|
||||
.inSingletonScope();
|
||||
bind(Service)
|
||||
.toDynamicValue(ctx => new CoordinationService(ctx.container.get(Context)))
|
||||
.inSingletonScope();
|
||||
bindBackendService('/services/wishforge-coordination', Service, (service, frontend) => {
|
||||
service.context.frontend = frontend;
|
||||
connections.set(service.context.id, service.context);
|
||||
return service;
|
||||
});
|
||||
rebind(DebugService).to(ScopedDebugService).inSingletonScope();
|
||||
rebind(HostedPluginProcess).to(ScopedHostedPluginProcess).inSingletonScope();
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@ -1,306 +0,0 @@
|
||||
const { FrontendApplicationContribution, ApplicationShell, OpenerService, open } = require('@theia/core/lib/browser');
|
||||
const {
|
||||
CommandContribution,
|
||||
MessageService,
|
||||
QuickInputService,
|
||||
UntitledResourceResolver,
|
||||
URI,
|
||||
} = require('@theia/core');
|
||||
const { EditorManager } = require('@theia/editor/lib/browser');
|
||||
const { WorkspaceService } = require('@theia/workspace/lib/browser');
|
||||
const { WebSocketConnectionProvider } = require('@theia/core/lib/browser/messaging/ws-connection-provider');
|
||||
const { StatusBar, StatusBarAlignment } = require('@theia/core/lib/browser/status-bar/status-bar');
|
||||
const { DiffUris } = require('@theia/core/lib/browser/diff-uris');
|
||||
const { DraftStore } = require('./drafts.cjs');
|
||||
const Service = Symbol('WishForgeFrontendCoordination');
|
||||
const vector = documents =>
|
||||
JSON.stringify(
|
||||
documents.map(d => ({ uri: d.uri, version: d.version, dirty: d.dirty })).sort((a, b) => a.uri.localeCompare(b.uri)),
|
||||
);
|
||||
|
||||
class FrontendCoordination {
|
||||
constructor(services) {
|
||||
Object.assign(this, services);
|
||||
this.drafts = new DraftStore(window.indexedDB);
|
||||
this.tracked = new Map();
|
||||
this.frozen = new Map();
|
||||
this.controller = false;
|
||||
this.busy = false;
|
||||
this.draftWarning = false;
|
||||
}
|
||||
documents() {
|
||||
const documents = new Map();
|
||||
for (const widget of this.editors.all) {
|
||||
const doc = {
|
||||
uri: widget.editor.uri.toString(),
|
||||
version: widget.editor.document.version,
|
||||
dirty: widget.editor.document.dirty,
|
||||
};
|
||||
const previous = documents.get(doc.uri);
|
||||
if (previous && previous.version !== doc.version) throw new Error('Conflicting editor versions for one document');
|
||||
documents.set(doc.uri, { ...doc, dirty: doc.dirty || previous?.dirty === true });
|
||||
}
|
||||
return [...documents.values()];
|
||||
}
|
||||
async onStart() {
|
||||
this.rpc = this.connection.createProxy('/services/wishforge-coordination', {
|
||||
prepareSnapshot: () => this.prepareSnapshot(),
|
||||
confirmSnapshot: docs => this.confirmSnapshot(docs),
|
||||
releaseSnapshot: () => this.releaseSnapshot(),
|
||||
debugGranted: () => {
|
||||
this.controller = true;
|
||||
return this.heartbeat();
|
||||
},
|
||||
});
|
||||
this.rpc.onDidCloseConnection?.(() => {
|
||||
this.releaseSnapshot();
|
||||
this.controller = false;
|
||||
});
|
||||
this.editors.onCreated(widget => this.track(widget));
|
||||
for (const widget of this.editors.all) this.track(widget);
|
||||
await this.heartbeat();
|
||||
this.timer = setInterval(() => this.heartbeat(), 5000);
|
||||
window.addEventListener('pagehide', () => {
|
||||
for (const widget of this.editors.all) this.persistDraft(widget);
|
||||
});
|
||||
}
|
||||
async heartbeat() {
|
||||
try {
|
||||
this.identity = await this.rpc.register(this.documents());
|
||||
this.scope = `${this.identity.workspaceId}/${this.identity.actorId}`;
|
||||
if (this.controller) await this.rpc.acquireDebug();
|
||||
const state = await this.rpc.status();
|
||||
this.status.setElement('wishforge-coordination', {
|
||||
text: `$(cloud-upload) Saved r${state.revision}${this.controller ? ' · Debug control' : ''}`,
|
||||
alignment: StatusBarAlignment.RIGHT,
|
||||
priority: 5,
|
||||
tooltip: 'WishForge coordinated snapshot and draft recovery',
|
||||
command: 'wishforge.snapshot',
|
||||
});
|
||||
if (!this.recoveryNotified) {
|
||||
this.recoveryNotified = true;
|
||||
const saved = await this.drafts.list(this.scope);
|
||||
if (saved.length)
|
||||
this.messages.info(
|
||||
`${saved.length} unconfirmed draft(s) are available. Use WishForge: Recover Unsaved Draft to compare them with saved files.`,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
this.controller = false;
|
||||
this.status.setElement('wishforge-coordination', {
|
||||
text: '$(warning) Coordination unavailable',
|
||||
alignment: StatusBarAlignment.RIGHT,
|
||||
priority: 5,
|
||||
tooltip: 'Snapshots and debug control require authenticated workspace coordination.',
|
||||
});
|
||||
}
|
||||
}
|
||||
pathFor(widget) {
|
||||
const current = widget.editor.uri;
|
||||
for (const root of this.workspace.tryGetRoots()) {
|
||||
const prefix = root.resource.path.toString().replace(/\/$/, '') + '/';
|
||||
if (current.scheme === root.resource.scheme && current.path.toString().startsWith(prefix))
|
||||
return current.path.toString().slice(prefix.length);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
track(widget) {
|
||||
if (this.tracked.has(widget)) return;
|
||||
const state = {
|
||||
id: window.crypto.randomUUID(),
|
||||
baseText: widget.editor.document.getText(),
|
||||
wasDirty: widget.editor.document.dirty,
|
||||
};
|
||||
this.tracked.set(widget, state);
|
||||
const change = () => {
|
||||
if (!state.timer)
|
||||
state.timer = setTimeout(() => {
|
||||
state.timer = undefined;
|
||||
this.persistDraft(widget);
|
||||
}, 120);
|
||||
this.rpc?.register(this.documents()).catch(() => {});
|
||||
};
|
||||
widget.editor.document.onContentChanged(change);
|
||||
widget.editor.document.onDirtyChanged(change);
|
||||
if (this.busy) this.freeze(widget);
|
||||
}
|
||||
async persistDraft(widget) {
|
||||
const state = this.tracked.get(widget);
|
||||
if (!state || !this.scope) return;
|
||||
const doc = widget.editor.document;
|
||||
const relative = this.pathFor(widget);
|
||||
if (!relative) return;
|
||||
try {
|
||||
if (doc.dirty) {
|
||||
state.wasDirty = true;
|
||||
await this.drafts.put({
|
||||
id: state.id,
|
||||
scope: this.scope,
|
||||
path: relative,
|
||||
uri: widget.editor.uri.toString(),
|
||||
text: doc.getText(),
|
||||
baseText: state.baseText,
|
||||
version: doc.version,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
} else if (state.wasDirty) {
|
||||
await this.drafts.remove(state.id);
|
||||
state.baseText = doc.getText();
|
||||
state.wasDirty = false;
|
||||
}
|
||||
} catch (error) {
|
||||
if (!this.draftWarning) {
|
||||
this.draftWarning = true;
|
||||
this.messages.warn(`Draft recovery storage unavailable: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
freeze(widget) {
|
||||
if (this.frozen.has(widget)) return;
|
||||
const control = widget.editor.getControl?.();
|
||||
if (!control?.updateOptions) throw new Error('This editor cannot be frozen for a coordinated snapshot');
|
||||
const previous = control.getRawOptions?.().readOnly ?? widget.editor.readOnly ?? false;
|
||||
this.frozen.set(widget, { control, previous });
|
||||
control.updateOptions({ readOnly: true });
|
||||
}
|
||||
async prepareSnapshot() {
|
||||
if (this.busy) throw new Error('Editor is already participating in a save barrier');
|
||||
this.busy = true;
|
||||
for (const w of this.editors.all) this.freeze(w);
|
||||
try {
|
||||
await this.shell.saveAll();
|
||||
const docs = this.documents();
|
||||
if (docs.some(doc => doc.dirty)) throw new Error('Unconfirmed or unsaved documents prevent the snapshot');
|
||||
return docs;
|
||||
} catch (error) {
|
||||
this.releaseSnapshot();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
confirmSnapshot(expected) {
|
||||
const docs = this.documents();
|
||||
if (!this.busy || vector(docs) !== vector(expected) || docs.some(doc => doc.dirty))
|
||||
throw new Error('Document versions changed during the save barrier');
|
||||
return docs;
|
||||
}
|
||||
releaseSnapshot() {
|
||||
for (const { control, previous } of this.frozen.values()) control.updateOptions({ readOnly: previous });
|
||||
this.frozen.clear();
|
||||
this.busy = false;
|
||||
return true;
|
||||
}
|
||||
registerCommands(commands) {
|
||||
commands.registerCommand(
|
||||
{ id: 'wishforge.snapshot', label: 'Create Verified Workspace Snapshot', category: 'WishForge' },
|
||||
{
|
||||
execute: async () => {
|
||||
try {
|
||||
const snapshot = await this.rpc.snapshot();
|
||||
await this.heartbeat();
|
||||
this.messages.info(`Saved workspace revision ${snapshot.revision} (${snapshot.digest.slice(0, 12)}).`);
|
||||
} catch (error) {
|
||||
this.messages.error(`Snapshot refused: ${error.message}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
commands.registerCommand(
|
||||
{ id: 'wishforge.recover-draft', label: 'Recover Unsaved Draft', category: 'WishForge' },
|
||||
{ execute: () => this.recover() },
|
||||
);
|
||||
commands.registerCommand(
|
||||
{ id: 'wishforge.debug-acquire', label: 'Acquire Debug Control', category: 'WishForge' },
|
||||
{
|
||||
execute: async () => {
|
||||
try {
|
||||
await this.rpc.acquireDebug();
|
||||
this.controller = true;
|
||||
await this.heartbeat();
|
||||
this.messages.info('Debug control acquired for this client.');
|
||||
} catch (error) {
|
||||
this.messages.error(error.message);
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
commands.registerCommand(
|
||||
{ id: 'wishforge.debug-release', label: 'Release Debug Control', category: 'WishForge' },
|
||||
{
|
||||
execute: async () => {
|
||||
await this.rpc.releaseDebug();
|
||||
this.controller = false;
|
||||
await this.heartbeat();
|
||||
},
|
||||
},
|
||||
);
|
||||
commands.registerCommand(
|
||||
{ id: 'wishforge.debug-transfer', label: 'Transfer Debug Control', category: 'WishForge' },
|
||||
{
|
||||
execute: async () => {
|
||||
try {
|
||||
const peers = (await this.rpc.peers()).filter(p => p.clientId !== this.identity?.clientId);
|
||||
const picked = await this.quick.pick(
|
||||
peers.map(p => ({ label: p.actorId, description: p.clientId, value: p.clientId })),
|
||||
{ title: 'Transfer control to a connected workspace client' },
|
||||
);
|
||||
if (picked) {
|
||||
await this.rpc.transferDebug(picked.value);
|
||||
this.controller = false;
|
||||
await this.heartbeat();
|
||||
}
|
||||
} catch (error) {
|
||||
this.messages.error(error.message);
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
async recover() {
|
||||
try {
|
||||
if (!this.scope) throw new Error('Authenticated workspace identity unavailable');
|
||||
const records = await this.drafts.list(this.scope);
|
||||
const picked = await this.quick.pick(
|
||||
records.map(record => ({
|
||||
label: record.path,
|
||||
description: new Date(record.updatedAt).toLocaleString(),
|
||||
record,
|
||||
})),
|
||||
{ title: 'Compare an unconfirmed draft with the saved file' },
|
||||
);
|
||||
if (!picked) return;
|
||||
const draft = picked.record;
|
||||
const saved = await this.rpc.readSaved(draft.path);
|
||||
const resource = await this.untitled.createUntitledResource(draft.text, draft.path.split('.').at(-1));
|
||||
const left = new URI('mem-txt-readonly:/Saved-file').withQuery(saved.content);
|
||||
await open(this.opener, DiffUris.encode(left, resource.uri, `Saved ↔ recovered ${draft.path}`));
|
||||
this.messages.info(
|
||||
saved.content === draft.baseText
|
||||
? 'Draft opened as an unsaved recovery copy. Review and Save As to apply it.'
|
||||
: 'The saved file changed after this draft. Review the comparison before applying the recovery copy.',
|
||||
);
|
||||
} catch (error) {
|
||||
this.messages.error(`Draft recovery: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
function bindCoordination(bind) {
|
||||
bind(Service)
|
||||
.toDynamicValue(
|
||||
ctx =>
|
||||
new FrontendCoordination({
|
||||
editors: ctx.container.get(EditorManager),
|
||||
workspace: ctx.container.get(WorkspaceService),
|
||||
shell: ctx.container.get(ApplicationShell),
|
||||
messages: ctx.container.get(MessageService),
|
||||
quick: ctx.container.get(QuickInputService),
|
||||
untitled: ctx.container.get(UntitledResourceResolver),
|
||||
opener: ctx.container.get(OpenerService),
|
||||
connection: ctx.container.get(WebSocketConnectionProvider),
|
||||
status: ctx.container.get(StatusBar),
|
||||
}),
|
||||
)
|
||||
.inSingletonScope();
|
||||
bind(FrontendApplicationContribution).toService(Service);
|
||||
bind(CommandContribution).toService(Service);
|
||||
}
|
||||
module.exports = { bindCoordination, FrontendCoordination };
|
||||
@ -1,46 +0,0 @@
|
||||
class DraftStore {
|
||||
constructor(indexedDB) {
|
||||
this.indexedDB = indexedDB;
|
||||
}
|
||||
async database() {
|
||||
if (!this.pending)
|
||||
this.pending = new Promise((resolve, reject) => {
|
||||
const request = this.indexedDB.open('wishforge-unconfirmed-drafts', 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore('drafts', { keyPath: 'id' });
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
return this.pending;
|
||||
}
|
||||
async operation(mode, action) {
|
||||
const db = await this.database();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction('drafts', mode);
|
||||
const request = action(tx.objectStore('drafts'));
|
||||
let value;
|
||||
request.onsuccess = () => {
|
||||
value = request.result;
|
||||
};
|
||||
tx.oncomplete = () => resolve(value);
|
||||
tx.onerror = () => reject(tx.error);
|
||||
tx.onabort = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
put(record) {
|
||||
if (
|
||||
record.text.length + record.baseText.length > 2 * 1024 * 1024 ||
|
||||
new TextEncoder().encode(record.text + record.baseText).byteLength > 2 * 1024 * 1024
|
||||
)
|
||||
throw new Error('Draft exceeds the 2 MiB local recovery limit');
|
||||
return this.operation('readwrite', store => store.put(record));
|
||||
}
|
||||
remove(id) {
|
||||
return this.operation('readwrite', store => store.delete(id));
|
||||
}
|
||||
async list(scope) {
|
||||
return (await this.operation('readonly', store => store.getAll()))
|
||||
.filter(record => record.scope === scope)
|
||||
.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
}
|
||||
}
|
||||
module.exports = { DraftStore };
|
||||
@ -54,7 +54,6 @@ class DedicatedWorkspaceService extends CollaborationWorkspaceService {
|
||||
injectable()(DedicatedWorkspaceService);
|
||||
module.exports.default = new ContainerModule((_bind, _unbind, _isBound, rebind) => {
|
||||
require('./plugin-install-frontend.cjs').bindManagedExtensionNotice(_bind);
|
||||
require('./coordination-frontend.cjs').bindCoordination(_bind);
|
||||
rebind(CollaborationWorkspaceService).to(DedicatedWorkspaceService).inSingletonScope();
|
||||
rebind(CollaborationFrontendContribution).to(ScopedCollaborationContribution).inSingletonScope();
|
||||
});
|
||||
|
||||
@ -1,26 +0,0 @@
|
||||
'use strict';
|
||||
/** Pinned Theia 1.76 seam. Unknown process/debug inventory is never idle evidence. */
|
||||
function sleepReceipt({ coordinator, processManager, debugManager, snapshotPending, hostedDebugTouched }) {
|
||||
try {
|
||||
if (!(processManager?.processes instanceof Map) || typeof debugManager?.getAll !== 'function')
|
||||
return { known: false };
|
||||
const input = coordinator.inputState();
|
||||
const state = coordinator.state();
|
||||
// Hosted plugin debug sessions are not enumerated by the native DAP manager.
|
||||
// Once used, require explicit pause until backend restart instead of guessing termination.
|
||||
const known = !snapshotPending && !hostedDebugTouched;
|
||||
return {
|
||||
known,
|
||||
activeClients: input.activeClients,
|
||||
terminals: processManager.processes.size,
|
||||
debugSessions: [...debugManager.getAll()].length + (state.debugController ? 1 : 0),
|
||||
dirty: input.dirty,
|
||||
snapshotComplete: !!input.latestSnapshot && input.latestSnapshot.digest === input.currentDiskDigest,
|
||||
snapshotRevision: input.latestSnapshot?.revision ?? 0,
|
||||
diskDigest: input.currentDiskDigest,
|
||||
};
|
||||
} catch {
|
||||
return { known: false };
|
||||
}
|
||||
}
|
||||
module.exports = { sleepReceipt };
|
||||
@ -1,220 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
Uint8ArrayReadBuffer,
|
||||
Uint8ArrayWriteBuffer,
|
||||
} = require('@theia/core/lib/common/message-rpc/uint8-array-message-buffer');
|
||||
const {
|
||||
MsgPackMessageDecoder,
|
||||
MsgPackMessageEncoder,
|
||||
} = require('@theia/core/lib/common/message-rpc/rpc-message-encoder');
|
||||
|
||||
const MAX_BATCH_MESSAGES = 10_000;
|
||||
const MAX_BATCH_BYTES = 64 * 1024 * 1024;
|
||||
const MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
||||
// filterPluginRpc is invoked once per batch. Keep synthetic DAP response sequence
|
||||
// numbers increasing across batches for the lifetime of this backend process.
|
||||
let pluginDapResponseSequence = 0;
|
||||
|
||||
function rejected(code) {
|
||||
return Object.assign(new Error(code), { code });
|
||||
}
|
||||
|
||||
// Theia's ReadBuffer intentionally trusts frame lengths. Validate every boundary
|
||||
// first: a Uint8Array may be a view into a larger websocket backing buffer.
|
||||
function readLength(bytes, cursor, maximum) {
|
||||
let value = 0;
|
||||
for (let shift = 0; shift <= 28; shift += 7) {
|
||||
if (cursor.offset >= bytes.byteLength) throw rejected('MALFORMED_PLUGIN_RPC');
|
||||
const byte = bytes[cursor.offset++];
|
||||
value += (byte & 127) * 2 ** shift;
|
||||
if (value > maximum) throw rejected('RPC_BATCH_LIMIT');
|
||||
if (byte < 128) return value;
|
||||
}
|
||||
throw rejected('MALFORMED_PLUGIN_RPC');
|
||||
}
|
||||
|
||||
function decodeBatch(payload) {
|
||||
if (!(payload instanceof Uint8Array)) throw rejected('MALFORMED_PLUGIN_RPC');
|
||||
if (payload.byteLength > MAX_BATCH_BYTES) throw rejected('RPC_BATCH_LIMIT');
|
||||
const cursor = { offset: 0 };
|
||||
const count = readLength(payload, cursor, MAX_BATCH_MESSAGES);
|
||||
const messages = [];
|
||||
const decoder = new MsgPackMessageDecoder();
|
||||
for (let index = 0; index < count; index++) {
|
||||
const length = readLength(payload, cursor, MAX_MESSAGE_BYTES);
|
||||
if (length === 0 || length > payload.byteLength - cursor.offset) throw rejected('MALFORMED_PLUGIN_RPC');
|
||||
const bytes = payload.slice(cursor.offset, cursor.offset + length);
|
||||
cursor.offset += length;
|
||||
const inner = { offset: 0 };
|
||||
const encodedLength = readLength(bytes, inner, MAX_MESSAGE_BYTES);
|
||||
if (encodedLength !== bytes.byteLength - inner.offset) throw rejected('MALFORMED_PLUGIN_RPC');
|
||||
let message;
|
||||
try {
|
||||
message = decoder.parse(new Uint8ArrayReadBuffer(bytes));
|
||||
} catch {
|
||||
throw rejected('UNDECODABLE_PLUGIN_RPC');
|
||||
}
|
||||
if (!message || ![1, 2, 3, 4, 5].includes(message.type)) throw rejected('MALFORMED_PLUGIN_RPC');
|
||||
if ((message.type !== 2 || message.id !== undefined) && (!Number.isSafeInteger(message.id) || message.id < 0))
|
||||
throw rejected('MALFORMED_PLUGIN_RPC');
|
||||
if (
|
||||
(message.type === 1 || message.type === 2) &&
|
||||
(typeof message.method !== 'string' || !Array.isArray(message.args))
|
||||
)
|
||||
throw rejected('MALFORMED_PLUGIN_RPC');
|
||||
messages.push({ bytes, message });
|
||||
}
|
||||
if (cursor.offset !== payload.byteLength) throw rejected('MALFORMED_PLUGIN_RPC');
|
||||
return messages;
|
||||
}
|
||||
|
||||
function encodeBatch(messages) {
|
||||
if (messages.length === 0) return null;
|
||||
const writer = new Uint8ArrayWriteBuffer();
|
||||
writer.writeLength(messages.length);
|
||||
for (const message of messages) writer.writeBytes(message);
|
||||
const encoded = writer.getCurrentContents();
|
||||
writer.dispose();
|
||||
return encoded;
|
||||
}
|
||||
|
||||
function gated(message) {
|
||||
if (message.type !== 1 && message.type !== 2) return false;
|
||||
return (
|
||||
(message.args[0] === 'DebugExt' && ['$createDebugSession', '$terminateDebugSession'].includes(message.method)) ||
|
||||
(message.args[0] === 'ConnectionExt' && ['$sendMessage', '$deleteConnection'].includes(message.method))
|
||||
);
|
||||
}
|
||||
|
||||
function assertSynchronously(assertControl) {
|
||||
const result = assertControl();
|
||||
// The backend guard must make its authorization decision before forwarding.
|
||||
if (result === false || (result && typeof result.then === 'function')) throw rejected('DEBUG_CONTROL_REQUIRED');
|
||||
}
|
||||
|
||||
function dapRequest(value) {
|
||||
if (typeof value !== 'string') return null;
|
||||
let request;
|
||||
try {
|
||||
request = JSON.parse(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
!request ||
|
||||
Array.isArray(request) ||
|
||||
request.type !== 'request' ||
|
||||
!Number.isSafeInteger(request.seq) ||
|
||||
request.seq < 0 ||
|
||||
typeof request.command !== 'string' ||
|
||||
!request.command
|
||||
)
|
||||
return null;
|
||||
return request;
|
||||
}
|
||||
|
||||
function pluginDapDenial(message, encoder) {
|
||||
if (message.args[0] !== 'ConnectionExt' || message.method !== '$sendMessage') return null;
|
||||
const sessionId = message.args[1];
|
||||
if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 1024) return null;
|
||||
const request = dapRequest(message.args[2]);
|
||||
if (!request) return null;
|
||||
const response = {
|
||||
seq: ++pluginDapResponseSequence,
|
||||
type: 'response',
|
||||
request_seq: request.seq,
|
||||
command: request.command,
|
||||
success: false,
|
||||
message: 'WishForge debug controller lease required',
|
||||
};
|
||||
const writer = new Uint8ArrayWriteBuffer();
|
||||
// PluginChannel.send discards its RPC promise. ReplyErr alone leaves the DAP
|
||||
// request pending, so deliver a real DAP failure through the frontend channel.
|
||||
encoder.notification(writer, '$sendMessage', ['ConnectionMain', sessionId, JSON.stringify(response)]);
|
||||
const bytes = writer.getCurrentContents();
|
||||
writer.dispose();
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** Filter a real Theia BatchingChannel frame without forwarding any undecoded bytes. */
|
||||
function filterPluginRpc(payload, assertControl) {
|
||||
if (typeof assertControl !== 'function') throw rejected('DEBUG_GUARD_REQUIRED');
|
||||
const messages = decodeBatch(payload);
|
||||
const forwarded = [];
|
||||
const replies = [];
|
||||
const encoder = new MsgPackMessageEncoder();
|
||||
let denied = 0;
|
||||
for (const { bytes, message } of messages) {
|
||||
if (gated(message)) {
|
||||
try {
|
||||
assertSynchronously(assertControl);
|
||||
} catch {
|
||||
denied++;
|
||||
if (message.type === 1) {
|
||||
const writer = new Uint8ArrayWriteBuffer();
|
||||
encoder.replyErr(writer, message.id, rejected('DEBUG_CONTROL_REQUIRED'));
|
||||
replies.push(writer.getCurrentContents());
|
||||
writer.dispose();
|
||||
}
|
||||
const dapReply = pluginDapDenial(message, encoder);
|
||||
if (dapReply) replies.push(dapReply);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
forwarded.push(bytes);
|
||||
}
|
||||
return { forwarded: encodeBatch(forwarded), replies: encodeBatch(replies), denied };
|
||||
}
|
||||
|
||||
/** Wrap the native ForwardingDebugChannel; authorization is checked per incoming DAP message. */
|
||||
function guardDebugChannel(raw, assertControl) {
|
||||
if (typeof assertControl !== 'function') throw rejected('DEBUG_GUARD_REQUIRED');
|
||||
let responseSequence = 0;
|
||||
return {
|
||||
send: message => raw.send(message),
|
||||
onClose: callback => raw.onClose(callback),
|
||||
onError: callback => raw.onError(callback),
|
||||
close: () => raw.close(),
|
||||
onMessage: callback =>
|
||||
raw.onMessage(message => {
|
||||
try {
|
||||
assertSynchronously(assertControl);
|
||||
} catch {
|
||||
let request;
|
||||
try {
|
||||
request = JSON.parse(message);
|
||||
} catch {
|
||||
raw.close();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!request ||
|
||||
request.type !== 'request' ||
|
||||
!Number.isSafeInteger(request.seq) ||
|
||||
request.seq < 0 ||
|
||||
typeof request.command !== 'string' ||
|
||||
!request.command
|
||||
) {
|
||||
raw.close();
|
||||
return;
|
||||
}
|
||||
raw.send(
|
||||
JSON.stringify({
|
||||
seq: ++responseSequence,
|
||||
type: 'response',
|
||||
request_seq: request.seq,
|
||||
command: request.command,
|
||||
success: false,
|
||||
message: 'WishForge debug controller lease required',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Adapter callback errors are not authorization failures and must not be swallowed.
|
||||
callback(message);
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { filterPluginRpc, guardDebugChannel, MAX_BATCH_MESSAGES, MAX_BATCH_BYTES, MAX_MESSAGE_BYTES };
|
||||
@ -1,367 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const {
|
||||
Uint8ArrayReadBuffer,
|
||||
Uint8ArrayWriteBuffer,
|
||||
} = require('@theia/core/lib/common/message-rpc/uint8-array-message-buffer');
|
||||
const {
|
||||
MsgPackMessageDecoder,
|
||||
MsgPackMessageEncoder,
|
||||
} = require('@theia/core/lib/common/message-rpc/rpc-message-encoder');
|
||||
const {
|
||||
BatchingChannel,
|
||||
RPCProtocolImpl,
|
||||
createProxyIdentifier,
|
||||
} = require('@theia/plugin-ext/lib/common/rpc-protocol');
|
||||
const { ConnectionImpl } = require('@theia/plugin-ext/lib/common/connection');
|
||||
const { ForwardingDebugChannel } = require('@theia/debug/lib/common/debug-service');
|
||||
const { Emitter } = require('@theia/core/lib/common/event');
|
||||
const { filterPluginRpc, guardDebugChannel, MAX_BATCH_MESSAGES } = require('../plugin-dap-guard.cjs');
|
||||
const { Coordinator, DEBUG_LEASE_MS } = require('../../coordination/index.cjs');
|
||||
|
||||
const encoder = new MsgPackMessageEncoder();
|
||||
const decoder = new MsgPackMessageDecoder();
|
||||
const deny = () => {
|
||||
throw new Error('DEBUG_FORBIDDEN');
|
||||
};
|
||||
function rpc(method, service, id = 1, type = 1, rest = []) {
|
||||
const writer = new Uint8ArrayWriteBuffer();
|
||||
if (type === 2) encoder.notification(writer, method, [service, ...rest], id);
|
||||
else encoder.request(writer, id, method, [service, ...rest]);
|
||||
return writer.getCurrentContents();
|
||||
}
|
||||
function batch(...messages) {
|
||||
const writer = new Uint8ArrayWriteBuffer();
|
||||
writer.writeLength(messages.length);
|
||||
for (const message of messages) writer.writeBytes(message);
|
||||
return writer.getCurrentContents();
|
||||
}
|
||||
function decode(payload) {
|
||||
if (!payload) return [];
|
||||
const reader = new Uint8ArrayReadBuffer(payload);
|
||||
const count = reader.readLength();
|
||||
return Array.from({ length: count }, () => decoder.parse(new Uint8ArrayReadBuffer(reader.readBytes())));
|
||||
}
|
||||
function memoryChannel() {
|
||||
const messages = new Emitter();
|
||||
const errors = new Emitter();
|
||||
const closes = new Emitter();
|
||||
const sent = [];
|
||||
let closed = false;
|
||||
return {
|
||||
sent,
|
||||
get closed() {
|
||||
return closed;
|
||||
},
|
||||
onMessage: messages.event,
|
||||
onError: errors.event,
|
||||
onClose: closes.event,
|
||||
getWriteBuffer() {
|
||||
const writer = new Uint8ArrayWriteBuffer();
|
||||
writer.onCommit(value => sent.push(value));
|
||||
return writer;
|
||||
},
|
||||
close() {
|
||||
closed = true;
|
||||
closes.fire({ code: 1000, reason: 'closed' });
|
||||
},
|
||||
receive(bytes) {
|
||||
messages.fire(() => new Uint8ArrayReadBuffer(bytes));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('real Theia RPCProtocol emits the DebugExt wire shape gated by the filter', async () => {
|
||||
const wire = memoryChannel();
|
||||
const protocol = new RPCProtocolImpl(wire);
|
||||
const pending = protocol
|
||||
.getProxy(createProxyIdentifier('DebugExt'))
|
||||
.$createDebugSession({ type: 'pwa-node', name: 'test' }, 'file:///workspace');
|
||||
const rejected = assert.rejects(pending, /DEBUG_CONTROL_REQUIRED/);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(wire.sent.length, 1);
|
||||
const actual = decode(wire.sent[0]);
|
||||
assert.equal(actual[0].method, '$createDebugSession');
|
||||
assert.equal(actual[0].args[0], 'DebugExt');
|
||||
const result = filterPluginRpc(wire.sent[0], deny);
|
||||
assert.equal(result.forwarded, null);
|
||||
assert.equal(result.denied, 1);
|
||||
wire.receive(result.replies);
|
||||
await rejected;
|
||||
protocol.dispose();
|
||||
});
|
||||
|
||||
test('unauthorized plugin create/terminate/send/delete requests never enter the forwarded host batch', () => {
|
||||
const calls = [
|
||||
rpc('$createDebugSession', 'DebugExt', 10),
|
||||
rpc('$terminateDebugSession', 'DebugExt', 11),
|
||||
rpc('$sendMessage', 'ConnectionExt', 12, 1, ['session', '{"command":"continue"}']),
|
||||
rpc('$deleteConnection', 'ConnectionExt', 13),
|
||||
];
|
||||
const result = filterPluginRpc(batch(...calls), deny);
|
||||
assert.equal(result.forwarded, null);
|
||||
assert.equal(result.denied, 4);
|
||||
assert.deepEqual(
|
||||
decode(result.replies).map(message => ({ type: message.type, id: message.id, error: message.err.message })),
|
||||
[10, 11, 12, 13].map(id => ({ type: 4, id, error: 'DEBUG_CONTROL_REQUIRED' })),
|
||||
);
|
||||
});
|
||||
|
||||
test('denied plugin DAP reaches real frontend RPCProtocol and ConnectionMain as a failed response', async () => {
|
||||
const wire = memoryChannel();
|
||||
const protocol = new RPCProtocolImpl(wire);
|
||||
const proxy = protocol.getProxy(createProxyIdentifier('ConnectionExt'));
|
||||
const connectionMain = protocol.set(createProxyIdentifier('ConnectionMain'), new ConnectionImpl(proxy));
|
||||
const frontendChannel = await connectionMain.doEnsureConnection('session-real');
|
||||
const received = [];
|
||||
frontendChannel.onMessage(message => received.push(JSON.parse(message)));
|
||||
let previousSequence = 0;
|
||||
try {
|
||||
for (const [seq, command] of [
|
||||
[31, 'next'],
|
||||
[32, 'continue'],
|
||||
]) {
|
||||
const pending = proxy.$sendMessage(
|
||||
'session-real',
|
||||
JSON.stringify({ type: 'request', seq, command, arguments: { threadId: 1 } }),
|
||||
);
|
||||
const rejected = assert.rejects(pending, /DEBUG_CONTROL_REQUIRED/);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
const result = filterPluginRpc(wire.sent.at(-1), deny);
|
||||
assert.equal(result.forwarded, null);
|
||||
assert.equal(result.denied, 1);
|
||||
const messages = decode(result.replies);
|
||||
assert.equal(messages[0].type, 4);
|
||||
assert.equal(messages[1].type, 2);
|
||||
assert.equal(messages[1].method, '$sendMessage');
|
||||
assert.deepEqual(messages[1].args.slice(0, 2), ['ConnectionMain', 'session-real']);
|
||||
wire.receive(result.replies);
|
||||
await rejected;
|
||||
const response = received.at(-1);
|
||||
assert.ok(Number.isSafeInteger(response.seq) && response.seq > previousSequence);
|
||||
previousSequence = response.seq;
|
||||
assert.deepEqual(
|
||||
{ ...response, seq: undefined },
|
||||
{
|
||||
seq: undefined,
|
||||
type: 'response',
|
||||
request_seq: seq,
|
||||
command,
|
||||
success: false,
|
||||
message: 'WishForge debug controller lease required',
|
||||
},
|
||||
);
|
||||
}
|
||||
assert.equal(received.length, 2);
|
||||
} finally {
|
||||
protocol.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('denied DAP carried as an RPC notification receives only a DAP failure notification', () => {
|
||||
const request = JSON.stringify({ type: 'request', seq: 4, command: 'disconnect' });
|
||||
const result = filterPluginRpc(batch(rpc('$sendMessage', 'ConnectionExt', 42, 2, ['session-one', request])), deny);
|
||||
assert.equal(result.forwarded, null);
|
||||
assert.equal(result.denied, 1);
|
||||
const replies = decode(result.replies);
|
||||
assert.equal(replies.length, 1);
|
||||
assert.equal(replies[0].type, 2);
|
||||
assert.deepEqual(replies[0].args.slice(0, 2), ['ConnectionMain', 'session-one']);
|
||||
assert.equal(JSON.parse(replies[0].args[2]).request_seq, 4);
|
||||
});
|
||||
|
||||
test('malformed or nonrequest denied plugin DAP never fabricates a DAP response', () => {
|
||||
const cases = [
|
||||
['session', 'bad-json'],
|
||||
['session', 'null'],
|
||||
['session', '[]'],
|
||||
['session', '{"type":"event","seq":1,"command":"next"}'],
|
||||
['session', '{"type":"request","seq":"1","command":"next"}'],
|
||||
['session', '{"type":"request","seq":-1,"command":"next"}'],
|
||||
['session', '{"type":"request","seq":1}'],
|
||||
['session', '{"type":"request","seq":1,"command":""}'],
|
||||
['session', { type: 'request', seq: 1, command: 'next' }],
|
||||
['', '{"type":"request","seq":1,"command":"next"}'],
|
||||
[5, '{"type":"request","seq":1,"command":"next"}'],
|
||||
];
|
||||
for (const args of cases) {
|
||||
const result = filterPluginRpc(batch(rpc('$sendMessage', 'ConnectionExt', 42, 1, args)), deny);
|
||||
assert.equal(result.forwarded, null);
|
||||
assert.equal(result.denied, 1);
|
||||
const replies = decode(result.replies);
|
||||
assert.equal(replies.length, 1);
|
||||
assert.equal(replies[0].type, 4);
|
||||
assert.equal(replies[0].err.message, 'DEBUG_CONTROL_REQUIRED');
|
||||
}
|
||||
});
|
||||
|
||||
test('ordinary RPC forwards byte-for-byte while denied notifications do not fabricate replies', () => {
|
||||
const ordinary = rpc('$acceptModelChanged', 'EditorsAndDocumentsExt', 1, 2);
|
||||
const reply = new Uint8ArrayWriteBuffer();
|
||||
encoder.replyOK(reply, 8, { success: true });
|
||||
const result = filterPluginRpc(
|
||||
batch(ordinary, rpc('$sendMessage', 'ConnectionExt', 2, 2), reply.getCurrentContents()),
|
||||
deny,
|
||||
);
|
||||
assert.deepEqual(result.forwarded, batch(ordinary, reply.getCurrentContents()));
|
||||
assert.equal(result.replies, null);
|
||||
assert.equal(result.denied, 1);
|
||||
});
|
||||
|
||||
test('controller forwarding preserves actual BatchingChannel bytes and rechecks authorization for every command', () => {
|
||||
const wire = memoryChannel();
|
||||
const batching = new BatchingChannel(wire);
|
||||
const first = batching.getWriteBuffer();
|
||||
encoder.request(first, 1, '$createDebugSession', ['DebugExt']);
|
||||
first.commit();
|
||||
const second = batching.getWriteBuffer();
|
||||
encoder.request(second, 2, '$sendMessage', ['ConnectionExt', 'session', '{}']);
|
||||
second.commit();
|
||||
batching.sendAccumulated();
|
||||
const payload = wire.sent[0];
|
||||
let checks = 0;
|
||||
const allowed = filterPluginRpc(payload, () => {
|
||||
checks++;
|
||||
});
|
||||
assert.deepEqual(allowed.forwarded, payload);
|
||||
assert.equal(allowed.replies, null);
|
||||
assert.equal(checks, 2);
|
||||
checks = 0;
|
||||
const revokedMidBatch = filterPluginRpc(payload, () => {
|
||||
if (++checks === 2) deny();
|
||||
});
|
||||
assert.equal(decode(revokedMidBatch.forwarded).length, 1);
|
||||
assert.equal(decode(revokedMidBatch.replies)[0].id, 2);
|
||||
batching.close();
|
||||
});
|
||||
|
||||
test('malformed, truncated, oversized or trailing frames fail atomically before any forwarding', () => {
|
||||
const good = batch(rpc('$createDebugSession', 'DebugExt'));
|
||||
const excessive = new Uint8ArrayWriteBuffer();
|
||||
excessive.writeLength(MAX_BATCH_MESSAGES + 1);
|
||||
const invalidInner = new Uint8ArrayWriteBuffer();
|
||||
invalidInner.writeLength(100);
|
||||
invalidInner.writeRaw(new Uint8Array([1]));
|
||||
const wrongShape = new Uint8ArrayWriteBuffer();
|
||||
encoder.encode(wrongShape, { type: 1, id: 3, method: '$sendMessage', args: { 0: 'ConnectionExt' } });
|
||||
for (const bytes of [
|
||||
new Uint8Array(),
|
||||
good.slice(0, -1),
|
||||
new Uint8Array([...good, 0]),
|
||||
excessive.getCurrentContents(),
|
||||
batch(invalidInner.getCurrentContents()),
|
||||
batch(wrongShape.getCurrentContents()),
|
||||
new Uint8Array([129, 129, 129, 129, 129, 0]),
|
||||
]) {
|
||||
let invoked = false;
|
||||
assert.throws(
|
||||
() =>
|
||||
filterPluginRpc(bytes, () => {
|
||||
invoked = true;
|
||||
}),
|
||||
/PLUGIN_RPC|RPC_BATCH_LIMIT/,
|
||||
);
|
||||
assert.equal(invoked, false);
|
||||
}
|
||||
// Prevent reading into extra bytes from a websocket buffer outside the actual view.
|
||||
const backed = new Uint8Array([...good, ...good]);
|
||||
assert.throws(() => filterPluginRpc(backed.subarray(0, good.length - 1), deny), /PLUGIN_RPC/);
|
||||
assert.deepEqual(filterPluginRpc(batch(), deny), { forwarded: null, replies: null, denied: 0 });
|
||||
});
|
||||
|
||||
test('guard cannot accidentally authorize on a false or asynchronous decision', () => {
|
||||
const payload = batch(rpc('$sendMessage', 'ConnectionExt'));
|
||||
for (const callback of [() => false, () => Promise.resolve(true)])
|
||||
assert.equal(filterPluginRpc(payload, callback).forwarded, null);
|
||||
assert.throws(() => filterPluginRpc(payload), /DEBUG_GUARD_REQUIRED/);
|
||||
});
|
||||
|
||||
test('real coordinator lease owner, renewal, expiry and revocation govern plugin forwarding', t => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'wishforge-debug-guard-'));
|
||||
const workspaceRoot = path.join(directory, 'source');
|
||||
fs.mkdirSync(workspaceRoot);
|
||||
let now = 1000;
|
||||
const coordinator = new Coordinator({ workspaceRoot, stateDirectory: path.join(directory, 'state'), now: () => now });
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
const alice = coordinator.debugAcquire('alice');
|
||||
const payload = batch(rpc('$sendMessage', 'ConnectionExt'));
|
||||
assert.equal(filterPluginRpc(payload, () => coordinator.assertDebugController('bob', alice.token)).forwarded, null);
|
||||
assert.equal(
|
||||
filterPluginRpc(payload, () => coordinator.assertDebugController('alice', 'another-tab-token')).forwarded,
|
||||
null,
|
||||
);
|
||||
const permitted = () => coordinator.assertDebugController('alice', alice.token);
|
||||
assert.deepEqual(filterPluginRpc(payload, permitted).forwarded, payload);
|
||||
now += 10_000;
|
||||
coordinator.debugAcquire('alice', alice.token);
|
||||
now += DEBUG_LEASE_MS - 10_000;
|
||||
assert.deepEqual(filterPluginRpc(payload, permitted).forwarded, payload);
|
||||
now += 10_000;
|
||||
assert.equal(filterPluginRpc(payload, permitted).forwarded, null);
|
||||
const next = coordinator.debugAcquire('alice');
|
||||
assert.deepEqual(
|
||||
filterPluginRpc(payload, () => coordinator.assertDebugController('alice', next.token)).forwarded,
|
||||
payload,
|
||||
);
|
||||
coordinator.revoke('alice');
|
||||
assert.equal(filterPluginRpc(payload, () => coordinator.assertDebugController('alice', next.token)).forwarded, null);
|
||||
});
|
||||
|
||||
test('native DAP wrapper checks the live lease before adapter callback and sends decodable denials', () => {
|
||||
const wire = memoryChannel();
|
||||
const raw = new ForwardingDebugChannel(wire);
|
||||
let allowed = false;
|
||||
const guarded = guardDebugChannel(raw, () => {
|
||||
if (!allowed) deny();
|
||||
});
|
||||
const received = [];
|
||||
guarded.onMessage(message => received.push(JSON.parse(message)));
|
||||
const incoming = (seq, command) => {
|
||||
const writer = new Uint8ArrayWriteBuffer();
|
||||
writer.writeString(JSON.stringify({ type: 'request', seq, command }));
|
||||
wire.receive(writer.getCurrentContents());
|
||||
};
|
||||
incoming(1, 'launch');
|
||||
incoming(2, 'continue');
|
||||
assert.deepEqual(received, []);
|
||||
const errors = wire.sent.map(bytes => JSON.parse(new Uint8ArrayReadBuffer(bytes).readString()));
|
||||
assert.deepEqual(
|
||||
errors.map(error => [error.seq, error.request_seq, error.command, error.success]),
|
||||
[
|
||||
[1, 1, 'launch', false],
|
||||
[2, 2, 'continue', false],
|
||||
],
|
||||
);
|
||||
allowed = true;
|
||||
incoming(3, 'next');
|
||||
assert.equal(received[0].command, 'next');
|
||||
allowed = false;
|
||||
incoming(4, 'disconnect');
|
||||
assert.equal(received.length, 1);
|
||||
guarded.send(JSON.stringify({ type: 'event', event: 'stopped' }));
|
||||
assert.equal(JSON.parse(new Uint8ArrayReadBuffer(wire.sent.at(-1)).readString()).event, 'stopped');
|
||||
guarded.close();
|
||||
assert.equal(wire.closed, true);
|
||||
});
|
||||
|
||||
test('unauthorized malformed native DAP closes channel without reaching adapter', () => {
|
||||
for (const message of ['bad-json', 'null', '{"type":"event","event":"stopped"}', '{"type":"request","seq":1}']) {
|
||||
const wire = memoryChannel();
|
||||
const guarded = guardDebugChannel(new ForwardingDebugChannel(wire), deny);
|
||||
let reached = false;
|
||||
guarded.onMessage(() => {
|
||||
reached = true;
|
||||
});
|
||||
const writer = new Uint8ArrayWriteBuffer();
|
||||
writer.writeString(message);
|
||||
wire.receive(writer.getCurrentContents());
|
||||
assert.equal(reached, false);
|
||||
assert.equal(wire.closed, true);
|
||||
assert.equal(wire.sent.length, 0);
|
||||
}
|
||||
});
|
||||
@ -1,12 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { DraftStore } = require('../drafts.cjs');
|
||||
test('draft quota rejects oversized ASCII and multibyte content before touching IndexedDB', () => {
|
||||
const store = new DraftStore({
|
||||
open() {
|
||||
throw new Error('storage should not be opened');
|
||||
},
|
||||
});
|
||||
assert.throws(() => store.put({ text: 'a'.repeat(2 * 1024 * 1024 + 1), baseText: '' }), /2 MiB/);
|
||||
assert.throws(() => store.put({ text: '中'.repeat(800000), baseText: '' }), /2 MiB/);
|
||||
});
|
||||
@ -1,54 +0,0 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { sleepReceipt } = require('../lifecycle-safety.cjs');
|
||||
const hash = 'a'.repeat(64);
|
||||
function fixture() {
|
||||
return {
|
||||
coordinator: {
|
||||
inputState: () => ({
|
||||
activeClients: 0,
|
||||
dirty: false,
|
||||
currentDiskDigest: hash,
|
||||
latestSnapshot: { digest: hash, revision: 1 },
|
||||
}),
|
||||
state: () => ({ debugController: null }),
|
||||
},
|
||||
processManager: { processes: new Map() },
|
||||
debugManager: { getAll: () => [].values() },
|
||||
snapshotPending: false,
|
||||
hostedDebugTouched: false,
|
||||
};
|
||||
}
|
||||
test('quiescent saved workspace reports complete snapshots and no active processes', () => {
|
||||
assert.deepEqual(sleepReceipt(fixture()), {
|
||||
known: true,
|
||||
activeClients: 0,
|
||||
terminals: 0,
|
||||
debugSessions: 0,
|
||||
dirty: false,
|
||||
snapshotComplete: true,
|
||||
snapshotRevision: 1,
|
||||
diskDigest: hash,
|
||||
});
|
||||
});
|
||||
test('unknown/debug/plugin activity, active terminals and incomplete snapshots never look quiescent', () => {
|
||||
const f = fixture();
|
||||
f.processManager.processes.set(1, {});
|
||||
assert.equal(sleepReceipt(f).terminals, 1);
|
||||
f.hostedDebugTouched = true;
|
||||
assert.equal(sleepReceipt(f).known, false);
|
||||
f.hostedDebugTouched = false;
|
||||
f.debugManager.getAll = () => [{}].values();
|
||||
assert.equal(sleepReceipt(f).debugSessions, 1);
|
||||
f.coordinator.inputState = () => ({
|
||||
activeClients: 1,
|
||||
dirty: true,
|
||||
currentDiskDigest: hash,
|
||||
latestSnapshot: { digest: 'b'.repeat(64), revision: 1 },
|
||||
});
|
||||
assert.equal(sleepReceipt(f).snapshotComplete, false);
|
||||
assert.equal(sleepReceipt(f).activeClients, 1);
|
||||
assert.equal(sleepReceipt({ ...f, processManager: {} }).known, false);
|
||||
assert.equal(sleepReceipt({ ...f, snapshotPending: true }).known, false);
|
||||
});
|
||||
@ -1,7 +0,0 @@
|
||||
{
|
||||
"nameShort": "WishForge",
|
||||
"nameLong": "WishForge IDE",
|
||||
"applicationName": "wishforge-ide",
|
||||
"version": "1.108.2",
|
||||
"extensionEnabledApiProposals": {}
|
||||
}
|
||||
@ -36,17 +36,16 @@ test('creating manifests does not mark an unready IDE available', async () => {
|
||||
assert.equal(result.status, 'pending');
|
||||
assert.throws(() => renderWorkspaceResources(config, { ...input, tenantId: 'beta' }, image));
|
||||
});
|
||||
test('scoped collaboration and coordination expose only public identity material to the workspace', () => {
|
||||
const rendered = renderWorkspaceResources({ ...config, gatewayPublicKeyConfigMap: 'gateway-public' }, input, image, {
|
||||
test('scoped collaboration runs as a sidecar without any platform credential in the workspace', () => {
|
||||
const rendered = renderWorkspaceResources(config, input, image, {
|
||||
image,
|
||||
gatewayBase: 'https://ide.example/',
|
||||
});
|
||||
const pod = rendered.resources.find(r => r.kind === 'Deployment').spec.template.spec;
|
||||
{
|
||||
assert.equal(pod.containers.length, 2);
|
||||
assert.ok(pod.containers[0].env.some(e => e.name === 'WF_IDE_GATEWAY_PUBLIC_KEY_FILE'));
|
||||
assert.ok(!JSON.stringify(pod).includes('PRIVATE_KEY'));
|
||||
assert.ok(pod.volumes.some(v => v.name === 'coordination-state'));
|
||||
assert.ok(!JSON.stringify(pod).includes('TOKEN'));
|
||||
const octEnv = Object.fromEntries(pod.containers[1].env.map(e => [e.name, e.value]));
|
||||
assert.equal(octEnv.WF_WORKSPACE_ID, input.workspaceId);
|
||||
assert.equal(octEnv.WISHFORGE_GATEWAY_ENFORCED, 'true');
|
||||
|
||||
@ -144,38 +144,6 @@ export function renderWorkspaceResources(config, input, image, collaboration) {
|
||||
);
|
||||
workspacePod.volumes.push({ name: 'temporary', emptyDir: { sizeLimit: '2Gi' } });
|
||||
workspacePod.containers[0].volumeMounts.push({ name: 'temporary', mountPath: '/tmp' });
|
||||
if (config.gatewayPublicKeyConfigMap) {
|
||||
if (
|
||||
!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(config.gatewayPublicKeyConfigMap) ||
|
||||
config.gatewayPublicKeyConfigMap.length > 63
|
||||
)
|
||||
throw new Error('INVALID_GATEWAY_PUBLIC_KEY_CONFIGMAP');
|
||||
resources.unshift({
|
||||
apiVersion: 'v1',
|
||||
kind: 'PersistentVolumeClaim',
|
||||
metadata: metadata(`${name}-state`),
|
||||
spec: {
|
||||
storageClassName: config.storageClass,
|
||||
accessModes: ['ReadWriteOnce'],
|
||||
resources: { requests: { storage: '1Gi' } },
|
||||
},
|
||||
});
|
||||
workspacePod.volumes.push(
|
||||
{ name: 'coordination-state', persistentVolumeClaim: { claimName: `${name}-state` } },
|
||||
{
|
||||
name: 'gateway-public-key',
|
||||
configMap: { name: config.gatewayPublicKeyConfigMap, items: [{ key: 'public.pem', path: 'public.pem' }] },
|
||||
},
|
||||
);
|
||||
workspacePod.containers[0].volumeMounts.push(
|
||||
{ name: 'coordination-state', mountPath: '/var/lib/wishforge-coordination' },
|
||||
{ name: 'gateway-public-key', mountPath: '/run/wishforge-identity', readOnly: true },
|
||||
);
|
||||
workspacePod.containers[0].env.push(
|
||||
{ name: 'WF_COORDINATION_STATE_DIR', value: '/var/lib/wishforge-coordination' },
|
||||
{ name: 'WF_IDE_GATEWAY_PUBLIC_KEY_FILE', value: '/run/wishforge-identity/public.pem' },
|
||||
);
|
||||
}
|
||||
let collaborationUpstreamUrl;
|
||||
if (collaboration) {
|
||||
if (!/^[^\s]+@sha256:[a-f0-9]{64}$/.test(collaboration.image ?? ''))
|
||||
@ -264,15 +232,7 @@ export async function provisionWorkspace(config, input, options = {}) {
|
||||
(process.env.WF_OCT_WORKSPACE_IMAGE
|
||||
? { image: process.env.WF_OCT_WORKSPACE_IMAGE, gatewayBase: process.env.WF_WORKSPACE_GATEWAY_BASE }
|
||||
: undefined);
|
||||
const rendered = renderWorkspaceResources(
|
||||
{
|
||||
...config,
|
||||
gatewayPublicKeyConfigMap: options.gatewayPublicKeyConfigMap ?? process.env.WF_IDE_GATEWAY_PUBLIC_KEY_CONFIGMAP,
|
||||
},
|
||||
input,
|
||||
options.image ?? process.env.WF_THEIA_IMAGE,
|
||||
collaboration,
|
||||
);
|
||||
const rendered = renderWorkspaceResources(config, input, options.image ?? process.env.WF_THEIA_IMAGE, collaboration);
|
||||
await (options.apply ?? runKubectl)(config, rendered.resources);
|
||||
const ready = await (options.observe ?? observe)(config, rendered.name);
|
||||
return {
|
||||
|
||||
@ -1,55 +0,0 @@
|
||||
const { createPrivateKey, createPublicKey, sign, verify } = require('node:crypto');
|
||||
const roles = new Set(['owner', 'admin', 'developer']);
|
||||
function signAssertion(privateKey, grant, now = Date.now()) {
|
||||
if (!grant.userId || !roles.has(grant.role)) throw new Error('Workspace actor is not authorized');
|
||||
const body = Buffer.from(
|
||||
JSON.stringify({
|
||||
aud: 'wishforge-workspace',
|
||||
purpose: grant.purpose ?? 'interactive',
|
||||
tenantId: grant.tenantId,
|
||||
workspaceId: grant.workspaceId,
|
||||
actorId: grant.userId,
|
||||
role: grant.role,
|
||||
iat: Math.floor(now / 1000),
|
||||
exp: Math.floor(now / 1000) + 900,
|
||||
}),
|
||||
).toString('base64url');
|
||||
return `${body}.${sign(null, Buffer.from(body), createPrivateKey(privateKey)).toString('base64url')}`;
|
||||
}
|
||||
function verifyAssertion(publicKey, value, scope, now = Date.now()) {
|
||||
if (typeof value !== 'string' || value.length > 4096) throw new Error('WORKSPACE_IDENTITY_REQUIRED');
|
||||
const parts = value.split('.');
|
||||
if (
|
||||
parts.length !== 2 ||
|
||||
parts.some(
|
||||
part => !part || !/^[A-Za-z0-9_-]+$/.test(part) || Buffer.from(part, 'base64url').toString('base64url') !== part,
|
||||
) ||
|
||||
Buffer.from(parts[1], 'base64url').length !== 64
|
||||
)
|
||||
throw new Error('WORKSPACE_IDENTITY_INVALID');
|
||||
const [body, signature] = parts;
|
||||
const key = createPublicKey(publicKey);
|
||||
if (key.asymmetricKeyType !== 'ed25519' || !verify(null, Buffer.from(body), key, Buffer.from(signature, 'base64url')))
|
||||
throw new Error('WORKSPACE_IDENTITY_INVALID');
|
||||
const claims = JSON.parse(Buffer.from(body, 'base64url').toString());
|
||||
const time = Math.floor(now / 1000);
|
||||
if ((claims.purpose ?? 'interactive') !== (scope.purpose ?? 'interactive'))
|
||||
throw new Error('WORKSPACE_IDENTITY_PURPOSE');
|
||||
if (
|
||||
claims.aud !== 'wishforge-workspace' ||
|
||||
claims.tenantId !== scope.tenantId ||
|
||||
claims.workspaceId !== scope.workspaceId ||
|
||||
typeof claims.actorId !== 'string' ||
|
||||
!claims.actorId ||
|
||||
!roles.has(claims.role) ||
|
||||
!Number.isInteger(claims.iat) ||
|
||||
!Number.isInteger(claims.exp) ||
|
||||
claims.iat > time + 30 ||
|
||||
claims.exp <= time ||
|
||||
claims.exp <= claims.iat ||
|
||||
claims.exp - claims.iat > 900
|
||||
)
|
||||
throw new Error('WORKSPACE_IDENTITY_SCOPE');
|
||||
return claims;
|
||||
}
|
||||
module.exports = { signAssertion, verifyAssertion };
|
||||
@ -1,18 +0,0 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { generateKeyPairSync, createPrivateKey, createPublicKey } = require('node:crypto');
|
||||
const directory = path.resolve(process.argv[2] ?? '.wishforge/gateway-keys');
|
||||
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
||||
const privateFile = path.join(directory, 'private.pem'),
|
||||
publicFile = path.join(directory, 'public.pem');
|
||||
if (!fs.existsSync(privateFile)) {
|
||||
const keys = generateKeyPairSync('ed25519');
|
||||
fs.writeFileSync(privateFile, keys.privateKey.export({ type: 'pkcs8', format: 'pem' }), { flag: 'wx', mode: 0o600 });
|
||||
}
|
||||
const privateKey = createPrivateKey(fs.readFileSync(privateFile));
|
||||
if (privateKey.asymmetricKeyType !== 'ed25519') throw new Error('Existing gateway key is not Ed25519');
|
||||
const publicPem = createPublicKey(privateKey).export({ type: 'spki', format: 'pem' });
|
||||
if (fs.existsSync(publicFile) && fs.readFileSync(publicFile, 'utf8') !== publicPem)
|
||||
throw new Error('Existing public key does not match; inspect key rotation explicitly');
|
||||
if (!fs.existsSync(publicFile)) fs.writeFileSync(publicFile, publicPem, { flag: 'wx', mode: 0o644 });
|
||||
console.log(JSON.stringify({ privateKeyFile: privateFile, publicKeyFile: publicFile }));
|
||||
@ -1,155 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { generateKeyPairSync, sign } = require('node:crypto');
|
||||
const { signAssertion, verifyAssertion } = require('../assertions.cjs');
|
||||
|
||||
const pair = generateKeyPairSync('ed25519');
|
||||
const privateKey = pair.privateKey.export({ format: 'pem', type: 'pkcs8' });
|
||||
const publicKey = pair.publicKey.export({ format: 'pem', type: 'spki' });
|
||||
const time = 1_725_000_000_000;
|
||||
const scope = { tenantId: 'tenant-one', workspaceId: 'workspace-one' };
|
||||
const grant = { ...scope, userId: 'actor-alice', role: 'developer' };
|
||||
function claims(overrides = {}) {
|
||||
return {
|
||||
aud: 'wishforge-workspace',
|
||||
purpose: 'interactive',
|
||||
...scope,
|
||||
actorId: grant.userId,
|
||||
role: grant.role,
|
||||
iat: Math.floor(time / 1000),
|
||||
exp: Math.floor(time / 1000) + 900,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
function signedClaims(value) {
|
||||
const body = Buffer.from(JSON.stringify(value)).toString('base64url');
|
||||
return `${body}.${sign(null, Buffer.from(body), privateKey).toString('base64url')}`;
|
||||
}
|
||||
|
||||
test('Ed25519 assertion roundtrip binds each authorized role to actor, tenant and workspace', () => {
|
||||
for (const role of ['owner', 'admin', 'developer']) {
|
||||
const token = signAssertion(privateKey, { ...grant, role }, time);
|
||||
assert.deepEqual(verifyAssertion(publicKey, token, scope, time), claims({ role }));
|
||||
}
|
||||
});
|
||||
|
||||
test('body tampering, forged signature and untrusted signing keys are rejected', () => {
|
||||
const token = signAssertion(privateKey, grant, time);
|
||||
const [body, signature] = token.split('.');
|
||||
const tampered = Buffer.from(JSON.stringify(claims({ actorId: 'attacker' }))).toString('base64url');
|
||||
assert.throws(
|
||||
() => verifyAssertion(publicKey, `${tampered}.${signature}`, scope, time),
|
||||
/WORKSPACE_IDENTITY_INVALID/,
|
||||
);
|
||||
const forgedSignature = Buffer.from(signature, 'base64url');
|
||||
forgedSignature[0] ^= 1;
|
||||
assert.throws(
|
||||
() => verifyAssertion(publicKey, `${body}.${forgedSignature.toString('base64url')}`, scope, time),
|
||||
/WORKSPACE_IDENTITY_INVALID/,
|
||||
);
|
||||
const untrusted = generateKeyPairSync('ed25519');
|
||||
assert.throws(
|
||||
() => verifyAssertion(untrusted.publicKey.export({ type: 'spki', format: 'pem' }), token, scope, time),
|
||||
/WORKSPACE_IDENTITY_INVALID/,
|
||||
);
|
||||
});
|
||||
|
||||
test('expiry boundary, future issue time and overlong assertion lifetime fail closed', () => {
|
||||
const token = signAssertion(privateKey, grant, time);
|
||||
assert.equal(verifyAssertion(publicKey, token, scope, time + 899_999).actorId, grant.userId);
|
||||
assert.throws(() => verifyAssertion(publicKey, token, scope, time + 900_000), /WORKSPACE_IDENTITY_SCOPE/);
|
||||
assert.throws(
|
||||
() => verifyAssertion(publicKey, signedClaims(claims({ iat: Math.floor(time / 1000) + 31 })), scope, time),
|
||||
/WORKSPACE_IDENTITY_SCOPE/,
|
||||
);
|
||||
assert.throws(
|
||||
() => verifyAssertion(publicKey, signedClaims(claims({ exp: Math.floor(time / 1000) + 901 })), scope, time),
|
||||
/WORKSPACE_IDENTITY_SCOPE/,
|
||||
);
|
||||
assert.throws(
|
||||
() => verifyAssertion(publicKey, signedClaims(claims({ exp: 'later' })), scope, time),
|
||||
/WORKSPACE_IDENTITY_SCOPE/,
|
||||
);
|
||||
});
|
||||
|
||||
test('valid signatures cannot cross tenant, workspace, audience or role boundaries', () => {
|
||||
const token = signAssertion(privateKey, grant, time);
|
||||
assert.throws(
|
||||
() => verifyAssertion(publicKey, token, { ...scope, tenantId: 'tenant-two' }, time),
|
||||
/WORKSPACE_IDENTITY_SCOPE/,
|
||||
);
|
||||
assert.throws(
|
||||
() => verifyAssertion(publicKey, token, { ...scope, workspaceId: 'workspace-two' }, time),
|
||||
/WORKSPACE_IDENTITY_SCOPE/,
|
||||
);
|
||||
for (const overrides of [
|
||||
{ aud: 'another-service' },
|
||||
{ role: 'viewer' },
|
||||
{ role: 'deployer' },
|
||||
{ role: 'root' },
|
||||
{ actorId: '' },
|
||||
{ actorId: 5 },
|
||||
]) {
|
||||
assert.throws(
|
||||
() => verifyAssertion(publicKey, signedClaims(claims(overrides)), scope, time),
|
||||
/WORKSPACE_IDENTITY_SCOPE/,
|
||||
);
|
||||
}
|
||||
assert.throws(() => signAssertion(privateKey, { ...grant, role: 'viewer' }, time), /not authorized/);
|
||||
assert.throws(() => signAssertion(privateKey, { ...grant, userId: '' }, time), /not authorized/);
|
||||
});
|
||||
|
||||
test('assertions require exactly two canonical base64url segments', () => {
|
||||
const token = signAssertion(privateKey, grant, time);
|
||||
const [body, signature] = token.split('.');
|
||||
for (const value of [
|
||||
token + '.',
|
||||
token + '..',
|
||||
token + '!!!!',
|
||||
token + '=',
|
||||
`${body}. ${signature}`,
|
||||
`${body}.${signature}.extra`,
|
||||
`${body}.`,
|
||||
`.${signature}`,
|
||||
'',
|
||||
undefined,
|
||||
5,
|
||||
'x'.repeat(4097),
|
||||
]) {
|
||||
assert.throws(
|
||||
() => verifyAssertion(publicKey, value, scope, time),
|
||||
undefined,
|
||||
`Accepted malformed assertion ${String(value).slice(-20)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a non-Ed25519 public key cannot authorize an otherwise valid assertion', () => {
|
||||
const token = signAssertion(privateKey, grant, time);
|
||||
const other = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
|
||||
assert.throws(
|
||||
() => verifyAssertion(other.publicKey.export({ type: 'spki', format: 'pem' }), token, scope, time),
|
||||
/WORKSPACE_IDENTITY_INVALID/,
|
||||
);
|
||||
});
|
||||
|
||||
test('integration inspection assertion cannot invoke interactive coordination or debug', () => {
|
||||
const token = signAssertion(privateKey, { ...grant, purpose: 'integration-state' }, time);
|
||||
assert.equal(
|
||||
verifyAssertion(publicKey, token, { ...scope, purpose: 'integration-state' }, time).purpose,
|
||||
'integration-state',
|
||||
);
|
||||
assert.throws(() => verifyAssertion(publicKey, token, scope, time), /WORKSPACE_IDENTITY_PURPOSE/);
|
||||
assert.throws(
|
||||
() =>
|
||||
verifyAssertion(
|
||||
publicKey,
|
||||
signAssertion(privateKey, grant, time),
|
||||
{ ...scope, purpose: 'integration-state' },
|
||||
time,
|
||||
),
|
||||
/WORKSPACE_IDENTITY_PURPOSE/,
|
||||
);
|
||||
});
|
||||
@ -2594,10 +2594,6 @@ button {
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.workspace-input-panel .form-stack {
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.requirement-amendment > summary {
|
||||
cursor: pointer;
|
||||
padding: 0 22px 18px;
|
||||
|
||||
@ -35,7 +35,6 @@ import {
|
||||
Panel,
|
||||
Status,
|
||||
} from '@/components/ui';
|
||||
import { WorkspaceInputPanel } from '@/features/workspace-input';
|
||||
import { providerNames, RunTable, stages } from '@/components/run-table';
|
||||
|
||||
export function RunsView() {
|
||||
@ -421,7 +420,6 @@ export function RunDetailView({ id }: { id: string }) {
|
||||
</details>
|
||||
</Panel>
|
||||
) : null}
|
||||
{!terminal ? <WorkspaceInputPanel runId={id} /> : null}
|
||||
<RunDeliveryPanel runId={id} />
|
||||
<div className="tabs" role="tablist" aria-label="运行详情">
|
||||
{[
|
||||
|
||||
@ -1,80 +0,0 @@
|
||||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { messageOf, mutateApi, shortId, useResource } from '@/lib/api';
|
||||
import { Button, Field, FormError, Notice, Panel } from '@/components/ui';
|
||||
|
||||
interface WorkspaceInputs {
|
||||
required: boolean;
|
||||
workspaces: { id: string; status: string }[];
|
||||
snapshots: { workspaceId: string; revision: number; sourceCommit: string }[];
|
||||
}
|
||||
export function WorkspaceInputPanel({ runId }: { runId: string }) {
|
||||
const resource = useResource<WorkspaceInputs>(`/runs/${runId}/workspace-input`, 10000);
|
||||
const [workspaceId, setWorkspaceId] = useState('');
|
||||
const [sourceCommit, setSourceCommit] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [saved, setSaved] = useState(false);
|
||||
if (resource.error) return <Notice tone="warning">暂时无法读取协作输入状态,请重试后再继续集成。</Notice>;
|
||||
if (!resource.data?.required) return null;
|
||||
const selected = workspaceId || resource.data.workspaces[0]?.id || '';
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setSaved(false);
|
||||
try {
|
||||
await mutateApi(`/runs/${runId}/workspaces/${selected}/import-snapshot`, {
|
||||
sourceCommit: sourceCommit.trim(),
|
||||
confirmation: 'saved-workspace-committed',
|
||||
});
|
||||
setSaved(true);
|
||||
await resource.mutate();
|
||||
} catch (failure) {
|
||||
setError(messageOf(failure));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Panel title="协作工作区输入" className="answer-panel workspace-input-panel">
|
||||
<p>
|
||||
先在云 IDE 保存修改,并将提交推送到项目目标分支。导入时会再次请求所有在线编辑者保存确认;独立验证器随后核对实际
|
||||
Git 内容。
|
||||
</p>
|
||||
{resource.data.snapshots.map(snapshot => (
|
||||
<p key={snapshot.workspaceId}>
|
||||
工作区 {shortId(snapshot.workspaceId)} 已导入保存版本 {snapshot.revision},对应提交{' '}
|
||||
{shortId(snapshot.sourceCommit)}。
|
||||
</p>
|
||||
))}
|
||||
<form onSubmit={submit} className="form-stack">
|
||||
<Field label="工作区">
|
||||
<select value={selected} onChange={event => setWorkspaceId(event.target.value)}>
|
||||
{resource.data.workspaces.map(workspace => (
|
||||
<option key={workspace.id} value={workspace.id}>
|
||||
{shortId(workspace.id)} · {workspace.status}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="已推送的完整提交 SHA">
|
||||
<input
|
||||
required
|
||||
pattern="([a-f0-9]{40}|[a-f0-9]{64})"
|
||||
value={sourceCommit}
|
||||
onChange={event => setSourceCommit(event.target.value)}
|
||||
placeholder="填写 git rev-parse HEAD 的完整结果"
|
||||
/>
|
||||
</Field>
|
||||
<FormError message={error} />
|
||||
{saved ? (
|
||||
<Notice>保存快照已绑定。点击“继续”后执行 Git 内容比对和独立验证;这还不是验证通过或发布完成。</Notice>
|
||||
) : null}
|
||||
<Button busy={busy} disabled={!selected || !sourceCommit.trim()}>
|
||||
检查保存并绑定提交
|
||||
</Button>
|
||||
</form>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import path from 'node:path';
|
||||
import { realpath, mkdir, open, unlink } from 'node:fs/promises';
|
||||
import { realpath, mkdir } from 'node:fs/promises';
|
||||
import { Context } from '@temporalio/activity';
|
||||
import { ApplicationFailure } from '@temporalio/common';
|
||||
import type { Project, Run, VerificationProfile } from '@wishforge/contracts';
|
||||
@ -13,8 +13,6 @@ import {
|
||||
isolatedVerifierExecutor,
|
||||
RuntimeError,
|
||||
safeIdentifier,
|
||||
matchWorkspaceSnapshot,
|
||||
type WorkspaceSnapshot,
|
||||
requireBranchName,
|
||||
validateRepositoryUrl,
|
||||
verifyWorkspace,
|
||||
@ -436,17 +434,14 @@ export function createActivities(config: WorkerConfig) {
|
||||
...extras,
|
||||
});
|
||||
};
|
||||
let integrationLock: Awaited<ReturnType<typeof open>> | undefined;
|
||||
let lockPath: string | undefined;
|
||||
let integrationFence: number | undefined;
|
||||
let integrationTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let integrationRenewing = false;
|
||||
let workspaceMatched = false;
|
||||
// The control plane re-checks the project integration lease on every integrate/build transition.
|
||||
const assertIntegrationGate = async () => {
|
||||
if (integrationFence === undefined)
|
||||
throw new RuntimeError('INTEGRATION_LEASE_REQUIRED', 'Project integration lease is required');
|
||||
await ensureLease();
|
||||
await api.request(`/internal/runs/${input.runId}/workspace-input/check`, { leaseToken });
|
||||
};
|
||||
try {
|
||||
const context = await api.request<RunContext>(`/internal/runs/${input.runId}/context`);
|
||||
@ -550,7 +545,6 @@ export function createActivities(config: WorkerConfig) {
|
||||
leaseToken,
|
||||
fence: integrationFence,
|
||||
});
|
||||
if (workspaceMatched) await assertIntegrationGate();
|
||||
})()
|
||||
.catch(error => stopVerifier(error instanceof Error ? error : new Error('Integration ownership changed')))
|
||||
.finally(() => {
|
||||
@ -579,10 +573,6 @@ export function createActivities(config: WorkerConfig) {
|
||||
'INTEGRATION_SCOPE',
|
||||
'Integration repository must stay inside this tenant integrations directory',
|
||||
);
|
||||
lockPath = path.join(allowedRoot, `${safeIdentifier(context.project.id)}.lock`);
|
||||
integrationLock = await open(lockPath, 'wx', 0o600).catch(() => {
|
||||
throw new RuntimeError('INTEGRATION_BUSY', 'Another candidate owns the project integration queue');
|
||||
});
|
||||
const targetRef = `refs/heads/${context.project.targetBranch}`;
|
||||
await refreshGitCredential();
|
||||
await git.initializeIntegration({
|
||||
@ -594,40 +584,6 @@ export function createActivities(config: WorkerConfig) {
|
||||
targetRef,
|
||||
});
|
||||
const expectedTargetCommit = await git.head(integrationRepository, targetRef);
|
||||
const workspaceInput = await api.request<{
|
||||
required: boolean;
|
||||
workspaces: Array<{ id: string }>;
|
||||
snapshots: Array<WorkspaceSnapshot & { workspaceId: string; sourceCommit: string }>;
|
||||
}>(`/internal/runs/${input.runId}/workspace-input`);
|
||||
if (workspaceInput.required) {
|
||||
if (workspaceInput.snapshots.length !== workspaceInput.workspaces.length)
|
||||
throw new RuntimeError(
|
||||
'WORKSPACE_SNAPSHOT_REQUIRED',
|
||||
'Save, commit and import each active workspace snapshot before integration',
|
||||
);
|
||||
const matched = [];
|
||||
for (const snapshot of workspaceInput.snapshots) {
|
||||
const match = await matchWorkspaceSnapshot({
|
||||
repository: integrationRepository,
|
||||
sourceCommit: snapshot.sourceCommit,
|
||||
targetCommit: expectedTargetCommit,
|
||||
snapshot,
|
||||
signal: verifierSignal,
|
||||
});
|
||||
matched.push({
|
||||
workspaceId: snapshot.workspaceId,
|
||||
sourceCommit: match.sourceCommit,
|
||||
snapshotRevision: match.snapshotRevision,
|
||||
snapshotDigest: match.snapshotDigest,
|
||||
});
|
||||
}
|
||||
await api.request(`/internal/runs/${input.runId}/workspace-input/match`, {
|
||||
leaseToken,
|
||||
targetCommit: expectedTargetCommit,
|
||||
snapshots: matched,
|
||||
});
|
||||
}
|
||||
workspaceMatched = true;
|
||||
await assertIntegrationGate();
|
||||
let candidateWorkspace = workspace;
|
||||
let checkpoint = context.checkpoint;
|
||||
@ -900,10 +856,6 @@ export function createActivities(config: WorkerConfig) {
|
||||
await api
|
||||
.request(`/internal/runs/${input.runId}/integration-lease/release`, { leaseToken, fence: integrationFence })
|
||||
.catch(() => undefined);
|
||||
if (integrationLock) {
|
||||
await integrationLock.close();
|
||||
if (lockPath) await unlink(lockPath);
|
||||
}
|
||||
await api.request(`/internal/runs/${input.runId}/lease/release`, { leaseToken }).catch(() => undefined);
|
||||
}
|
||||
},
|
||||
|
||||
@ -24,7 +24,7 @@
|
||||
"typecheck": "npm run typecheck --workspaces --if-present",
|
||||
"test": "vitest run",
|
||||
"test:integration": "WF_INTEGRATION=1 vitest run tests/integration",
|
||||
"test:ide": "node --test apps/ide/gateway/test/*.test.mjs apps/ide/provisioner/test/*.test.mjs apps/ide/collaboration/test/*.test.mjs apps/ide/collaboration/test/*.test.cjs apps/ide/coordination/test/*.test.cjs apps/ide/security/test/*.test.cjs apps/ide/policy/test/*.test.cjs",
|
||||
"test:ide": "node --test apps/ide/gateway/test/*.test.mjs apps/ide/provisioner/test/*.test.mjs apps/ide/collaboration/test/*.test.mjs apps/ide/collaboration/test/*.test.cjs apps/ide/policy/test/*.test.cjs",
|
||||
"db:migrate": "tsx apps/api/src/db/migrate.ts",
|
||||
"db:seed": "tsx apps/api/src/db/seed.ts",
|
||||
"setup:local": "node scripts/setup-local.mjs && node scripts/configure-local-services.mjs",
|
||||
|
||||
@ -4,7 +4,6 @@ export * from './git.js';
|
||||
export * from './verify.js';
|
||||
export * from './build.js';
|
||||
export * from './sandbox.js';
|
||||
export * from './workspace-snapshot.js';
|
||||
export * from './deploy.js';
|
||||
export * from './runner.js';
|
||||
export * from './providers/codex.js';
|
||||
|
||||
@ -1,154 +0,0 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { requireCommit } from './git.js';
|
||||
import { RuntimeError } from './types.js';
|
||||
|
||||
/** Keep in sync with the pinned Theia coordination policy; tested against that export. */
|
||||
export const WORKSPACE_SNAPSHOT_EXCLUDED = [
|
||||
'.git',
|
||||
'node_modules',
|
||||
'dist',
|
||||
'build',
|
||||
'coverage',
|
||||
'.next',
|
||||
'.cache',
|
||||
'src-gen',
|
||||
'.wishforge',
|
||||
'.wishforge-runtime',
|
||||
'.runtime',
|
||||
'.coordination',
|
||||
];
|
||||
export interface WorkspaceSnapshotFile {
|
||||
path: string;
|
||||
sha256: string;
|
||||
size: number;
|
||||
mode: number;
|
||||
}
|
||||
export interface WorkspaceSnapshot {
|
||||
id: string;
|
||||
revision: number;
|
||||
digest: string;
|
||||
files: WorkspaceSnapshotFile[];
|
||||
}
|
||||
export function snapshotDigest(files: WorkspaceSnapshotFile[]): string {
|
||||
return createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify(files.map(file => ({ path: file.path, sha256: file.sha256, size: file.size, mode: file.mode }))),
|
||||
)
|
||||
.digest('hex');
|
||||
}
|
||||
export function validateSnapshot(snapshot: WorkspaceSnapshot): void {
|
||||
if (
|
||||
!Number.isSafeInteger(snapshot.revision) ||
|
||||
snapshot.revision < 1 ||
|
||||
!/^[a-f0-9]{64}$/.test(snapshot.id) ||
|
||||
!/^[a-f0-9]{64}$/.test(snapshot.digest) ||
|
||||
!Array.isArray(snapshot.files) ||
|
||||
snapshot.files.length > 20000
|
||||
)
|
||||
throw new RuntimeError('INVALID_WORKSPACE_SNAPSHOT', 'Invalid workspace snapshot identity');
|
||||
const paths = new Set<string>();
|
||||
let bytes = 0;
|
||||
for (const file of snapshot.files) {
|
||||
if (
|
||||
typeof file.path !== 'string' ||
|
||||
!file.path ||
|
||||
file.path.startsWith('/') ||
|
||||
/[\x00-\x1f\\]/.test(file.path) ||
|
||||
file.path.split('/').some(part => !part || ['.', '..', ...WORKSPACE_SNAPSHOT_EXCLUDED].includes(part)) ||
|
||||
paths.has(file.path) ||
|
||||
!/^[a-f0-9]{64}$/.test(file.sha256) ||
|
||||
!Number.isSafeInteger(file.size) ||
|
||||
file.size < 0 ||
|
||||
file.size > 32 * 1024 * 1024 ||
|
||||
!Number.isInteger(file.mode) ||
|
||||
file.mode < 0 ||
|
||||
file.mode > 0o777
|
||||
)
|
||||
throw new RuntimeError('INVALID_WORKSPACE_SNAPSHOT', 'Invalid or excluded snapshot file');
|
||||
paths.add(file.path);
|
||||
bytes += file.size;
|
||||
}
|
||||
if (bytes > 256 * 1024 * 1024 || snapshotDigest(snapshot.files) !== snapshot.digest)
|
||||
throw new RuntimeError('INVALID_WORKSPACE_SNAPSHOT', 'Snapshot content digest or quota is invalid');
|
||||
}
|
||||
const run = promisify(execFile);
|
||||
/** Input matching only. This is never a test/build success attestation. Does not write any working tree. */
|
||||
export async function matchWorkspaceSnapshot(input: {
|
||||
repository: string;
|
||||
sourceCommit: string;
|
||||
targetCommit: string;
|
||||
snapshot: WorkspaceSnapshot;
|
||||
signal?: AbortSignal;
|
||||
}) {
|
||||
requireCommit(input.sourceCommit);
|
||||
requireCommit(input.targetCommit);
|
||||
validateSnapshot(input.snapshot);
|
||||
const git = async (args: string[], maxBuffer = 64 * 1024 * 1024) =>
|
||||
(
|
||||
await run('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args], {
|
||||
cwd: input.repository,
|
||||
encoding: 'buffer',
|
||||
maxBuffer,
|
||||
signal: input.signal,
|
||||
env: {
|
||||
PATH: process.env.PATH,
|
||||
GIT_CONFIG_GLOBAL: '/dev/null',
|
||||
GIT_CONFIG_NOSYSTEM: '1',
|
||||
GIT_NO_REPLACE_OBJECTS: '1',
|
||||
},
|
||||
})
|
||||
).stdout;
|
||||
try {
|
||||
await git(['merge-base', '--is-ancestor', input.sourceCommit, input.targetCommit]);
|
||||
} catch {
|
||||
throw new RuntimeError(
|
||||
'WORKSPACE_NOT_COMMITTED',
|
||||
'Commit and push the saved workspace snapshot onto the integration target before continuing',
|
||||
);
|
||||
}
|
||||
const entries = new Map<string, { object: string; mode: string }>();
|
||||
const listed = (await git(['ls-tree', '-rz', '--full-tree', input.sourceCommit])).toString('utf8');
|
||||
for (const item of listed.split('\0').filter(Boolean)) {
|
||||
const split = item.indexOf('\t');
|
||||
const [mode, type, object] = item.slice(0, split).split(' ');
|
||||
const file = item.slice(split + 1);
|
||||
if (
|
||||
split < 0 ||
|
||||
!object ||
|
||||
!type ||
|
||||
!mode ||
|
||||
file.split('/').some(part => part === '..' || part === '.') ||
|
||||
/[\x00-\x1f\\]/.test(file)
|
||||
)
|
||||
throw new RuntimeError('INVALID_GIT_TREE', 'Unsafe Git tree');
|
||||
if (file.split('/').some(part => WORKSPACE_SNAPSHOT_EXCLUDED.includes(part))) continue;
|
||||
if (type !== 'blob' || !['100644', '100755'].includes(mode))
|
||||
throw new RuntimeError('UNSUPPORTED_WORKSPACE_TREE', 'Workspace input matching rejects symlinks/submodules');
|
||||
entries.set(file, { object, mode });
|
||||
}
|
||||
const expectedPaths = input.snapshot.files.map(file => file.path).sort();
|
||||
if (JSON.stringify([...entries.keys()].sort()) !== JSON.stringify(expectedPaths))
|
||||
throw new RuntimeError(
|
||||
'WORKSPACE_TREE_MISMATCH',
|
||||
'Saved workspace and committed source have different files, including additions/deletions',
|
||||
);
|
||||
for (const file of input.snapshot.files) {
|
||||
const entry = entries.get(file.path)!;
|
||||
const blob = await git(['cat-file', 'blob', entry.object], 32 * 1024 * 1024 + 1);
|
||||
if (
|
||||
blob.length !== file.size ||
|
||||
createHash('sha256').update(blob).digest('hex') !== file.sha256 ||
|
||||
Boolean(file.mode & 0o111) !== (entry.mode === '100755')
|
||||
)
|
||||
throw new RuntimeError('WORKSPACE_TREE_MISMATCH', `Saved workspace differs from committed source: ${file.path}`);
|
||||
}
|
||||
return {
|
||||
sourceCommit: input.sourceCommit,
|
||||
targetCommit: input.targetCommit,
|
||||
snapshotRevision: input.snapshot.revision,
|
||||
snapshotDigest: input.snapshot.digest,
|
||||
matchedFiles: entries.size,
|
||||
};
|
||||
}
|
||||
@ -1,141 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdtemp, rm, writeFile, mkdir, chmod, symlink } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { executeCommand } from '../src/process.js';
|
||||
import {
|
||||
matchWorkspaceSnapshot,
|
||||
snapshotDigest,
|
||||
validateSnapshot,
|
||||
WORKSPACE_SNAPSHOT_EXCLUDED,
|
||||
type WorkspaceSnapshot,
|
||||
type WorkspaceSnapshotFile,
|
||||
} from '../src/workspace-snapshot.js';
|
||||
const require = createRequire(import.meta.url);
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map(dir => rm(dir, { recursive: true, force: true })));
|
||||
});
|
||||
const sha = (data: Buffer | string) => createHash('sha256').update(data).digest('hex');
|
||||
function snapshot(files: WorkspaceSnapshotFile[]): WorkspaceSnapshot {
|
||||
return { id: sha('manifest'), revision: 1, digest: snapshotDigest(files), files };
|
||||
}
|
||||
const file = (name: string, content: Buffer | string, mode = 0o644): WorkspaceSnapshotFile => ({
|
||||
path: name,
|
||||
sha256: sha(content),
|
||||
size: Buffer.byteLength(content),
|
||||
mode,
|
||||
});
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'wishforge-input-match-'));
|
||||
roots.push(root);
|
||||
const git = async (args: string[]) => {
|
||||
const r = await executeCommand({
|
||||
executable: 'git',
|
||||
args: [
|
||||
'-c',
|
||||
'core.hooksPath=/dev/null',
|
||||
'-c',
|
||||
'user.email=fixture@wishforge.invalid',
|
||||
'-c',
|
||||
'user.name=Fixture',
|
||||
...args,
|
||||
],
|
||||
cwd: root,
|
||||
});
|
||||
expect(r.exitCode, r.stderr).toBe(0);
|
||||
return r.stdout.trim();
|
||||
};
|
||||
await git(['init', '-b', 'main']);
|
||||
return {
|
||||
root,
|
||||
git,
|
||||
commit: async () => {
|
||||
await git(['add', '.']);
|
||||
await git(['commit', '-m', 'fixture']);
|
||||
return git(['rev-parse', 'HEAD']);
|
||||
},
|
||||
};
|
||||
}
|
||||
describe('saved workspace input matching in independent Git storage', () => {
|
||||
it('shares the exact snapshot exclusion policy with Theia and accepts JSONB key reordering', () => {
|
||||
expect(WORKSPACE_SNAPSHOT_EXCLUDED).toEqual(require('../../../apps/ide/coordination/index.cjs').EXCLUDED);
|
||||
const f = file('app.py', 'print(1)');
|
||||
const reordered = { mode: f.mode, size: f.size, sha256: f.sha256, path: f.path };
|
||||
expect(() => validateSnapshot({ ...snapshot([f]), files: [reordered] })).not.toThrow();
|
||||
});
|
||||
it('matches all files, binary bytes and Git executable bits without touching the worktree', async () => {
|
||||
const { root, git, commit } = await fixture();
|
||||
await writeFile(path.join(root, 'app.py'), 'print(1)');
|
||||
await writeFile(path.join(root, 'binary.dat'), Buffer.from([0, 255, 4]));
|
||||
await writeFile(path.join(root, 'run.sh'), '#!/bin/sh\ntrue\n');
|
||||
await chmod(path.join(root, 'run.sh'), 0o755);
|
||||
await mkdir(path.join(root, 'dist'));
|
||||
await writeFile(path.join(root, 'dist', 'generated'), 'ignored output');
|
||||
const source = await commit();
|
||||
const input = snapshot([
|
||||
file('app.py', 'print(1)'),
|
||||
file('binary.dat', Buffer.from([0, 255, 4])),
|
||||
file('run.sh', '#!/bin/sh\ntrue\n', 0o755),
|
||||
]);
|
||||
await writeFile(path.join(root, 'app.py'), 'unsaved-local-change');
|
||||
const before = await git(['status', '--porcelain']);
|
||||
expect(
|
||||
await matchWorkspaceSnapshot({ repository: root, sourceCommit: source, targetCommit: source, snapshot: input }),
|
||||
).toMatchObject({ matchedFiles: 3, snapshotDigest: input.digest });
|
||||
expect(await git(['status', '--porcelain'])).toBe(before);
|
||||
});
|
||||
it('rejects changed bytes, missing/deleted files, new files and executable bit differences', async () => {
|
||||
const { root, commit } = await fixture();
|
||||
await writeFile(path.join(root, 'app.ts'), 'original');
|
||||
const source = await commit();
|
||||
for (const files of [
|
||||
[file('app.ts', 'changed')],
|
||||
[],
|
||||
[file('app.ts', 'original'), file('new.ts', 'new')],
|
||||
[file('app.ts', 'original', 0o755)],
|
||||
])
|
||||
await expect(
|
||||
matchWorkspaceSnapshot({
|
||||
repository: root,
|
||||
sourceCommit: source,
|
||||
targetCommit: source,
|
||||
snapshot: snapshot(files),
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 'WORKSPACE_TREE_MISMATCH' });
|
||||
});
|
||||
it('requires the imported source to be committed onto the target and rejects symlinks', async () => {
|
||||
const { root, git, commit } = await fixture();
|
||||
await writeFile(path.join(root, 'app.ts'), 'base');
|
||||
const base = await commit();
|
||||
await writeFile(path.join(root, 'app.ts'), 'next');
|
||||
const next = await commit();
|
||||
await expect(
|
||||
matchWorkspaceSnapshot({
|
||||
repository: root,
|
||||
sourceCommit: next,
|
||||
targetCommit: base,
|
||||
snapshot: snapshot([file('app.ts', 'next')]),
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 'WORKSPACE_NOT_COMMITTED' });
|
||||
await symlink('app.ts', path.join(root, 'alias'));
|
||||
const linked = await commit();
|
||||
await expect(
|
||||
matchWorkspaceSnapshot({
|
||||
repository: root,
|
||||
sourceCommit: linked,
|
||||
targetCommit: linked,
|
||||
snapshot: snapshot([file('app.ts', 'next'), file('alias', 'app.ts')]),
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 'UNSUPPORTED_WORKSPACE_TREE' });
|
||||
expect(await git(['rev-parse', 'HEAD'])).toBe(linked);
|
||||
});
|
||||
it('rejects untrusted traversal, duplicate paths and invalid digests before invoking Git', () => {
|
||||
for (const name of ['../secret', '/etc/passwd', 'src/../a', 'node_modules/code', 'a\\b', 'a\n'])
|
||||
expect(() => validateSnapshot(snapshot([file(name, 'x')]))).toThrow();
|
||||
expect(() => validateSnapshot(snapshot([file('a', 'x'), file('a', 'x')]))).toThrow();
|
||||
expect(() => validateSnapshot({ ...snapshot([]), digest: sha('incorrect') })).toThrow();
|
||||
});
|
||||
});
|
||||
@ -52,18 +52,6 @@ try {
|
||||
);
|
||||
}
|
||||
add('WF_RUNNER_SIGNING_KEY_FILE', keyFile);
|
||||
await mkdir('.wishforge/gateway-keys', { recursive: true });
|
||||
const gatewayPrivate = resolve(root, '.wishforge/gateway-keys/private.pem');
|
||||
const gatewayPublic = resolve(root, '.wishforge/gateway-keys/public.pem');
|
||||
try {
|
||||
await readFile(gatewayPrivate);
|
||||
} catch {
|
||||
const { privateKey, publicKey } = generateKeyPairSync('ed25519');
|
||||
await writeFile(gatewayPrivate, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600, flag: 'wx' });
|
||||
await writeFile(gatewayPublic, publicKey.export({ type: 'spki', format: 'pem' }), { mode: 0o600, flag: 'wx' });
|
||||
}
|
||||
add('WF_IDE_GATEWAY_PRIVATE_KEY_FILE', gatewayPrivate);
|
||||
add('WF_IDE_GATEWAY_PUBLIC_KEY_FILE', gatewayPublic);
|
||||
add('WF_WORKSPACE_GATEWAY_TENANT_ID', 'demo');
|
||||
add('WF_TENANT_ID', 'demo');
|
||||
add('WF_IDE_GATEWAY_URL', 'http://127.0.0.1:4400');
|
||||
|
||||
@ -8,8 +8,6 @@ import { WorkspaceLifecycle } from '../apps/api/src/domain/workspace-lifecycle.j
|
||||
import { WorkspaceLaunch } from '../apps/api/src/domain/workspace-launch.js';
|
||||
import { Authenticator } from '../apps/api/src/auth.js';
|
||||
import { ControlPlane, record } from '../apps/api/src/domain/control-plane.js';
|
||||
import { WorkspaceIntegration } from '../apps/api/src/domain/workspace-integration.js';
|
||||
import { snapshotDigest } from '../packages/runtime/src/workspace-snapshot.js';
|
||||
import { MemoryStore } from './helpers/memory-store.js';
|
||||
const dirs: string[] = [];
|
||||
afterEach(async () => {
|
||||
@ -182,18 +180,7 @@ describe('tenant-owned gateway routes and human launch capability', () => {
|
||||
token: (options?.headers as Record<string, string>).authorization,
|
||||
});
|
||||
if (target.pathname === '/internal/lifecycle-state')
|
||||
return Response.json({
|
||||
workspaceId: row.workspaceId,
|
||||
gatewayConnections: 0,
|
||||
known: true,
|
||||
activeClients: 0,
|
||||
terminals: 0,
|
||||
debugSessions: 0,
|
||||
dirty: false,
|
||||
snapshotComplete: true,
|
||||
snapshotRevision: 1,
|
||||
diskDigest: 'f'.repeat(64),
|
||||
});
|
||||
return Response.json({ workspaceId: row.workspaceId, gatewayConnections: 0, known: true });
|
||||
return Response.json({
|
||||
workspaceId: row.workspaceId,
|
||||
revision: options?.method === 'PUT' ? 1 : 0,
|
||||
@ -239,59 +226,4 @@ describe('tenant-owned gateway routes and human launch capability', () => {
|
||||
])
|
||||
expect(() => validateGatewayLaunch(target, { launchUrl: url, expiresIn: 30 })).toThrow();
|
||||
});
|
||||
it('snapshot import and verifier state inspection use the same tenant route without mixing service credentials', async () => {
|
||||
const f = await fixture();
|
||||
const snapshot = { id: 'f'.repeat(64), revision: 1, digest: snapshotDigest([]), files: [] };
|
||||
const calls: Array<{ tenant: string; path: string; authorization: string }> = [];
|
||||
const fetcher: typeof fetch = async (url, options) => {
|
||||
const target = new URL(String(url));
|
||||
const tenant = target.hostname.startsWith('alpha.') ? 'alpha' : 'beta';
|
||||
calls.push({
|
||||
tenant,
|
||||
path: target.pathname,
|
||||
authorization: (options?.headers as Record<string, string>).authorization,
|
||||
});
|
||||
return Response.json({
|
||||
workspaceId: f.resources[tenant]!.workspaceId,
|
||||
dirty: false,
|
||||
activeClients: 0,
|
||||
activityDigest: 'b'.repeat(64),
|
||||
currentDiskDigest: snapshot.digest,
|
||||
latestSnapshot: snapshot,
|
||||
});
|
||||
};
|
||||
const integration = new WorkspaceIntegration(f.db, f.env, fetcher);
|
||||
for (const tenant of ['alpha', 'beta']) {
|
||||
const row = f.resources[tenant]!;
|
||||
await integration.importSnapshot(row.actor, row.runId, row.workspaceId, 'a'.repeat(40), `Bearer human-${tenant}`);
|
||||
const verifier = {
|
||||
...row.actor,
|
||||
kind: 'verifier' as const,
|
||||
userId: 'verifier',
|
||||
runId: row.runId,
|
||||
credentialId: 'generation',
|
||||
};
|
||||
await integration.acquire(verifier, row.runId, 1);
|
||||
await integration.recordMatch(verifier, row.runId, {
|
||||
leaseToken: 1,
|
||||
targetCommit: 'a'.repeat(40),
|
||||
snapshots: [
|
||||
{
|
||||
workspaceId: row.workspaceId,
|
||||
sourceCommit: 'a'.repeat(40),
|
||||
snapshotRevision: 1,
|
||||
snapshotDigest: snapshot.digest,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
expect(calls.filter(c => c.path === '/internal/integration-state').map(c => c.authorization)).toEqual([
|
||||
`Bearer ${'a'.repeat(32)}`,
|
||||
`Bearer ${'b'.repeat(32)}`,
|
||||
]);
|
||||
expect(calls.filter(c => c.path.endsWith('/snapshot')).map(c => c.authorization)).toEqual([
|
||||
'Bearer human-alpha',
|
||||
'Bearer human-beta',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
86
tests/integration-lease.test.ts
Normal file
86
tests/integration-lease.test.ts
Normal file
@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { Actor, Run } from '@wishforge/contracts';
|
||||
import { MemoryStore } from './helpers/memory-store.js';
|
||||
import { ControlPlane, record } from '../apps/api/src/domain/control-plane.js';
|
||||
import { Connections } from '../apps/api/src/domain/connections.js';
|
||||
|
||||
const owner: Actor = { tenantId: 'alpha', userId: 'owner', role: 'owner', kind: 'human' };
|
||||
|
||||
async function fixture() {
|
||||
const db = new MemoryStore();
|
||||
db.seed('alpha');
|
||||
const control = new ControlPlane(db, { NODE_ENV: 'test', WF_VAULT_KEY: 'a'.repeat(64) });
|
||||
const project = await control.createProject(owner, {
|
||||
name: 'Integration queue',
|
||||
repositoryUrl: 'https://example.test/repo.git',
|
||||
verificationCommands: [['node', '--test']],
|
||||
});
|
||||
await new Connections(db, control.env).create(owner, {
|
||||
provider: 'codex',
|
||||
label: 'fixture',
|
||||
apiKey: 'fixture-only-key',
|
||||
});
|
||||
/** Submits a run and leases it to a run-scoped verifier of a fixed generation. */
|
||||
async function verifierFor(key: string) {
|
||||
const { run_id: id } = await control.submit(
|
||||
owner,
|
||||
project.id,
|
||||
{ goal: `Change ${key}`, acceptanceCriteria: ['It works'] },
|
||||
`integration-${key}`,
|
||||
);
|
||||
const generation = `generation-${key}`;
|
||||
await db.transaction('alpha', async tx => {
|
||||
const run = (await tx.get<Run>('run', id))!;
|
||||
run.executionGeneration = generation;
|
||||
await tx.put('run', run);
|
||||
});
|
||||
const actor: Actor = { ...owner, kind: 'verifier', userId: `verifier-${key}`, runId: id, credentialId: generation };
|
||||
const leased = await control.lease(actor, id, `worker-${key}`, generation);
|
||||
return { id, actor, token: leased.lease!.token };
|
||||
}
|
||||
return { db, control, project, verifierFor };
|
||||
}
|
||||
|
||||
describe('project integration lease', () => {
|
||||
it('admits one integrating run per project and fences stale owners', async () => {
|
||||
const f = await fixture();
|
||||
const first = await f.verifierFor('one');
|
||||
const second = await f.verifierFor('two');
|
||||
const lease = await f.control.integration.acquire(first.actor, first.id, first.token);
|
||||
expect(lease).toMatchObject({ runId: first.id, fence: 1 });
|
||||
expect(await f.control.integration.acquire(first.actor, first.id, first.token)).toMatchObject({ fence: 1 });
|
||||
await expect(f.control.integration.acquire(second.actor, second.id, second.token)).rejects.toMatchObject({
|
||||
code: 'INTEGRATION_BUSY',
|
||||
});
|
||||
await expect(f.control.integration.renew(first.actor, first.id, first.token, 99)).rejects.toMatchObject({
|
||||
code: 'STALE_INTEGRATION_FENCE',
|
||||
});
|
||||
expect(await f.control.integration.release(first.actor, first.id, first.token, 1)).toEqual({ released: true });
|
||||
expect(await f.control.integration.acquire(second.actor, second.id, second.token)).toMatchObject({ fence: 2 });
|
||||
});
|
||||
|
||||
it('requires the live lease of this execution before integrating or building', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.verifierFor('gate');
|
||||
await expect(f.control.integration.enforce(run.actor, run.id, run.token)).rejects.toMatchObject({
|
||||
code: 'INTEGRATION_LEASE_REQUIRED',
|
||||
});
|
||||
await f.control.integration.acquire(run.actor, run.id, run.token);
|
||||
await expect(f.control.integration.enforce(run.actor, run.id, run.token)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not let an open IDE workspace block agent integration', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.verifierFor('ide');
|
||||
await f.db.transaction('alpha', tx =>
|
||||
tx.put('workspace', {
|
||||
...record('alpha'),
|
||||
projectId: f.project.id,
|
||||
status: 'ready',
|
||||
upstreamUrl: 'http://127.0.0.1:4300',
|
||||
}),
|
||||
);
|
||||
await f.control.integration.acquire(run.actor, run.id, run.token);
|
||||
await expect(f.control.integration.enforce(run.actor, run.id, run.token)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@ -4,7 +4,6 @@ import { MemoryStore } from './helpers/memory-store.js';
|
||||
import { ControlPlane } from '../apps/api/src/domain/control-plane.js';
|
||||
import { Connections } from '../apps/api/src/domain/connections.js';
|
||||
import { Releases } from '../apps/api/src/domain/releases.js';
|
||||
import { WorkspaceIntegration } from '../apps/api/src/domain/workspace-integration.js';
|
||||
import { digest } from '../apps/api/src/domain/policy.js';
|
||||
import {
|
||||
configuredVerificationProfiles,
|
||||
@ -44,7 +43,7 @@ async function fixture(withProfile = true) {
|
||||
const leased = await dev.lease(verifier, runId, 'verifier');
|
||||
const env = { NODE_ENV: 'production', WF_VERIFICATION_PROFILES_JSON: JSON.stringify([profile]) };
|
||||
const control = new ControlPlane(db, env);
|
||||
await new WorkspaceIntegration(db, env).acquire(verifier, runId, leased.lease!.token);
|
||||
await control.integration.acquire(verifier, runId, leased.lease!.token);
|
||||
const evidence = {
|
||||
leaseToken: leased.lease!.token,
|
||||
runId,
|
||||
|
||||
@ -1,228 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { Actor, Run } from '@wishforge/contracts';
|
||||
import { MemoryStore } from './helpers/memory-store.js';
|
||||
import { ControlPlane, record } from '../apps/api/src/domain/control-plane.js';
|
||||
import { WorkspaceIntegration } from '../apps/api/src/domain/workspace-integration.js';
|
||||
import { Connections } from '../apps/api/src/domain/connections.js';
|
||||
import { snapshotDigest } from '../packages/runtime/src/workspace-snapshot.js';
|
||||
const owner: Actor = { tenantId: 'alpha', userId: 'owner', role: 'owner', kind: 'human' };
|
||||
const source = 'a'.repeat(40);
|
||||
const snapshot = { id: 'a'.repeat(64), revision: 1, digest: snapshotDigest([]), files: [] };
|
||||
async function fixture(ide = true, generation: string | undefined = 'generation-one') {
|
||||
const db = new MemoryStore();
|
||||
db.seed('alpha');
|
||||
const dev = new ControlPlane(db, { NODE_ENV: 'test', WF_VAULT_KEY: 'a'.repeat(64) });
|
||||
const project = await dev.createProject(owner, {
|
||||
name: 'Saved tree',
|
||||
repositoryUrl: 'https://example.test/repo.git',
|
||||
verificationCommands: [['node', '--test']],
|
||||
});
|
||||
await new Connections(db, dev.env).create(owner, { provider: 'codex', label: 'fixture', apiKey: 'fixture-only' });
|
||||
const { run_id: id } = await dev.submit(
|
||||
owner,
|
||||
project.id,
|
||||
{ goal: 'Add search', acceptanceCriteria: ['Search returns matching records'] },
|
||||
'workspace-input-fixture',
|
||||
);
|
||||
await db.transaction('alpha', async tx => {
|
||||
const run = (await tx.get<Run>('run', id))!;
|
||||
run.executionGeneration = generation;
|
||||
await tx.put('run', run);
|
||||
});
|
||||
const verifier: Actor = { ...owner, kind: 'verifier', userId: 'verifier', runId: id, credentialId: generation };
|
||||
const run = await dev.lease(verifier, id, 'verifier', generation);
|
||||
const token = run.lease!.token;
|
||||
const workspace = {
|
||||
...record('alpha'),
|
||||
projectId: project.id,
|
||||
status: 'ready',
|
||||
upstreamUrl: 'http://127.0.0.1:4300',
|
||||
};
|
||||
if (ide) await db.transaction('alpha', tx => tx.put('workspace', workspace));
|
||||
const state = {
|
||||
workspaceId: workspace.id,
|
||||
latestSnapshot: snapshot,
|
||||
currentDiskDigest: snapshot.digest,
|
||||
activityDigest: 'b'.repeat(64),
|
||||
dirty: false,
|
||||
activeClients: 1,
|
||||
};
|
||||
let failure = false;
|
||||
const calls: Array<{ url: string; options: RequestInit | undefined }> = [];
|
||||
const fetcher: typeof fetch = async (url, options) => {
|
||||
calls.push({ url: String(url), options });
|
||||
return new Response(failure ? '{}' : JSON.stringify(state), {
|
||||
status: failure ? 503 : 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
};
|
||||
const env = {
|
||||
NODE_ENV: 'production',
|
||||
WF_WORKSPACE_GATEWAY_BASE: 'https://gateway.example.test',
|
||||
WF_WORKSPACE_GATEWAY_TOKEN: 'g'.repeat(32),
|
||||
WF_WORKSPACE_GATEWAY_TENANT_ID: 'alpha',
|
||||
};
|
||||
const gate = new WorkspaceIntegration(db, env, fetcher);
|
||||
const acquire = () => gate.acquire(verifier, id, token);
|
||||
const save = () => gate.importSnapshot(owner, id, workspace.id, source, 'Bearer human-fixture');
|
||||
const match = () =>
|
||||
gate.recordMatch(verifier, id, {
|
||||
leaseToken: token,
|
||||
targetCommit: source,
|
||||
snapshots: [
|
||||
{
|
||||
workspaceId: workspace.id,
|
||||
sourceCommit: source,
|
||||
snapshotRevision: snapshot.revision,
|
||||
snapshotDigest: snapshot.digest,
|
||||
},
|
||||
],
|
||||
});
|
||||
return {
|
||||
db,
|
||||
dev,
|
||||
project,
|
||||
workspace,
|
||||
id,
|
||||
verifier,
|
||||
token,
|
||||
state,
|
||||
env,
|
||||
gate,
|
||||
calls,
|
||||
acquire,
|
||||
save,
|
||||
match,
|
||||
fail: () => {
|
||||
failure = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
describe('workspace input gate and global project integration lease', () => {
|
||||
it('requires the production global project lease even without an IDE and keeps legacy development compatible', async () => {
|
||||
const f = await fixture(false);
|
||||
await expect(f.gate.enforce(f.verifier, f.id, f.token)).rejects.toMatchObject({
|
||||
code: 'INTEGRATION_LEASE_REQUIRED',
|
||||
});
|
||||
expect((await f.dev.run(owner, f.id)).waitingReason).toBe('integration_lease_required');
|
||||
const legacy = await fixture(false, '');
|
||||
await expect(
|
||||
new WorkspaceIntegration(legacy.db, { NODE_ENV: 'test' }).enforce(legacy.verifier, legacy.id, legacy.token),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
it('waits when a ready workspace has no coordinated imported snapshot', async () => {
|
||||
const f = await fixture();
|
||||
await f.acquire();
|
||||
await expect(f.gate.enforce(f.verifier, f.id, f.token)).rejects.toMatchObject({
|
||||
code: 'WORKSPACE_SNAPSHOT_REQUIRED',
|
||||
});
|
||||
expect((await f.dev.run(owner, f.id)).status).toBe('waiting');
|
||||
});
|
||||
it('fetches the saved snapshot server-side with human authorization, then requires independent matching', async () => {
|
||||
const f = await fixture();
|
||||
await f.acquire();
|
||||
expect(await f.save()).toMatchObject({ trust: 'input-only', sourceCommit: source });
|
||||
expect(f.calls[0]!.url).toContain(`/workspaces/${f.workspace.id}/_wishforge/integration/snapshot`);
|
||||
expect(f.calls[0]!.options!.headers).toMatchObject({ authorization: 'Bearer human-fixture' });
|
||||
await f.match();
|
||||
await expect(f.gate.enforce(f.verifier, f.id, f.token)).resolves.toBeUndefined();
|
||||
expect(await f.db.transaction('alpha', tx => tx.list('evidence'))).toEqual([]);
|
||||
});
|
||||
it('does not treat an imported snapshot as a test attestation or unlock by itself', async () => {
|
||||
const f = await fixture();
|
||||
await f.acquire();
|
||||
await f.save();
|
||||
await expect(f.gate.enforce(f.verifier, f.id, f.token)).rejects.toMatchObject({
|
||||
code: 'WORKSPACE_GIT_MATCH_REQUIRED',
|
||||
});
|
||||
});
|
||||
it.each(['dirty', 'disk', 'membership', 'revision', 'unavailable'])(
|
||||
'blocks when current workspace state changes: %s',
|
||||
async change => {
|
||||
const f = await fixture();
|
||||
await f.acquire();
|
||||
await f.save();
|
||||
await f.match();
|
||||
if (change === 'dirty') f.state.dirty = true;
|
||||
if (change === 'disk') f.state.currentDiskDigest = 'c'.repeat(64);
|
||||
if (change === 'membership') f.state.activityDigest = 'c'.repeat(64);
|
||||
if (change === 'revision') f.state.latestSnapshot = { ...snapshot, revision: 2 };
|
||||
if (change === 'unavailable') f.fail();
|
||||
await expect(f.gate.enforce(f.verifier, f.id, f.token)).rejects.toMatchObject({
|
||||
code: change === 'unavailable' ? 'WORKSPACE_GATE_UNAVAILABLE' : 'WORKSPACE_INPUT_CHANGED',
|
||||
});
|
||||
expect((await f.dev.run(owner, f.id)).status).toBe('waiting');
|
||||
},
|
||||
);
|
||||
it('requires human edit ACL for import and independent verifier for matching', async () => {
|
||||
const f = await fixture();
|
||||
await expect(
|
||||
f.gate.importSnapshot({ ...owner, kind: 'connector' }, f.id, f.workspace.id, source, 'Bearer connector'),
|
||||
).rejects.toMatchObject({ code: 'HUMAN_APPROVAL_REQUIRED' });
|
||||
await expect(
|
||||
f.gate.importSnapshot(
|
||||
{ ...owner, userId: 'outsider', role: 'developer' },
|
||||
f.id,
|
||||
f.workspace.id,
|
||||
source,
|
||||
'Bearer outsider',
|
||||
),
|
||||
).rejects.toMatchObject({ code: 'NOT_FOUND' });
|
||||
await expect(
|
||||
f.gate.recordMatch(owner, f.id, { leaseToken: f.token, targetCommit: source, snapshots: [] }),
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
expect(f.calls).toEqual([]);
|
||||
});
|
||||
it('rejects forged snapshot metadata and old generation identities', async () => {
|
||||
const f = await fixture();
|
||||
await f.acquire();
|
||||
await f.save();
|
||||
await expect(
|
||||
f.gate.recordMatch(f.verifier, f.id, {
|
||||
leaseToken: f.token,
|
||||
targetCommit: source,
|
||||
snapshots: [
|
||||
{ workspaceId: f.workspace.id, sourceCommit: source, snapshotRevision: 2, snapshotDigest: snapshot.digest },
|
||||
],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 'WORKSPACE_INPUT_CHANGED' });
|
||||
await f.db.transaction('alpha', async tx => {
|
||||
const run = (await tx.get<Run>('run', f.id))!;
|
||||
run.executionGeneration = 'replacement';
|
||||
await tx.put('run', run);
|
||||
});
|
||||
await expect(f.gate.enforce(f.verifier, f.id, f.token)).rejects.toMatchObject({ code: 'EXECUTION_REVOKED' });
|
||||
expect((await f.dev.run(owner, f.id)).status).toBe('running');
|
||||
});
|
||||
it('serializes separate runs and fences stale release/renew after expired ownership', async () => {
|
||||
const f = await fixture(false);
|
||||
const first = await f.acquire();
|
||||
expect((await f.acquire()).fence).toBe(first.fence);
|
||||
const { run_id: id } = await f.dev.submit(
|
||||
owner,
|
||||
f.project.id,
|
||||
{ goal: 'Second change', acceptanceCriteria: ['A separate result'] },
|
||||
'second-workspace-run',
|
||||
);
|
||||
await f.db.transaction('alpha', async tx => {
|
||||
const run = (await tx.get<Run>('run', id))!;
|
||||
run.executionGeneration = 'generation-two';
|
||||
await tx.put('run', run);
|
||||
});
|
||||
const actor = { ...f.verifier, runId: id, credentialId: 'generation-two' };
|
||||
const second = await f.dev.lease(actor, id, 'verifier', 'generation-two');
|
||||
await expect(f.gate.acquire(actor, id, second.lease!.token)).rejects.toMatchObject({ code: 'INTEGRATION_BUSY' });
|
||||
await f.db.transaction('alpha', async tx => {
|
||||
const p = (await tx.get('project', f.project.id))!;
|
||||
(p.integrationLease as { expiresAt: string }).expiresAt = new Date(0).toISOString();
|
||||
await tx.put('project', p);
|
||||
});
|
||||
const replacement = await f.gate.acquire(actor, id, second.lease!.token);
|
||||
expect(replacement.fence).toBe(first.fence + 1);
|
||||
expect(await f.gate.release(f.verifier, f.id, f.token, first.fence)).toEqual({ released: false });
|
||||
await expect(f.gate.renew(f.verifier, f.id, f.token, first.fence)).rejects.toMatchObject({
|
||||
code: 'INTEGRATION_LEASE_REQUIRED',
|
||||
});
|
||||
await expect(f.gate.enforce(actor, id, second.lease!.token)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@ -3,7 +3,6 @@ import type { Actor, Entity } from '@wishforge/contracts';
|
||||
import { MemoryStore } from './helpers/memory-store.js';
|
||||
import { ControlPlane, record } from '../apps/api/src/domain/control-plane.js';
|
||||
import { WorkspaceLifecycle, WORKSPACE_IDLE_MS } from '../apps/api/src/domain/workspace-lifecycle.js';
|
||||
import { snapshotDigest } from '../packages/runtime/src/workspace-snapshot.js';
|
||||
const owner: Actor = { tenantId: 'alpha', userId: 'owner', role: 'owner', kind: 'human' };
|
||||
async function fixture() {
|
||||
const db = new MemoryStore();
|
||||
@ -32,34 +31,16 @@ async function fixture() {
|
||||
await tx.put('workspace', workspace);
|
||||
await tx.put('environment', environment);
|
||||
});
|
||||
const snapshot = { id: 'a'.repeat(64), revision: 1, digest: snapshotDigest([]), files: [] };
|
||||
const safety = {
|
||||
workspaceId: workspace.id,
|
||||
gatewayConnections: 0,
|
||||
known: true,
|
||||
activeClients: 0,
|
||||
terminals: 0,
|
||||
debugSessions: 0,
|
||||
dirty: false,
|
||||
snapshotComplete: true,
|
||||
snapshotRevision: 1,
|
||||
diskDigest: snapshot.digest,
|
||||
};
|
||||
const activity = { workspaceId: workspace.id, gatewayConnections: 0, known: true };
|
||||
let state = { workspaceId: workspace.id, revision: 0, desired: 'running', status: 'ready' };
|
||||
let lose = false;
|
||||
let unavailable = false;
|
||||
let saveBlocked = false;
|
||||
const calls: Array<{ url: string; method: string }> = [];
|
||||
const fetcher: typeof fetch = async (url, options) => {
|
||||
const target = new URL(String(url));
|
||||
const method = options?.method ?? 'GET';
|
||||
calls.push({ url: target.pathname, method });
|
||||
if (target.pathname.endsWith('/snapshot'))
|
||||
return Response.json(
|
||||
{ workspaceId: workspace.id, dirty: false, latestSnapshot: snapshot, currentDiskDigest: snapshot.digest },
|
||||
{ status: saveBlocked ? 409 : 200 },
|
||||
);
|
||||
if (target.pathname === '/internal/lifecycle-state') return Response.json(safety);
|
||||
if (target.pathname === '/internal/lifecycle-state') return Response.json(activity);
|
||||
if (unavailable) throw new Error('offline');
|
||||
if (method === 'PUT') {
|
||||
const input = JSON.parse(String(options?.body));
|
||||
@ -93,16 +74,13 @@ async function fixture() {
|
||||
environment,
|
||||
lifecycle,
|
||||
calls,
|
||||
safety,
|
||||
activity,
|
||||
get,
|
||||
items,
|
||||
age,
|
||||
setUnavailable: () => {
|
||||
unavailable = true;
|
||||
},
|
||||
blockSave: () => {
|
||||
saveBlocked = true;
|
||||
},
|
||||
lose: () => {
|
||||
lose = true;
|
||||
},
|
||||
@ -122,19 +100,19 @@ describe('durable workspace lifecycle without application deployment changes', (
|
||||
it('uses the scoped tenant provisioner resolver and never falls back to another tenant', async () => {
|
||||
const f = await fixture();
|
||||
f.env.WF_PROVISIONER_TENANT_ID = 'beta';
|
||||
await expect(
|
||||
f.lifecycle.manual(owner, f.workspace.id, 'pause', 'wrong-tenant-route', 'Bearer user'),
|
||||
).rejects.toMatchObject({ code: 'WORKSPACE_LIFECYCLE_UNCONFIGURED' });
|
||||
await expect(f.lifecycle.manual(owner, f.workspace.id, 'pause', 'wrong-tenant-route')).rejects.toMatchObject({
|
||||
code: 'WORKSPACE_LIFECYCLE_UNCONFIGURED',
|
||||
});
|
||||
await f.lifecycle.scheduleIdle('alpha');
|
||||
expect(f.calls).toEqual([]);
|
||||
expect(await f.items()).toEqual([]);
|
||||
});
|
||||
it('requires a human save barrier, deduplicates pause, and never reports paused before observation', async () => {
|
||||
it('deduplicates pause and never reports paused before observation', async () => {
|
||||
const f = await fixture();
|
||||
const result = await f.lifecycle.manual(owner, f.workspace.id, 'pause', 'pause-key-one', 'Bearer user');
|
||||
const result = await f.lifecycle.manual(owner, f.workspace.id, 'pause', 'pause-key-one');
|
||||
expect(result).toMatchObject({ status: 'pausing' });
|
||||
await f.lifecycle.manual(owner, f.workspace.id, 'pause', 'pause-key-one', 'Bearer user');
|
||||
expect(f.calls.filter(c => c.url.endsWith('/snapshot'))).toHaveLength(1);
|
||||
await f.lifecycle.manual(owner, f.workspace.id, 'pause', 'pause-key-one');
|
||||
expect(await f.items()).toHaveLength(1);
|
||||
const [item] = await f.items();
|
||||
await f.lifecycle.reconcile('alpha', item!);
|
||||
expect((await f.get()).status).toBe('pausing');
|
||||
@ -146,11 +124,11 @@ describe('durable workspace lifecycle without application deployment changes', (
|
||||
});
|
||||
it('remembers a no-op resume key so a later retry cannot resume a subsequently paused workspace', async () => {
|
||||
const f = await fixture();
|
||||
expect(await f.lifecycle.manual(owner, f.workspace.id, 'resume', 'noop-resume-key', 'Bearer user')).toMatchObject({
|
||||
expect(await f.lifecycle.manual(owner, f.workspace.id, 'resume', 'noop-resume-key')).toMatchObject({
|
||||
status: 'ready',
|
||||
});
|
||||
await f.setStatus('paused');
|
||||
expect(await f.lifecycle.manual(owner, f.workspace.id, 'resume', 'noop-resume-key', 'Bearer user')).toMatchObject({
|
||||
expect(await f.lifecycle.manual(owner, f.workspace.id, 'resume', 'noop-resume-key')).toMatchObject({
|
||||
status: 'ready',
|
||||
});
|
||||
expect((await f.get()).status).toBe('paused');
|
||||
@ -159,7 +137,7 @@ describe('durable workspace lifecycle without application deployment changes', (
|
||||
it('resumes via replicas one and waits for readiness', async () => {
|
||||
const f = await fixture();
|
||||
await f.setStatus('paused');
|
||||
await f.lifecycle.manual(owner, f.workspace.id, 'resume', 'resume-key-one', 'Bearer user');
|
||||
await f.lifecycle.manual(owner, f.workspace.id, 'resume', 'resume-key-one');
|
||||
const [item] = await f.items();
|
||||
await f.lifecycle.reconcile('alpha', item!);
|
||||
expect((await f.get()).status).toBe('resuming');
|
||||
@ -167,11 +145,10 @@ describe('durable workspace lifecycle without application deployment changes', (
|
||||
await f.lifecycle.reconcile('alpha', item!);
|
||||
expect((await f.get()).status).toBe('ready');
|
||||
expect(Date.parse(String((await f.get()).lastActivityAt))).toBeGreaterThan(Date.now() - 1000);
|
||||
expect(f.calls.some(c => c.url.endsWith('/snapshot'))).toBe(false);
|
||||
});
|
||||
it('a lost scale response is unknown, then observed without a second mutation', async () => {
|
||||
const f = await fixture();
|
||||
await f.lifecycle.manual(owner, f.workspace.id, 'pause', 'pause-key-lost', 'Bearer user');
|
||||
await f.lifecycle.manual(owner, f.workspace.id, 'pause', 'pause-key-lost');
|
||||
f.lose();
|
||||
const [item] = await f.items();
|
||||
await f.lifecycle.reconcile('alpha', item!);
|
||||
@ -183,30 +160,24 @@ describe('durable workspace lifecycle without application deployment changes', (
|
||||
});
|
||||
it('unknown observation cannot result in a blind mutation or ready response', async () => {
|
||||
const f = await fixture();
|
||||
await f.lifecycle.manual(owner, f.workspace.id, 'pause', 'pause-key-offline', 'Bearer user');
|
||||
await f.lifecycle.manual(owner, f.workspace.id, 'pause', 'pause-key-offline');
|
||||
f.setUnavailable();
|
||||
await f.lifecycle.reconcile('alpha', (await f.items())[0]!);
|
||||
expect((await f.get()).status).toBe('unknown');
|
||||
expect(f.calls.filter(c => c.method === 'PUT')).toHaveLength(0);
|
||||
});
|
||||
it('enforces human edit membership and a successful save before queuing pause', async () => {
|
||||
it('enforces human edit membership before queuing pause', async () => {
|
||||
const f = await fixture();
|
||||
for (const actor of [
|
||||
{ ...owner, kind: 'connector' as const },
|
||||
{ ...owner, userId: 'viewer', role: 'viewer' as const },
|
||||
{ ...owner, userId: 'absent', role: 'owner' as const },
|
||||
])
|
||||
await expect(
|
||||
f.lifecycle.manual(actor, f.workspace.id, 'pause', 'pause-key-acl', 'Bearer user'),
|
||||
).rejects.toThrow();
|
||||
f.blockSave();
|
||||
await expect(
|
||||
f.lifecycle.manual(owner, f.workspace.id, 'pause', 'pause-key-save', 'Bearer user'),
|
||||
).rejects.toMatchObject({ code: 'WORKSPACE_SAVE_REQUIRED' });
|
||||
await expect(f.lifecycle.manual(actor, f.workspace.id, 'pause', 'pause-key-acl')).rejects.toThrow();
|
||||
expect((await f.get()).status).toBe('ready');
|
||||
expect(await f.items()).toEqual([]);
|
||||
});
|
||||
it('queues automatic pause only after 30 minutes with complete quiescence evidence', async () => {
|
||||
it('queues automatic pause only after 30 minutes without gateway connections', async () => {
|
||||
const f = await fixture();
|
||||
await f.lifecycle.scheduleIdle('alpha');
|
||||
expect((await f.get()).status).toBe('pausing');
|
||||
@ -215,13 +186,11 @@ describe('durable workspace lifecycle without application deployment changes', (
|
||||
await f.lifecycle.reconcile('alpha', (await f.items())[0]!);
|
||||
expect(f.calls.filter(c => c.method === 'PUT')).toHaveLength(1);
|
||||
});
|
||||
it.each(['gatewayConnections', 'activeClients', 'terminals', 'debugSessions', 'dirty', 'known', 'snapshotComplete'])(
|
||||
'does not automatically stop active or unknown workspace (%s)',
|
||||
async field => {
|
||||
it.each([{ gatewayConnections: 1 }, { known: false }])(
|
||||
'does not automatically stop an active or unknown workspace (%o)',
|
||||
async change => {
|
||||
const f = await fixture();
|
||||
Object.assign(f.safety, {
|
||||
[field]: ['known', 'snapshotComplete'].includes(field) ? false : field === 'dirty' ? true : 1,
|
||||
});
|
||||
Object.assign(f.activity, change);
|
||||
await f.lifecycle.scheduleIdle('alpha');
|
||||
expect((await f.get()).status).toBe('ready');
|
||||
expect(await f.items()).toEqual([]);
|
||||
@ -250,7 +219,7 @@ describe('durable workspace lifecycle without application deployment changes', (
|
||||
await f.lifecycle.scheduleIdle('alpha');
|
||||
const [pause] = await f.items();
|
||||
await f.age();
|
||||
f.safety.terminals = 1;
|
||||
f.activity.gatewayConnections = 1;
|
||||
await f.lifecycle.reconcile('alpha', pause!);
|
||||
expect(f.calls.filter(c => c.method === 'PUT')).toHaveLength(0);
|
||||
expect((await f.get()).status).toBe('resuming');
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user