eust-w 0ef99b1e6d style: add Prettier and EditorConfig, format the codebase
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>
2026-10-19 13:32:43 +08:00

285 lines
11 KiB
JavaScript

import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { runKubectl } from './provisioner.mjs';
const safe = /^[a-zA-Z0-9_-]{1,128}$/;
export function renderWorkspaceResources(config, input, image, collaboration) {
if (!image || !/^[^\s]+@sha256:[a-f0-9]{64}$/.test(image)) throw new Error('UNCONFIGURED_THEIA_IMAGE');
if (
!input ||
input.tenantId !== config.tenantId ||
!safe.test(input.projectId ?? '') ||
!safe.test(input.workspaceId ?? '') ||
Object.keys(input).some(k => !['tenantId', 'projectId', 'workspaceId'].includes(k))
)
throw new Error('INVALID_WORKSPACE_REQUEST');
const name = `wf-ide-${createHash('sha256').update(`${input.tenantId}/${input.workspaceId}`).digest('hex').slice(0, 24)}`;
const labels = {
'wishforge.io/component': 'ide',
'wishforge.io/workspace': name,
'app.kubernetes.io/managed-by': 'wishforge-provisioner',
};
const metadata = n => ({ name: n, namespace: config.namespace, labels });
const resources = [
{
apiVersion: 'v1',
kind: 'PersistentVolumeClaim',
metadata: metadata(name),
spec: {
storageClassName: config.storageClass,
accessModes: ['ReadWriteOnce'],
resources: { requests: { storage: config.storageSize } },
},
},
{
apiVersion: 'networking.k8s.io/v1',
kind: 'NetworkPolicy',
metadata: metadata(`${name}-isolation`),
spec: {
podSelector: { matchLabels: { 'wishforge.io/workspace': name } },
policyTypes: ['Ingress', 'Egress'],
ingress: [
{
from: [
{
namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': config.controlNamespace } },
podSelector: { matchLabels: { 'wishforge.io/component': 'workspace-gateway' } },
},
],
ports: [{ protocol: 'TCP', port: 3000 }],
},
],
egress: [
{
to: [
{
namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': 'kube-system' } },
podSelector: { matchLabels: { 'k8s-app': 'kube-dns' } },
},
],
ports: [
{ protocol: 'UDP', port: 53 },
{ protocol: 'TCP', port: 53 },
],
},
],
},
},
{
apiVersion: 'apps/v1',
kind: 'Deployment',
metadata: metadata(name),
spec: {
replicas: 1,
strategy: { type: 'Recreate' },
selector: { matchLabels: { 'wishforge.io/workspace': name } },
template: {
metadata: { labels },
spec: {
runtimeClassName: config.runtimeClass,
automountServiceAccountToken: false,
securityContext: {
runAsNonRoot: true,
runAsUser: 1000,
runAsGroup: 1000,
fsGroup: 1000,
seccompProfile: { type: 'RuntimeDefault' },
},
initContainers: [
{
name: 'workspace-directories',
image,
command: [
'node',
'-e',
"const fs=require('fs');for(const dir of ['workspace','config'])fs.mkdirSync('/home/theia/data/'+dir,{recursive:true});",
],
securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] } },
volumeMounts: [{ name: 'workspace', mountPath: '/home/theia/data' }],
},
],
containers: [
{
name: 'theia',
image,
ports: [{ containerPort: 3000 }],
env: [
{ name: 'NODE_ENV', value: 'production' },
{ name: 'WISHFORGE_GATEWAY_ENFORCED', value: 'true' },
{ name: 'WISHFORGE_WORKSPACE_PATH', value: '/home/theia/data/workspace' },
{ name: 'THEIA_CONFIG_DIR', value: '/home/theia/data/config' },
{ name: 'WISHFORGE_IDE_HOST', value: '0.0.0.0' },
{ name: 'WISHFORGE_IDE_PORT', value: '3000' },
{ name: 'WISHFORGE_COLLABORATION_ENABLED', value: 'false' },
{ name: 'COLLABORATION_SERVER_URL', value: 'https://disabled.invalid/' },
],
resources: { requests: { cpu: '500m', memory: '1Gi' }, limits: { cpu: '2', memory: '4Gi' } },
securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] } },
readinessProbe: { httpGet: { path: '/', port: 3000 }, initialDelaySeconds: 10, periodSeconds: 5 },
volumeMounts: [{ name: 'workspace', mountPath: '/home/theia/data' }],
},
],
volumes: [{ name: 'workspace', persistentVolumeClaim: { claimName: name } }],
},
},
},
},
{
apiVersion: 'v1',
kind: 'Service',
metadata: metadata(name),
spec: {
selector: { 'wishforge.io/workspace': name },
type: 'ClusterIP',
ports: [{ port: 3000, targetPort: 3000 }],
},
},
];
const workspacePod = resources.find(r => r.kind === 'Deployment').spec.template.spec;
workspacePod.containers[0].securityContext.readOnlyRootFilesystem = true;
workspacePod.containers[0].env.push(
{ name: 'HOME', value: '/home/theia/data' },
{ name: 'WF_TENANT_ID', value: input.tenantId },
{ name: 'WF_WORKSPACE_ID', value: input.workspaceId },
);
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 ?? ''))
throw new Error('UNCONFIGURED_OCT_WORKSPACE_IMAGE');
const gateway = new URL(collaboration.gatewayBase);
if (
gateway.protocol !== 'https:' ||
gateway.username ||
gateway.password ||
gateway.pathname !== '/' ||
gateway.search ||
gateway.hash
)
throw new Error('INVALID_PUBLIC_WORKSPACE_GATEWAY');
const pod = resources.find(r => r.kind === 'Deployment').spec.template.spec;
pod.containers[0].env.push({
name: 'WF_COLLABORATION_GATEWAY_URL',
value: `${gateway.origin}/workspaces/${input.workspaceId}/collaboration/`,
});
pod.containers.push({
name: 'collaboration',
image: collaboration.image,
env: [
{ name: 'WF_TENANT_ID', value: input.tenantId },
{ name: 'WF_WORKSPACE_ID', value: input.workspaceId },
{ name: 'WISHFORGE_GATEWAY_ENFORCED', value: 'true' },
],
ports: [{ containerPort: 8100 }],
resources: { requests: { cpu: '100m', memory: '128Mi' }, limits: { cpu: '500m', memory: '512Mi' } },
securityContext: {
allowPrivilegeEscalation: false,
readOnlyRootFilesystem: true,
capabilities: { drop: ['ALL'] },
},
readinessProbe: { httpGet: { path: '/api/meta', port: 8100 }, initialDelaySeconds: 3, periodSeconds: 5 },
});
resources.find(r => r.kind === 'Service').spec.ports = [
{ name: 'theia', port: 3000, targetPort: 3000 },
{ name: 'collaboration', port: 8100, targetPort: 8100 },
];
resources.find(r => r.kind === 'NetworkPolicy').spec.ingress[0].ports.push({ protocol: 'TCP', port: 8100 });
collaborationUpstreamUrl = `http://${name}.${config.namespace}.svc:8100`;
}
return { name, resources, upstreamUrl: `http://${name}.${config.namespace}.svc:3000`, collaborationUpstreamUrl };
}
async function observe(config, name) {
return new Promise((resolve, reject) => {
const child = spawn(
'kubectl',
['--context', config.context, '--namespace', config.namespace, 'get', 'deployment', name, '-o', 'json'],
{ stdio: ['ignore', 'pipe', 'pipe'] },
);
let stdout = '';
const timer = setTimeout(() => {
child.kill('SIGTERM');
reject(new Error('KUBERNETES_OBSERVE_TIMEOUT'));
}, 10000);
child.stderr.resume();
child.stdout.on('data', b => {
stdout += b;
if (stdout.length > 1000000) child.kill('SIGTERM');
});
child.on('error', () => {
clearTimeout(timer);
reject(new Error('KUBERNETES_OBSERVE_FAILED'));
});
child.on('close', code => {
clearTimeout(timer);
try {
if (code !== 0) throw new Error();
const d = JSON.parse(stdout);
resolve(
d.status?.observedGeneration >= d.metadata.generation &&
d.status?.availableReplicas === 1 &&
d.status?.updatedReplicas === 1,
);
} catch {
reject(new Error('KUBERNETES_OBSERVE_FAILED'));
}
});
});
}
export async function provisionWorkspace(config, input, options = {}) {
const collaboration =
options.collaboration ??
(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,
);
await (options.apply ?? runKubectl)(config, rendered.resources);
const ready = await (options.observe ?? observe)(config, rendered.name);
return {
status: ready ? 'ready' : 'pending',
workspaceId: input.workspaceId,
upstreamUrl: rendered.upstreamUrl,
collaborationUpstreamUrl: rendered.collaborationUpstreamUrl,
};
}