Adds prettier 3.9.8 (exact) with a shared config (single quotes, 120 columns, trailing commas), .prettierignore, .editorconfig and the `format` / `format:check` scripts, then formats all TypeScript, JavaScript, CSS, JSON and YAML sources. Purely mechanical: no behaviour change. Typecheck passes, the vitest suite and the 74 IDE node tests produce the same results as before (socket-binding tests still cannot run inside this sandbox). Previously the longest source line was ~3000 characters; reviewing the following semantic changes now produces readable diffs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
300 lines
12 KiB
JavaScript
300 lines
12 KiB
JavaScript
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');
|
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
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();
|
|
}),
|
|
);
|
|
});
|