🔥 Remove the cloud IDE

The cluster never ran Theia or the IDE gateway, so every workspace stayed
"未配置" forever. The feature is gone instead of half-present:

- API: workspace, launch and lifecycle endpoints, the gateway identity and
  its internal routes, the dispatcher's workspace provisioning and the
  lifecycle worker. Migration 003 deletes stored workspaces and settles
  their pending outbox items.
- Provisioner: workspace provisioning and lifecycle for both backends.
- Web: the 云 IDE panel, the launch route, the start-branch picker that
  listed IDE branches, and the workspace count on usage.
- apps/ide, infra/oct, dev:ide and the CI job; IDE parts of local k3s,
  network policies, RBAC, docs and the architecture diagram.

A wish can still start from a pushed branch through the API (sourceBranch).
Plan files and stored entitlements may still carry maxWorkspaces; it is
accepted and ignored.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
eust-w 2026-11-04 12:43:02 +08:00
parent ee340d6a8b
commit da1cfcea13
128 changed files with 315 additions and 21764 deletions

View File

@ -13,6 +13,4 @@
**/*.tsbuildinfo
**/test-results
**/coverage
apps/ide
infra/oct
**/.DS_Store

View File

@ -62,18 +62,3 @@ jobs:
# A second run must find nothing to apply (requirements FR-K2).
- run: npm run db:migrate | tee migrate.log && grep -q 'up to date' migrate.log
- run: npm run test:integration
ide:
name: IDE gateway, collaboration and policy tests
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: apps/ide/package-lock.json
# The Theia application itself is not built here; these tests need only its dependencies.
- run: npm ci --prefix apps/ide --ignore-scripts
- run: npm run test:ide

1
.gitignore vendored
View File

@ -1,7 +1,6 @@
node_modules/
.next/
dist/
/apps/ide/lib/
coverage/
.env
.env.local

View File

@ -3,11 +3,6 @@ node_modules/
.next/
dist/
coverage/
apps/ide/lib/
apps/ide/plugins/
apps/ide/src-gen/
apps/ide/gen-esbuild.*.mjs
apps/ide/esbuild.mjs
# Generated or pinned files
package-lock.json

View File

@ -1,6 +1,6 @@
# WishForge
远程、意图驱动的软件交付平台:用一句话提出愿望(目标 + 验收标准),后端编码 Agent 在隔离环境中实现,独立验证器按受保护的命令判定,失败时把失败信息交还 Agent 自修复,通过后合入代码并按需构建、审批与部署。可以从 Web 工作台、WorkBuddy/Codex(MCP)或云 IDE 发起与跟进。
远程、意图驱动的软件交付平台:用一句话提出愿望(目标 + 验收标准),后端编码 Agent 在隔离环境中实现,独立验证器按受保护的命令判定,失败时把失败信息交还 Agent 自修复,通过后合入代码并按需构建、审批与部署。可以从 Web 工作台或 WorkBuddy/Codex(MCP)发起与跟进。
- 使用手册(使用者与本机服务维护者):[docs/user-manual.md](docs/user-manual.md)
- 综合指引(使用、架构与高频 QA):[docs/wishforge-summary.md](docs/wishforge-summary.md)
@ -67,10 +67,9 @@ npm run dev:all
| `apps/api` | 控制面 API(REST `/v1`、内部接口 `/internal`、MCP `/mcp`、模型代理) |
| `apps/web` | Web 工作台(Next.js,含 OIDC BFF) |
| `apps/worker` | Temporal worker:coordinator / executor / verifier / deployer |
| `apps/provisioner` | 执行环境与 IDE 工作区的创建(`local` 与 `kubernetes` 后端) |
| `apps/provisioner` | 执行环境的创建(`local` 与 `kubernetes` 后端) |
| `apps/git-service` | 平台 Git 服务 |
| `apps/runner` | 目标环境侧的部署 Runner |
| `apps/ide` | Theia 云 IDE、IDE 网关与协作 |
| `packages/contracts` | 领域类型、输入校验、规范化 JSON |
| `packages/agent` | Agent 配置与提示词组装 |
| `packages/runtime` | 执行器适配、Git、验证、构建与部署适配 |
@ -92,4 +91,4 @@ npm run typecheck
npm test
```
需要外部服务的集成测试默认跳过,开启方式见 [docs/development.md](docs/development.md#7-测试与检查)。
需要外部服务的集成测试默认跳过,开启方式见 [docs/development.md](docs/development.md#6-测试与检查)。

View File

@ -1,4 +1,3 @@
import { resolveGatewayTarget } from './domain/gateway-target.js';
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose';
import { DomainError, type Actor, isProduction, type Run, type RunnerRegistration } from '@wishforge/contracts';
import { currentGeneration, sameSecret } from './domain/policy.js';
@ -102,13 +101,6 @@ export class Authenticator {
throw new DomainError('UNAUTHENTICATED', 'Access token is invalid or expired', 401);
}
}
/**
* The person behind an established IDE session, with their current membership, so the
* gateway keeps checking access (and sees revocation) after their access token expired.
*/
async sessionUser(tenantId: string, userId: string): Promise<Actor> {
return this.member(tenantId, userId, 'human');
}
private async member(tenantId: string, userId: string, kind: Actor['kind'], clientId?: string): Promise<Actor> {
const role = await this.store.read(tenantId, tx => tx.membership(userId));
if (!role) throw new DomainError('FORBIDDEN', 'Tenant membership is missing or revoked', 403);
@ -131,9 +123,6 @@ export class Authenticator {
return scoped;
throw new DomainError('UNAUTHENTICATED', 'Execution credential was revoked or superseded', 401);
}
const gateway = await resolveGatewayTarget(this.env, tenant);
if (gateway && sameSecret(token, gateway.token))
return { tenantId: tenant, userId: 'workspace-gateway', role: 'admin', kind: 'worker' };
// Verifiers only ever use run-scoped tokens; there is no static verifier identity.
for (const [name, kind] of [
['WF_WORKER_TOKEN', 'worker'],

View File

@ -0,0 +1,7 @@
-- Data changes below must see every tenant: fail instead of silently skipping rows under RLS.
SET LOCAL row_security = off;
-- The cloud IDE was removed: its workspaces and their pending provisioning work go with it.
UPDATE outbox SET delivered_at = now()
WHERE type IN ('workspace.provision', 'workspace.reconcile') AND delivered_at IS NULL;
DELETE FROM entities WHERE kind = 'workspace';

View File

@ -59,8 +59,8 @@ export interface ListFilter {
/** Only entities created before this time: the cursor for the next page. */
before?: string;
}
/** Outbox items are processed in this order: control signals first, then reconciliation, then new work. */
export const OUTBOX_PRIORITY = ['run.signal', 'workspace.reconcile'];
/** Outbox items are processed in this order: control signals first, then new work. */
export const OUTBOX_PRIORITY = ['run.signal'];
export interface Transaction {
tenant(): Promise<Tenant>;
membership(userId: string): Promise<Role | undefined>;
@ -261,7 +261,7 @@ class PgTransaction implements Transaction {
}
async outbox(): Promise<OutboxItem[]> {
const r = await this.c.query(
"SELECT id,type,payload,attempts FROM outbox WHERE tenant_id=$1 AND delivered_at IS NULL AND next_attempt_at<=now() AND type IN ('run.start','run.signal','workspace.provision','workspace.reconcile') ORDER BY CASE WHEN type='run.signal' THEN 0 WHEN type='workspace.reconcile' THEN 1 ELSE 2 END,created_at LIMIT 50",
"SELECT id,type,payload,attempts FROM outbox WHERE tenant_id=$1 AND delivered_at IS NULL AND next_attempt_at<=now() AND type IN ('run.start','run.signal') ORDER BY CASE WHEN type='run.signal' THEN 0 ELSE 1 END,created_at LIMIT 50",
[this.tenantId],
);
return r.rows;

View File

@ -1,4 +1,3 @@
import { resolveGatewayTarget } from './domain/gateway-target.js';
import { Client, Connection, WorkflowIdReusePolicy } from '@temporalio/client';
import type { ControlPlane } from './domain/control-plane.js';
import { ServiceTokens } from './service-tokens.js';
@ -10,9 +9,7 @@ import {
requireTenantNamespaces,
temporalNamespace,
temporalTlsFiles,
type Project,
type Run,
type Workspace,
} from '@wishforge/contracts';
import { reserveExecutionGrant, recordAllocation } from './domain/entitlements.js';
import { resolveProvisionerTarget, type ProvisionerTarget } from './domain/provisioner-target.js';
@ -60,95 +57,9 @@ export class Dispatcher {
}
// Claimed items are invisible to other API replicas until acknowledged, deferred or expired.
const pending = await this.control.store.transaction(tenant, tx =>
tx.claimOutbox(['run.signal', 'run.start', 'workspace.provision'], 300),
tx.claimOutbox(['run.signal', 'run.start'], 300),
);
for (const item of pending) {
if (item.type === 'workspace.provision') {
try {
if (provisionerError) throw provisionerError;
const gateway = await resolveGatewayTarget(this.control.env, tenant);
if (!gateway) {
await this.control.store.transaction(tenant, tx => tx.defer(item.id, 60));
continue;
}
const { currentWorkspace, project } = await this.control.store.transaction(tenant, async tx => {
const currentWorkspace = await must<Workspace>(tx, 'workspace', String(item.payload.workspaceId));
return { currentWorkspace, project: await tx.get<Project>('project', currentWorkspace.projectId) };
});
if (currentWorkspace.lifecycle) {
await this.control.store.transaction(tenant, tx => tx.acknowledge(item.id));
continue;
}
if (!provisioner) {
await this.control.store.transaction(tenant, tx => tx.defer(item.id, 60));
continue;
}
const response = await fetch(`${provisioner.url}/workspaces`, {
method: 'POST',
headers: { Authorization: `Bearer ${provisioner.token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
tenantId: tenant,
projectId: item.payload.projectId,
workspaceId: item.payload.workspaceId,
// The workspace then accepts credentials for this repository only.
...(project?.repositoryStorage === 'platform' && project.repositoryUrl
? { repositoryUrl: project.repositoryUrl }
: {}),
}),
signal: AbortSignal.timeout(30000),
});
if (!response.ok) throw new Error('WorkspaceProvisioningFailed');
const state = (await response.json()) as {
status: 'ready' | 'pending';
upstreamUrl: string;
collaborationUpstreamUrl?: string;
/** The local backend shares one Theia and cannot pause or resume it. */
lifecycle?: 'unmanaged';
};
if (!['ready', 'pending'].includes(state.status)) throw new Error('InvalidWorkspaceReceipt');
await this.control.store.transaction(tenant, async tx => {
const w = await must<Workspace>(tx, 'workspace', String(item.payload.workspaceId));
if (w.lifecycle) {
await tx.acknowledge(item.id);
return;
}
w.managedBy = state.lifecycle === 'unmanaged' ? 'local-provisioner' : 'wishforge-provisioner';
if (state.status === 'ready') w.lastActivityAt = new Date().toISOString();
w.status = state.status === 'ready' ? 'ready' : 'requested';
w.reason =
state.status === 'ready' ? undefined : 'Waiting for the isolated Theia instance to become ready.';
if (state.status === 'ready') {
const target = new URL(state.upstreamUrl);
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password)
throw new Error('InvalidWorkspaceTarget');
w.upstreamUrl = target.toString();
if (state.collaborationUpstreamUrl) {
const collaboration = new URL(state.collaborationUpstreamUrl);
if (
collaboration.hostname !== target.hostname ||
collaboration.port !== '8100' ||
collaboration.username ||
collaboration.password ||
collaboration.pathname !== '/' ||
collaboration.search ||
collaboration.hash
)
throw new Error('InvalidCollaborationTarget');
w.collaborationUpstreamUrl = collaboration.toString();
}
w.url = `${gateway.publicUrl}/workspaces/${w.id}/`;
await tx.acknowledge(item.id);
}
await tx.put('workspace', touch(w));
});
if (state.status === 'pending')
await this.control.store.transaction(tenant, tx => tx.defer(item.id, 15));
} catch (error) {
await this.control.store.transaction(tenant, tx => tx.defer(item.id, 60));
console.error(`Workspace provisioning pending: ${error instanceof Error ? error.name : 'failure'}`);
}
continue;
}
if (item.type !== 'run.start' && item.type !== 'run.signal') continue;
const workflowId = `wishforge:${tenant}:${String(item.payload.runId)}`;
try {

View File

@ -10,12 +10,11 @@ import {
/**
* Validate an environment's application URL. Deployed applications are untrusted
* code, so they may never share an origin with the console, API or IDE gateways.
* code, so they may never share an origin with the console or API.
*/
export function applicationUrlFor(
environment: Pick<Environment, 'applicationUrl' | 'production'> & { projectId?: string },
env: NodeJS.ProcessEnv,
additionalOrigins: string[] = [],
): string | undefined {
if (!environment.applicationUrl) return undefined;
let applicationUrl: string;
@ -39,13 +38,7 @@ export function applicationUrlFor(
);
}
const origin = new URL(applicationUrl).origin;
for (const configured of [
env.WF_PUBLIC_URL,
env.WF_API_PUBLIC_URL,
env.WF_IDE_PUBLIC_URL,
env.WF_WORKSPACE_GATEWAY_BASE,
...additionalOrigins,
]) {
for (const configured of [env.WF_PUBLIC_URL, env.WF_API_PUBLIC_URL]) {
if (!configured) continue;
let protectedOrigin: string;
try {
@ -60,7 +53,7 @@ export function applicationUrlFor(
if (origin === protectedOrigin)
throw new DomainError(
'APPLICATION_ORIGIN_CONFLICT',
'Applications must use an origin separate from the console, API and IDE authentication origins',
'Applications must use an origin separate from the console and API authentication origins',
400,
);
}

View File

@ -387,11 +387,7 @@ export class ControlPlane {
data.sourceBranch &&
(data.sourceBranch === project.targetBranch || data.sourceBranch.startsWith('wishforge/'))
)
throw new DomainError(
'INVALID_SOURCE_BRANCH',
'Start from another branch than the target branch, for example one pushed from the IDE',
400,
);
throw new DomainError('INVALID_SOURCE_BRANCH', 'Start from another branch than the target branch', 400);
// A wish runs with one of its project's models, flash when offered unless chosen; a project
// without models leaves the choice to the agent configuration and the executor.
const models = project.models ?? [];

View File

@ -21,7 +21,8 @@ export const planLimitsSchema = z
.object({
maxMembers: positive.max(10000),
maxProjects: positive.max(10000),
maxWorkspaces: positive.max(10000),
/** The retired cloud IDE's allowance: still accepted in stored snapshots and plan files, ignored. */
maxWorkspaces: positive.max(10000).optional(),
maxConcurrentRuns: positive.max(1000),
monthlyModelTokens: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
execution: z
@ -58,7 +59,6 @@ export const PILOT_PLAN: CommercialPlan = {
limits: {
maxMembers: 10,
maxProjects: 10,
maxWorkspaces: 5,
maxConcurrentRuns: 2,
monthlyModelTokens: 2_000_000,
execution: { cpuMilli: 2000, memoryMiB: 4096, storageMiB: 10240 },
@ -105,7 +105,6 @@ export function effectiveEntitlements(tenant: Tenant): {
limits: {
...structuredClone(PILOT_PLAN.limits),
maxProjects: 20,
maxWorkspaces: 10,
maxConcurrentRuns: tenant.maxConcurrentRuns,
monthlyModelTokens: tenant.tokenLimit,
},
@ -128,11 +127,11 @@ export function requirePlatformOperator(actor: Actor, env = process.env) {
403,
);
}
export async function requireCapacity(tx: Transaction, kind: 'project' | 'workspace') {
export async function requireCapacity(tx: Transaction, kind: 'project') {
const limits = effectiveEntitlements(await tx.tenant()).limits;
// Projects and workspaces cannot be deleted yet (project archiving is planned), so every one counts.
// Projects cannot be deleted yet (project archiving is planned), so every one counts.
const count = (await tx.list(kind)).length;
if (count >= (kind === 'project' ? limits.maxProjects : limits.maxWorkspaces))
if (count >= limits.maxProjects)
throw new DomainError('ENTITLEMENT_LIMIT', `Tenant ${kind} allowance is exhausted`, 429);
}
export function heldAllocation(run: Run): boolean {
@ -307,7 +306,6 @@ export class Entitlements {
counts: {
members: (await tx.members()).filter(member => member.active).length,
projects: (await tx.list('project')).length,
workspaces: (await tx.list('workspace')).length,
reservedExecutionSlots: (await tx.list<Run>('run')).filter(occupiesExecutionSlot).length,
},
};

View File

@ -1,137 +0,0 @@
import { readFile } from 'node:fs/promises';
import { z } from 'zod';
import { DomainError, plainHttpAllowed } from '@wishforge/contracts';
import { dispatchTenants } from '../tenants.js';
const entry = z
.object({
internalUrl: z.string().max(2048),
publicUrl: z.string().max(2048),
tokenEnv: z.string().regex(/^WF_[A-Z0-9_]{1,100}_TOKEN$/),
})
.strict();
const schema = z
.object({ schemaVersion: z.literal(1), tenants: z.record(z.string().regex(/^[A-Za-z0-9_-]{1,128}$/), entry) })
.strict();
export interface GatewayTarget {
internalUrl: string;
publicUrl: string;
token: string;
}
function origin(raw: string, env: NodeJS.ProcessEnv) {
let value: URL;
try {
value = new URL(raw);
} catch {
throw new DomainError('GATEWAY_CONFIGURATION_INVALID', 'Gateway URL is invalid', 503);
}
if (
value.username ||
value.password ||
value.pathname !== '/' ||
value.search ||
value.hash ||
!(value.protocol === 'https:' || plainHttpAllowed(env, value))
)
throw new DomainError(
'GATEWAY_CONFIGURATION_INVALID',
'Gateway requires an HTTPS origin (development loopback excepted)',
503,
);
return value.origin;
}
async function mapping(file: string) {
try {
const bytes = await readFile(file);
if (bytes.length > 65536) throw Error();
return schema.parse(JSON.parse(bytes.toString('utf8')));
} catch {
throw new DomainError('GATEWAY_CONFIGURATION_INVALID', 'Operator tenant gateway map is unreadable or invalid', 503);
}
}
export async function resolveGatewayTarget(
env: NodeJS.ProcessEnv,
tenantId: string,
): Promise<GatewayTarget | undefined> {
if (!/^[A-Za-z0-9_-]{1,128}$/.test(tenantId))
throw new DomainError('GATEWAY_CONFIGURATION_INVALID', 'Invalid gateway tenant scope', 503);
let config: { internalUrl: string; publicUrl: string; tokenEnv: string } | undefined;
if (env.WF_WORKSPACE_GATEWAY_TARGETS_FILE) {
const map = await mapping(env.WF_WORKSPACE_GATEWAY_TARGETS_FILE);
config = Object.prototype.hasOwnProperty.call(map.tenants, tenantId) ? map.tenants[tenantId] : undefined;
if (!config) return;
for (const [otherId, other] of Object.entries(map.tenants)) {
if (otherId === tenantId) continue;
if (
origin(other.publicUrl, env) === origin(config.publicUrl, env) ||
(env[config.tokenEnv] && env[config.tokenEnv] === env[other.tokenEnv])
)
throw new DomainError(
'GATEWAY_CONFIGURATION_INVALID',
'Tenant gateways require distinct public origins and service credentials',
503,
);
}
} else {
if (!env.WF_WORKSPACE_GATEWAY_BASE && !env.WF_WORKSPACE_GATEWAY_TOKEN) return;
const tenants = dispatchTenants(env);
const bound = env.WF_WORKSPACE_GATEWAY_TENANT_ID ?? (tenants.length === 1 ? tenants[0] : undefined);
if (!bound)
throw new DomainError(
'GATEWAY_TENANT_BINDING_REQUIRED',
'A legacy gateway must be explicitly bound to one tenant; configure a tenant gateway map for multiple tenants',
503,
);
if (bound !== tenantId) return;
config = {
internalUrl: env.WF_WORKSPACE_GATEWAY_BASE ?? '',
publicUrl: env.WF_IDE_PUBLIC_URL ?? env.WF_WORKSPACE_GATEWAY_BASE ?? '',
tokenEnv: 'WF_WORKSPACE_GATEWAY_TOKEN',
};
}
const token = env[config.tokenEnv];
if (!token || token.length < 32)
throw new DomainError('GATEWAY_CONFIGURATION_INVALID', 'Gateway requires a tenant-scoped service token', 503);
return { internalUrl: origin(config.internalUrl, env), publicUrl: origin(config.publicUrl, env), token };
}
/** All known platform gateway origins are protected from untrusted application hosting. */
export async function gatewayIdentityOrigins(env: NodeJS.ProcessEnv): Promise<string[]> {
if (env.WF_WORKSPACE_GATEWAY_TARGETS_FILE) {
const map = await mapping(env.WF_WORKSPACE_GATEWAY_TARGETS_FILE);
return [
...new Set(
Object.values(map.tenants).flatMap(item => [origin(item.internalUrl, env), origin(item.publicUrl, env)]),
),
];
}
return [env.WF_WORKSPACE_GATEWAY_BASE, env.WF_IDE_PUBLIC_URL]
.filter((value): value is string => !!value)
.map(value => origin(value, env));
}
export function validateGatewayLaunch(target: GatewayTarget, payload: unknown) {
const value = payload as { launchUrl?: unknown; expiresIn?: unknown };
let url: URL;
try {
if (typeof value?.launchUrl !== 'string') throw Error();
url = new URL(value.launchUrl);
} catch {
throw new DomainError('INVALID_GATEWAY_LAUNCH', 'Gateway did not return a valid one-time launch URL', 502);
}
const keys = [...url.searchParams.keys()];
if (
url.origin !== target.publicUrl ||
url.pathname !== '/session' ||
url.username ||
url.password ||
url.hash ||
keys.length !== 1 ||
keys[0] !== 'code' ||
!/^[A-Za-z0-9_-]{40,128}$/.test(url.searchParams.get('code') ?? '') ||
value.expiresIn !== 30
)
throw new DomainError(
'INVALID_GATEWAY_LAUNCH',
'One-time launch URL does not match the assigned tenant gateway',
502,
);
return { launchUrl: url.toString(), expiresIn: 30 };
}

View File

@ -1,8 +1,5 @@
import { DomainError, type Actor, type Project, type Run, plainHttpAllowed } from '@wishforge/contracts';
/** IDE workspaces push here; a wish starting from such a branch verifies and merges it. */
export const IDE_BRANCH_PREFIX = 'ide/';
/** Only the trusted control plane can provision repositories or mint repository-scoped access. */
export class GitStorage {
constructor(
@ -44,35 +41,6 @@ export class GitStorage {
defaultBranch: project.targetBranch,
});
}
/**
* Write access for people editing in the project's IDE workspace. The Git service lets it
* update `ide/` branches only: the target branch changes through verified wishes alone.
*/
workspaceCredential(project: Project) {
if (project.repositoryStorage !== 'platform' || !project.repositoryUrl)
throw new DomainError(
'WORKSPACE_REPOSITORY_UNSUPPORTED',
'Only repositories hosted by the platform are cloned into IDE workspaces',
409,
);
return this.request<{ token: string; expiresAt: string }>('/tokens', {
tenantId: project.tenantId,
projectId: project.id,
permission: 'write',
ttlSeconds: 900,
refPrefix: `refs/heads/${IDE_BRANCH_PREFIX}`,
});
}
/** The branches people pushed from the IDE, most recent first. */
async ideBranches(project: Project) {
if (project.repositoryStorage !== 'platform' || !project.repositoryUrl || !this.configured()) return [];
const listed = await this.request<{ branches: { name: string; commit: string; updatedAt: string }[] }>('/refs', {
tenantId: project.tenantId,
projectId: project.id,
prefix: `refs/heads/${IDE_BRANCH_PREFIX}`,
});
return listed.branches;
}
async credential(actor: Actor, project: Project, run: Run) {
if (
project.repositoryStorage !== 'platform' ||

View File

@ -1,7 +1,6 @@
import { assertPocBuild } from './local-poc.js';
import { z } from 'zod';
import { requireDeploymentSecretPolicy } from './deployment-secret-policy.js';
import { gatewayIdentityOrigins } from './gateway-target.js';
import {
DomainError,
environmentInput,
@ -124,7 +123,7 @@ export class Releases {
const env = {
...record(actor.tenantId),
...data,
applicationUrl: applicationUrlFor(data, this.env, await gatewayIdentityOrigins(this.env)),
applicationUrl: applicationUrlFor(data, this.env),
} as Environment;
await tx.put('environment', env);
return env;
@ -144,7 +143,6 @@ export class Releases {
environment.applicationUrl = applicationUrlFor(
{ ...environment, applicationUrl: input.applicationUrl ?? undefined },
this.env,
await gatewayIdentityOrigins(this.env),
);
await tx.put('environment', touch(environment));
return environment;
@ -298,7 +296,7 @@ export class Releases {
if (env.projectId !== run.projectId)
throw new DomainError('ENVIRONMENT_MISMATCH', 'Environment belongs to another project');
requireDeploymentSecretPolicy(env);
applicationUrlFor(env, this.env, await gatewayIdentityOrigins(this.env));
applicationUrlFor(env, this.env);
assertApplicationConfigured(
{ applicationUrl: env.applicationUrl, deliveryRequired: isProduction(this.env) },
this.env,
@ -398,7 +396,7 @@ export class Releases {
assertVerificationProfile(project, this.env);
if (environment.applicationUrl !== release.applicationUrl)
throw new DomainError('RELEASE_STALE', 'Application URL changed; request a new release');
applicationUrlFor(environment, this.env, await gatewayIdentityOrigins(this.env));
applicationUrlFor(environment, this.env);
assertApplicationConfigured(release, this.env);
if (
digest(releaseBinding(release)) !== release.bindingDigest ||

View File

@ -1,45 +0,0 @@
import { DomainError, type Actor, type Workspace } from '@wishforge/contracts';
import type { Authenticator } from '../auth.js';
import type { Store } from '../db/store.js';
import { must, projectAccess } from './control-plane.js';
import { GitStorage } from './git-storage.js';
import { requireHuman, requireRole } from './policy.js';
/** Who commits from the IDE: the person's own name and email when their sign-in carries them. */
export function commitAuthor(actor: Actor) {
const local = actor.userId.replace(/[^A-Za-z0-9._-]+/g, '-').slice(0, 64) || 'user';
return { name: actor.displayName ?? actor.userId, email: actor.email ?? `${local}@users.wishforge.invalid` };
}
/**
* The IDE gateway asks for the repository credential of a workspace on behalf of a person
* with an open editing session; their membership and role are checked again every time.
*/
export class WorkspaceGit {
constructor(
private store: Store,
private auth: Authenticator,
private env = process.env,
private fetcher: typeof fetch = fetch,
) {}
async credential(tenantId: string, workspaceId: string, userId: string) {
const user = await this.auth.sessionUser(tenantId, userId);
requireHuman(user);
requireRole(user, ['owner', 'admin', 'developer']);
const { workspace, project } = await this.store.read(tenantId, async tx => {
const workspace = await must<Workspace>(tx, 'workspace', workspaceId);
return { workspace, project: await projectAccess(tx, user, workspace.projectId) };
});
if (workspace.status !== 'ready')
throw new DomainError('WORKSPACE_NOT_READY', 'Workspace has not been provisioned', 503);
const credential = await new GitStorage(this.env, this.fetcher).workspaceCredential(project);
return {
projectId: project.id,
projectName: project.name,
repositoryUrl: project.repositoryUrl!,
branch: project.targetBranch,
token: credential.token,
expiresAt: credential.expiresAt,
};
}
}

View File

@ -1,40 +0,0 @@
import { DomainError, type Actor, type Workspace } from '@wishforge/contracts';
import type { Store } from '../db/store.js';
import { must, projectAccess } from './control-plane.js';
import { requireHuman, requireRole } from './policy.js';
import { resolveGatewayTarget, validateGatewayLaunch } from './gateway-target.js';
export class WorkspaceLaunch {
constructor(
private store: Store,
private env = process.env,
private fetcher: typeof fetch = fetch,
) {}
async launch(actor: Actor, id: string, authorization: string) {
requireHuman(actor);
requireRole(actor, ['owner', 'admin', 'developer']);
await this.store.transaction(actor.tenantId, async tx => {
const workspace = await must<Workspace>(tx, 'workspace', id);
await projectAccess(tx, actor, String(workspace.projectId));
if (workspace.status !== 'ready' || !workspace.upstreamUrl)
throw new DomainError('WORKSPACE_NOT_READY', 'Workspace is not ready', 503);
});
const target = await resolveGatewayTarget(this.env, actor.tenantId);
if (!target) throw new DomainError('GATEWAY_UNCONFIGURED', 'No IDE gateway is configured for this tenant', 503);
const response = await this.fetcher(new URL('/launch', target.internalUrl), {
method: 'POST',
headers: { authorization, 'content-type': 'application/json' },
body: JSON.stringify({ workspaceId: id }),
redirect: 'error',
signal: AbortSignal.timeout(15000),
}).catch(() => {
throw new DomainError('GATEWAY_UNAVAILABLE', 'Tenant IDE gateway is unavailable', 503);
});
if (!response.ok)
throw new DomainError(
'IDE_LAUNCH_DENIED',
'Tenant gateway denied this interactive workspace session',
[401, 403, 404].includes(response.status) ? response.status : 503,
);
return validateGatewayLaunch(target, await response.json());
}
}

View File

@ -1,245 +0,0 @@
import { resolveGatewayTarget } from './gateway-target.js';
import { resolveProvisionerTarget } from './provisioner-target.js';
import { randomUUID } from 'node:crypto';
import {
DomainError,
type Actor,
type Workspace,
type WorkspaceLifecycleOperation as Lifecycle,
} from '@wishforge/contracts';
import type { OutboxItem, Store, Transaction } from '../db/store.js';
import { idempotent, must, projectAccess, touch } from './control-plane.js';
import { requireHuman, requireRole } from './policy.js';
export const WORKSPACE_IDLE_MS = 30 * 60_000;
interface GatewayActivity {
workspaceId: string;
known: boolean;
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,
private env = process.env,
private fetcher: typeof fetch = fetch,
) {}
private async access(tx: Transaction, actor: Actor, id: string) {
requireHuman(actor);
requireRole(actor, ['owner', 'admin', 'developer']);
const currentRole = await tx.membership(actor.userId);
if (!currentRole || !['owner', 'admin', 'developer'].includes(currentRole))
throw new DomainError('FORBIDDEN', 'Workspace permission was revoked', 403);
const workspace = await must<Workspace>(tx, 'workspace', id);
await projectAccess(tx, { ...actor, role: currentRole }, String(workspace.projectId));
return workspace;
}
private safe(w: Workspace) {
return { id: w.id, status: w.status, lifecycle: w.lifecycle, reason: w.reason, lastActivityAt: w.lastActivityAt };
}
private async provisioner(tenantId: string) {
const provisioner = await resolveProvisionerTarget(this.env, tenantId);
if (!provisioner)
throw new DomainError(
'WORKSPACE_LIFECYCLE_UNCONFIGURED',
'A scoped workspace provisioner is required for this tenant',
503,
);
return provisioner;
}
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 };
return this.store.transaction(actor.tenantId, async tx => {
const workspace = await this.access(tx, actor, id);
return idempotent(tx, key, request, async () => {
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: Workspace, desired: Lifecycle['desired'], automatic: boolean) {
const revision = (workspace.lifecycle?.revision ?? 0) + 1;
const operationId = randomUUID();
workspace.lifecycle = {
revision,
desired,
automatic,
requestedAt: new Date().toISOString(),
operationId,
state: 'queued',
} satisfies Lifecycle;
workspace.status = desired === 'paused' ? 'pausing' : 'resuming';
workspace.reason = 'Waiting for the workspace controller to confirm the requested state.';
await tx.put('workspace', touch(workspace));
await tx.enqueue(
'workspace.reconcile',
{ workspaceId: workspace.id, projectId: workspace.projectId, revision, desired },
operationId,
);
return this.safe(workspace);
}
/** Idle only when the gateway positively reports no open connection to the workspace. */
private async idle(workspace: Workspace): Promise<boolean> {
const gateway = await resolveGatewayTarget(this.env, workspace.tenantId);
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),
}).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;
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>('workspace')).filter(
w =>
w.managedBy === 'wishforge-provisioner' &&
w.status === 'ready' &&
typeof w.lastActivityAt === 'string' &&
Date.parse(w.lastActivityAt) <= cutoff,
),
);
for (const before of candidates) {
if (!(await this.idle(before))) continue;
await this.store.transaction(tenantId, async tx => {
const w = await must<Workspace>(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<Workspace>(tx, 'workspace', String(item.payload.workspaceId)),
);
const operation = workspace.lifecycle;
if (!operation || operation.operationId !== item.id || operation.revision !== item.payload.revision) {
await this.store.transaction(tenantId, tx => tx.acknowledge(item.id));
return;
}
try {
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;
}
const target = new URL(`${provisioner.url}/workspaces/${workspace.id}/lifecycle`);
target.searchParams.set('tenantId', tenantId);
target.searchParams.set('projectId', String(workspace.projectId));
const headers = { authorization: `Bearer ${provisioner.token}`, 'content-type': 'application/json' };
// Always observe first. A lost response never causes an unconditional mutation replay.
const observed = await this.fetcher(target, { headers, redirect: 'error', signal: AbortSignal.timeout(15000) });
if (!observed.ok) throw new Error('WORKSPACE_OBSERVE_UNKNOWN');
let state = (await observed.json()) as {
workspaceId: string;
revision: number;
desired: string;
status: Workspace['status'];
};
const valid = () =>
state.workspaceId === workspace.id &&
Number.isSafeInteger(state.revision) &&
state.revision >= 0 &&
['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 && !(await this.idle(workspace))) {
await this.store.transaction(tenantId, async tx => {
const current = await must<Workspace>(tx, 'workspace', workspace.id);
if (current.lifecycle?.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 => {
const current = await must<Workspace>(tx, 'workspace', workspace.id);
if (current.lifecycle?.operationId !== item.id) throw new Error('WORKSPACE_SUPERSEDED');
if (operation.automatic && current.lastActivityAt !== workspace.lastActivityAt)
throw new Error('WORKSPACE_ACTIVITY_CHANGED');
current.lifecycle = { ...operation, state: 'unknown' };
await tx.put('workspace', touch(current));
});
target.search = '';
const changed = await this.fetcher(target, {
method: 'PUT',
headers,
body: JSON.stringify({
tenantId,
projectId: workspace.projectId,
workspaceId: workspace.id,
revision: operation.revision,
desired: operation.desired,
}),
redirect: 'error',
signal: AbortSignal.timeout(15000),
});
if (!changed.ok) throw new Error('WORKSPACE_RECONCILE_UNKNOWN');
state = (await changed.json()) as typeof state;
}
if (!valid() || state.revision !== operation.revision || state.desired !== operation.desired)
throw new Error('WORKSPACE_OBSERVE_UNKNOWN');
await this.store.transaction(tenantId, async tx => {
const current = await must<Workspace>(tx, 'workspace', workspace.id);
if (current.lifecycle?.operationId !== item.id) return;
const complete =
(operation.desired === 'paused' && state.status === 'paused') ||
(operation.desired === 'running' && state.status === 'ready');
current.lifecycle = { ...operation, state: complete ? 'complete' : 'observing' };
current.status = complete ? state.status : operation.desired === 'paused' ? 'pausing' : 'resuming';
current.reason = complete ? undefined : 'Waiting for observed workspace replicas and readiness.';
if (complete && state.status === 'ready') current.lastActivityAt = new Date().toISOString();
await tx.put('workspace', touch(current));
if (complete) await tx.acknowledge(item.id);
else await tx.defer(item.id, 10);
});
} 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<Workspace>(tx, 'workspace', workspace.id);
if (current.lifecycle?.operationId !== item.id) return;
current.status = 'unknown';
current.reason = 'Workspace controller outcome is unknown; observation will be retried before any new action.';
current.lifecycle = { ...operation, state: 'unknown' };
await tx.put('workspace', touch(current));
await tx.defer(item.id, 30);
});
}
}
}

View File

@ -29,10 +29,9 @@ import {
type Actor,
type Run,
isProduction,
type Workspace,
} from '@wishforge/contracts';
import { Authenticator, localUser } from './auth.js';
import { ControlPlane, must, projectAccess, record, touch } from './domain/control-plane.js';
import { ControlPlane, must, projectAccess, touch } from './domain/control-plane.js';
import { Releases } from './domain/releases.js';
import { AgentBundles } from './domain/agent-bundles.js';
import { Lessons } from './domain/lessons.js';
@ -41,11 +40,10 @@ import { WishReports } from './domain/wish-report.js';
import { Connections } from './domain/connections.js';
import { RunnerBroker } from './domain/runner-broker.js';
import { GitStorage } from './domain/git-storage.js';
import { WorkspaceGit, commitAuthor } from './domain/workspace-git.js';
import { GitHubIntegration } from './domain/github.js';
import { Usage } from './domain/usage.js';
import { ProviderProxy } from './domain/provider-proxy.js';
import { Entitlements, requireCapacity } from './domain/entitlements.js';
import { Entitlements } from './domain/entitlements.js';
import { requireRole, requireHuman } from './domain/policy.js';
import { configuredVerificationProfiles, selectVerificationProfile } from './domain/verification-policy.js';
import { LocalAccounts, localAccountsEnabled } from './domain/local-accounts.js';
@ -153,17 +151,6 @@ const meterBody = z
computeSeconds: z.number().min(0),
})
.strict();
/** The first check of an IDE session carries the user's token; later checks name the established user. */
const authorizeBody = z
.object({
userToken: z.string().min(1).max(16384).optional(),
userId: z.string().min(1).max(200).optional(),
operation: z.enum(['edit', 'terminal', 'debug']),
})
.strict()
.refine(body => Boolean(body.userToken) !== Boolean(body.userId), 'Provide either userToken or userId');
const gatewayUserBody = z.object({ userId: z.string().min(1).max(200) }).strict();
@Catch()
export class Errors implements ExceptionFilter {
catch(error: unknown, host: ArgumentsHost) {
@ -684,44 +671,6 @@ export class ApiController {
res.type('text/csv').setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`);
res.send(exported.content);
}
@Get('projects/:id/branches') async branches(@Req() r: AuthRequest, @Param('id') id: string) {
const project = await this.s.control.store.read(r.actor.tenantId, tx => projectAccess(tx, r.actor, id));
return ok(await new GitStorage(this.s.control.env).ideBranches(project));
}
@Get('projects/:id/workspaces') async workspaces(@Req() r: AuthRequest, @Param('id') id: string) {
return ok(
await this.s.control.store.read(r.actor.tenantId, async tx => {
await projectAccess(tx, r.actor, id);
return (await tx.list<Workspace>('workspace', { projectId: id })).map(publicWorkspace);
}),
);
}
@Post('projects/:id/workspaces') async workspace(@Req() r: AuthRequest, @Param('id') id: string) {
requireRole(r.actor, ['owner', 'admin', 'developer']);
return ok(
await this.s.control.store.transaction(r.actor.tenantId, async tx => {
await projectAccess(tx, r.actor, id);
const existing = (await tx.list<Workspace>('workspace', { projectId: id }))[0];
if (existing) return publicWorkspace(existing);
await requireCapacity(tx, 'workspace');
const workspace = {
...record(r.actor.tenantId),
projectId: id,
status: 'unconfigured',
reason:
'An isolated Theia workspace provisioner and authenticated gateway must be connected before this workspace can be opened.',
};
await tx.put('workspace', workspace);
await tx.enqueue('workspace.provision', { workspaceId: workspace.id, projectId: id });
return workspace;
}),
);
}
}
/** A workspace as people see it: its internal upstream addresses are only for the gateway. */
function publicWorkspace({ upstreamUrl: _, collaborationUpstreamUrl: _collaboration, ...workspace }: Workspace) {
return workspace;
}
@Controller('internal')
@ -871,63 +820,4 @@ export class InternalController {
if (r.actor.kind !== 'deployer') throw new DomainError('FORBIDDEN', 'Deployer required', 403);
return ok(await this.s.releases.request(r.actor, b, key(r)));
}
@Post('workspaces/:id/authorize') async authorizeWorkspace(
@Req() r: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
const b = authorizeBody.parse(body);
if (r.actor.userId !== 'workspace-gateway')
throw new DomainError('FORBIDDEN', 'Workspace gateway identity required', 403);
const user = b.userToken
? await this.s.auth.authenticate(`Bearer ${b.userToken}`)
: await this.s.auth.sessionUser(r.actor.tenantId, b.userId!);
if (user.tenantId !== r.actor.tenantId) throw new DomainError('NOT_FOUND', 'Workspace not found', 404);
return ok(
await this.s.control.store.transaction(user.tenantId, async tx => {
const workspace = await must<Workspace>(tx, 'workspace', id);
await projectAccess(tx, user, String(workspace.projectId));
if (['edit', 'terminal', 'debug'].includes(b.operation)) {
requireHuman(user);
requireRole(user, ['owner', 'admin', 'developer']);
}
if (workspace.status !== 'ready' || !workspace.upstreamUrl)
throw new DomainError('WORKSPACE_NOT_READY', 'Workspace has not been provisioned', 503);
if (
r.actor.userId === 'workspace-gateway' &&
(!workspace.lastActivityAt || Date.now() - Date.parse(String(workspace.lastActivityAt)) >= 15000)
) {
workspace.lastActivityAt = new Date().toISOString();
await tx.put('workspace', workspace);
}
return {
tenantId: user.tenantId,
projectId: workspace.projectId,
workspaceId: id,
upstreamUrl: workspace.upstreamUrl,
collaborationUpstreamUrl: workspace.collaborationUpstreamUrl,
userId: user.userId,
role: user.role,
// Known only from a sign-in token: the gateway keeps it for the session's commits.
...(b.userToken ? { author: commitAuthor(user) } : {}),
};
}),
);
}
@Post('workspaces/:id/git-credential') async workspaceGitCredential(
@Req() r: AuthRequest,
@Param('id') id: string,
@Body() body: unknown,
) {
if (r.actor.userId !== 'workspace-gateway')
throw new DomainError('FORBIDDEN', 'Workspace gateway identity required', 403);
const { userId } = gatewayUserBody.parse(body);
return ok(
await new WorkspaceGit(this.s.control.store, this.s.auth, this.s.control.env).credential(
r.actor.tenantId,
id,
userId,
),
);
}
}

View File

@ -14,8 +14,7 @@ const STATIC_ROUTES: Partial<Record<Actor['kind'], RegExp[]>> = {
/**
* Resolves the identity behind an `/internal` request and confines it: run-scoped
* execution tokens address only their own run, static service identities only their
* routes, the IDE gateway only workspace authorization and Git credentials, and environment runners only
* their deployment tasks.
* routes, and environment runners only their deployment tasks.
*/
export async function internalActor(
auth: Authenticator,
@ -28,10 +27,7 @@ export async function internalActor(
(request.path === '/evidence' ? (request.body as { runId?: unknown } | undefined)?.runId : undefined);
if (addressed !== actor.runId) throw new DomainError('FORBIDDEN', 'Execution token is scoped to a single run', 403);
}
if (actor.userId === 'workspace-gateway') {
if (!/^\/workspaces\/[^/]+\/(authorize|git-credential)$/.test(request.path))
throw new DomainError('FORBIDDEN', 'Gateway identity is limited to workspace authorization', 403);
} else if (actor.userId.startsWith('runner:')) {
if (actor.userId.startsWith('runner:')) {
if (!request.path.startsWith('/runner/'))
throw new DomainError('FORBIDDEN', 'Runner identity is limited to assigned deployment tasks', 403);
} else if (!actor.runId && !(STATIC_ROUTES[actor.kind] ?? []).some(route => route.test(request.path)))

View File

@ -1,4 +1,3 @@
import { WorkspaceLaunchController } from './workspace-launch-http.js';
import 'reflect-metadata';
import { Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
@ -17,8 +16,6 @@ import { localUser } from './auth.js';
import { observability } from './telemetry.js';
import { ProviderProxy } from './domain/provider-proxy.js';
import { once } from 'node:events';
import { WorkspaceLifecycleController } from './workspace-lifecycle-http.js';
import { WorkspaceLifecycleWorker } from './workspace-lifecycle-worker.js';
import { ResourceReconciliationWorker } from './resource-reconciliation-worker.js';
export async function bootstrap() {
@ -39,7 +36,7 @@ export async function bootstrap() {
service.skills.startHarvesting();
const telemetry = await observability();
@Module({
controllers: [ApiController, InternalController, WorkspaceLifecycleController, WorkspaceLaunchController],
controllers: [ApiController, InternalController],
providers: [{ provide: Services, useValue: service }],
})
class AppModule {}
@ -180,8 +177,6 @@ export async function bootstrap() {
});
raw.all('/mcp', (_req: express.Request, res: express.Response) => res.status(405).setHeader('Allow', 'POST').end());
await app.listen(Number(process.env.PORT ?? 4000), process.env.HOST ?? '127.0.0.1');
const workspaceLifecycle = new WorkspaceLifecycleWorker(service.control);
if (process.env.WF_DISPATCH_ENABLED !== 'false') workspaceLifecycle.start();
const dispatcher = new Dispatcher(service.control);
if (process.env.WF_DISPATCH_ENABLED !== 'false') void dispatcher.start();
const resourceReconciliation = new ResourceReconciliationWorker(service.control);
@ -192,7 +187,6 @@ export async function bootstrap() {
const shutdown = async () => {
notifier.close();
await resourceReconciliation.close();
await workspaceLifecycle.close();
await dispatcher.close();
await app.close();
await store.close();

View File

@ -1,24 +0,0 @@
import { Body, Controller, Inject, Param, Post, Req } from '@nestjs/common';
import type { Request } from 'express';
import { z } from 'zod';
import type { Actor } from '@wishforge/contracts';
import { Services } from './http.js';
import { WorkspaceLaunch } from './domain/workspace-launch.js';
@Controller('v1/workspaces')
export class WorkspaceLaunchController {
constructor(@Inject(Services) private s: Services) {}
@Post(':id/launch') async launch(
@Req() req: Request & { actor: Actor },
@Param('id') id: string,
@Body() body: unknown,
) {
z.object({}).strict().parse(body);
return {
data: await new WorkspaceLaunch(this.s.control.store, this.s.control.env).launch(
req.actor,
id,
req.header('Authorization') ?? '',
),
};
}
}

View File

@ -1,25 +0,0 @@
import { Body, Controller, Inject, Param, Post, Req } from '@nestjs/common';
import { z } from 'zod';
import type { Request } from 'express';
import type { Actor } from '@wishforge/contracts';
import { Services } from './http.js';
import { WorkspaceLifecycle } from './domain/workspace-lifecycle.js';
type AuthRequest = Request & { actor: Actor };
@Controller('v1/workspaces')
export class WorkspaceLifecycleController {
constructor(@Inject(Services) private s: Services) {}
@Post(':id/lifecycle') async control(@Req() req: AuthRequest, @Param('id') id: string, @Body() body: unknown) {
const input = z
.object({ action: z.enum(['pause', 'resume']), confirmation: z.literal('change-workspace-lifecycle') })
.strict()
.parse(body);
return {
data: await new WorkspaceLifecycle(this.s.control.store, this.s.control.env).manual(
req.actor,
id,
input.action,
req.header('Idempotency-Key') ?? '',
),
};
}
}

View File

@ -1,38 +0,0 @@
import type { ControlPlane } from './domain/control-plane.js';
import { WorkspaceLifecycle } from './domain/workspace-lifecycle.js';
import { dispatchTenants } from './tenants.js';
/** Independent of Temporal availability; durable outbox reconciliation owns no application deployment. */
export class WorkspaceLifecycleWorker {
private timer?: ReturnType<typeof setTimeout>;
private stopped = false;
private busy?: Promise<void>;
constructor(private control: ControlPlane) {}
start() {
const tick = async () => {
if (this.stopped) return;
this.busy = this.tick();
await this.busy;
if (!this.stopped) this.timer = setTimeout(() => void tick(), 10000);
};
void tick();
}
private async tick() {
const lifecycle = new WorkspaceLifecycle(this.control.store, this.control.env);
for (const tenant of dispatchTenants(this.control.env)) {
try {
const pending = await this.control.store.transaction(tenant, tx =>
tx.claimOutbox(['workspace.reconcile'], 120),
);
for (const item of pending) await lifecycle.reconcile(tenant, item);
await lifecycle.scheduleIdle(tenant);
} catch {
/* Durable items remain pending; never infer ready/suspended from a transport failure. */
}
}
}
async close() {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
await this.busy;
}
}

View File

@ -22,7 +22,7 @@ export interface GitClaims {
iat: number;
exp: number;
runId?: string;
/** Pushes may only update refs under this prefix: an IDE workspace pushes `refs/heads/ide/*`. */
/** Pushes may only update refs under this prefix, for example `refs/heads/ide/*`. */
refPrefix?: string;
}
const REF_PREFIX = /^refs\/heads\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/$/;
@ -39,7 +39,7 @@ const gitEnv = () => ({
/**
* Every push runs this hook. A credential scoped to a ref prefix cannot update anything else,
* so people's pushes from the IDE reach the target branch only through a verified wish.
* so such pushes reach the target branch only through a verified wish.
*/
export const PRE_RECEIVE_HOOK = [
'#!/bin/sh',

View File

@ -1,6 +0,0 @@
**/node_modules
lib
src-gen
plugins
workspace
**/test

11
apps/ide/.gitignore vendored
View File

@ -1,11 +0,0 @@
node_modules/
plugins/
lib/
src-gen/
workspace/
webpack.config.js
gen-webpack.config.js
tsconfig.json
*.tsbuildinfo
esbuild.mjs
gen-esbuild.*.mjs

View File

@ -1,29 +0,0 @@
# syntax=docker/dockerfile:1
# Operators supply reviewed immutable Debian-based Node images (build and slim runtime).
ARG NODE_IMAGE
ARG NODE_SLIM_IMAGE
# The Theia workspace (`--target theia`); Git clones the project and serves the Git extension.
FROM ${NODE_IMAGE} AS theia
RUN apt-get update && apt-get install -y --no-install-recommends git python3 make g++ libsecret-1-dev libx11-dev libxkbfile-dev libudev-dev && rm -rf /var/lib/apt/lists/*
WORKDIR /opt/wishforge-ide
ENV PUPPETEER_SKIP_DOWNLOAD=true
COPY package.json package-lock.json ./
COPY policy ./policy
COPY collaboration ./collaboration
RUN npm ci --no-audit --no-fund
COPY scripts ./scripts
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
EXPOSE 4300
CMD ["node", "scripts/start.mjs"]
# The workspace gateway needs only its own files and the WebSocket library.
FROM ${NODE_SLIM_IMAGE} AS gateway
WORKDIR /opt/wishforge-gateway
COPY --from=theia /opt/wishforge-ide/node_modules/ws ./node_modules/ws
COPY gateway ./gateway
USER node
ENV NODE_ENV=production WF_IDE_GATEWAY_HOST=0.0.0.0 WF_IDE_GATEWAY_PORT=4400
EXPOSE 4400
CMD ["node", "gateway/main.mjs"]

View File

@ -1,80 +0,0 @@
# 云 IDE(Theia)
基于 Eclipse Theia **1.76.0** 的浏览器 IDE,包含 `@theia/collaboration`。它是独立的 npm 包(自己的 `package-lock.json`),不属于根目录的 npm workspaces,因为 Theia 依赖树很大且含原生模块。
| 目录 | 内容 |
|---|---|
| `src-gen/`、`lib/` | Theia 构建产物(`npm run ide:build` 生成) |
| `policy/` | 策略扩展:扩展白名单、按工作区隔离的协作,见 [policy/README.md](policy/README.md) |
| `gateway/` | IDE 网关:浏览器访问 Theia 的唯一入口,见 [gateway/README.md](gateway/README.md) |
| `collaboration/` | 每个工作区独立的 OCT 协作服务,见 [collaboration/README.md](collaboration/README.md) |
| `scripts/` | 启动脚本、扩展下载与校验 |
| `plugins/` | 镜像内固定的扩展(`plugins:download` 生成) |
## 本地运行
```bash
npm run ide:install
```
```bash
npm run ide:build
```
```bash
npm run dev:ide
```
`dev:ide` 启动 Theia(`http://127.0.0.1:4300`,只能经网关访问)与网关(`http://127.0.0.1:4400`),所有工作区共用 `.wishforge/ide-workspace` 目录,每个项目克隆到其中以项目命名的文件夹(工作分支 `ide/work`),仓库令牌放在 `.wishforge/ide-credentials`。原生模块的编译需要 Python、make/C++ 与系统开发库(Linux 依赖见 `Dockerfile`)。
在项目页创建开发环境后点击「打开 IDE」。
- **克隆**:平台托管仓库的项目第一次打开时会被克隆到以项目命名的文件夹,通常几秒内出现在资源管理器中,并处在 `ide/work` 分支上。外部仓库(如 GitHub)不克隆,那里的改动应走 PR。
- **推送**:提交后直接 `git push`(或 Git 面板的「发布分支」),推送到 `ide/work`。也可以建其他 `ide/` 开头的分支;推送目标分支或其他分支会被平台 Git 拒绝。
- **合入**:在项目页的 IDE 分支列表点「提交愿望合入」,或提交愿望时把「起点」选成这个分支。运行从分支的最新提交开始,Agent 在上面继续实现,验证通过后一并合入目标分支;验证失败时照常进入修复轮。
- **同步**:Agent 合入了新的改动后,用 `git pull origin <目标分支>` 把它们拉进 `ide/work`。
- **凭据**:会话期间网关持续送来 15 分钟的仓库令牌,存放在仓库之外(见 [policy/README.md](policy/README.md))。没有人打开 IDE 时令牌会过期,`git push` 也随之失败。
- **提交身份**:取最近打开会话的用户,用 `git config user.name`、`git config user.email` 可以改成自己的。
IDE 与 Agent 之间只通过 Git commit 交接,不存在 IDE 快照之类的旁路。
## 扩展
只能使用镜像中预置并校验过的扩展,运行时的安装、卸载、启用与停用请求都会被后端拒绝(`EXTENSIONS_MANAGED_BY_ADMIN`)。
- 内置扩展来自官方 `vscode-builtin-extensions` **1.108.2** 归档(SHA-256 `05a20cf3e671c8d328b04d9ce72b25688b0e762e4a3f5592f31a21ee38280367`),提供 Git、语言支持与 JavaScript 调试,每个扩展的 ID、版本与内容摘要记录在 `policy/managed-plugins.lock.json`;`node scripts/catalog-builtin-plugins.mjs <归档>` 在校验归档后重新生成该清单。
- Python 支持:`ms-python.python` 2026.4.0、`ms-python.debugpy` 2026.6.0(调试器)、`ms-pyright.pyright` 1.1.402(补全、悬停与诊断),在 `scripts/python-debugger.lock.json` 中为 Linux x64/ARM64 与 macOS x64/ARM64 固定了官方 VSIX 的校验和;其他平台明确失败。Python 解释器本身需要在工作区镜像或项目虚拟环境中提供。
```bash
npm run plugins:download --prefix apps/ide
```
```bash
npm run plugins:verify --prefix apps/ide
```
离线构建时可以把已下载的 VSIX 传给 `npm run plugins:download:python -- --archive <debugpy.vsix> --python-archive <python.vsix> --pyright-archive <pyright.vsix>`。下载脚本校验 SHA-256、包身份、大小与解压路径,并原子地解包(Theia 的 `local-dir` 加载器不会加载未解包的 VSIX)。缺少、多出或被修改的扩展都会让启动失败。
## 镜像
`apps/ide/Dockerfile` 以 `apps/ide` 为构建上下文,运维提供 `NODE_IMAGE` 与 `NODE_SLIM_IMAGE`:
- `theia` 目标:Theia 工作区(含 Git)。应用、扩展与清单归 root 所有,只有 `/workspace` 交给运行用户;生产还需要 provisioner 设置只读根文件系统。
- `gateway` 目标:IDE 网关。它是最后一个阶段,所以不指定 `--target` 时构建的是网关。
## 生产边界
- 不要直接暴露 4300 端口:终端、文件、插件与调试接口都必须在网关之后。启动脚本在 `NODE_ENV=production` 时要求 `WISHFORGE_GATEWAY_ENFORCED=true`——这只是运维的声明,真正的保护来自网关与网络策略。
- 只有项目的 owner/admin/developer 能进入编辑会话或协作房间;viewer 不会拿到 IDE 会话。Theia 内置协作的只读控制并不完整,隐藏按钮不是授权边界。
- OCT 0.3.1 的房间状态只在内存中:服务重启后需要新建房间,未保存的编辑可能丢失。
- Theia 后端与用户终端以同一个系统用户运行,同一工作区内的协作者之间没有隔离;工作区只应授予可信成员编辑权限。
## 测试
```bash
npm run test:ide
```
运行网关、协作客户端与策略扩展的 Node 测试(需要先 `npm run ide:install`)。Theia 的界面行为(编辑器、终端、调试、Python 语言服务)没有自动化测试,修改依赖或扩展后需要在浏览器中手动验证。
参考:[Theia 架构](https://theia-ide.org/docs/architecture/)、[Theia 1.76 协作源码](https://github.com/eclipse-theia/theia/blob/v1.76.0/packages/collaboration/src/browser/collaboration-frontend-contribution.ts)、[OCT 0.3.1](https://github.com/eclipse-oct/open-collaboration-tools/tree/ef757242e1bc5bd4a74f1baf068aa047decaad13)、[内置扩展发布](https://github.com/eclipse-theia/vscode-builtin-extensions/releases/tag/1.108.2)。

View File

@ -1,6 +0,0 @@
# Build the pinned upstream runtime first with infra/oct/Dockerfile.
FROM wishforge/oct:0.3.1-wf1
COPY --chown=node:node start-isolated.mjs /opt/oct/start-isolated.mjs
ENV WF_OCT_HOST=0.0.0.0
EXPOSE 8100
CMD ["node", "/opt/oct/start-isolated.mjs"]

View File

@ -1,57 +0,0 @@
# 按工作区隔离的 OCT 协作
本目录提供协作服务的启动器(`start-isolated.mjs`)与策略扩展使用的地址前缀适配器(`client-factory.cjs`)。每个工作区运行一个独立的 Open Collaboration Tools(OCT)0.3.1 进程,房间注册表与签名密钥不在工作区之间共享。身份以 WishForge 网关会话为准;OCT 的 `user` 显示名只是未经校验的展示文本,不代表租户身份或权限。
## 与上游实现相关的约束
以下行为来自固定版本的 Theia 1.76.0 与 OCT 0.3.1 源码,适配器据此设计:
- OCT 服务的 HTTP 路由都在根路径(`/api/meta`、`/api/login/*`、`/api/session/*`),没有 basepath 选项;Socket.IO 使用默认的 `/socket.io/` 路径,独立的 `/websocket` 服务在上游被注释掉,所以只支持 Socket.IO 传输。
- 上游的 Socket.IO 传输调用 `io(url)` 时不传 `path`,会把 URL 路径当作命名空间;Theia 的登录表单也会把绝对端点解析到源站根路径、丢掉工作区前缀。适配器因此显式设置 Socket.IO 路径为 `/workspaces/<id>/collaboration/socket.io`,并把登录端点改写为相对的 `api/login/simple`,不允许任意 OAuth 地址。
- 上游默认使用固定的开发签名密钥且 JWT 不过期。`start-isolated.mjs` 为每个进程生成随机密钥、JWT 8 小时过期,只开启显示名登录(`OCT_ACTIVATE_SIMPLE_LOGIN=true`)。服务重启后旧的房间凭据失效,需要重新创建或加入房间。它还绕开了 OCT 0.3.1 命令行 `parseInt` 端口参数的问题。
- Theia 使用的协议 0.3.0 与服务端 0.3.1 兼容(0.x 系列按主次版本号校验)。
源码位置:[OCT 服务](https://github.com/eclipse-oct/open-collaboration-tools/blob/ef757242e1bc5bd4a74f1baf068aa047decaad13/packages/open-collaboration-server/src/collaboration-server.ts)、[显示名登录](https://github.com/eclipse-oct/open-collaboration-tools/blob/ef757242e1bc5bd4a74f1baf068aa047decaad13/packages/open-collaboration-server/src/auth-endpoints/simple-login-endpoint.ts)、[凭据管理](https://github.com/eclipse-oct/open-collaboration-tools/blob/ef757242e1bc5bd4a74f1baf068aa047decaad13/packages/open-collaboration-server/src/credentials-manager.ts)、[协议连接](https://github.com/eclipse-oct/open-collaboration-tools/blob/ef757242e1bc5bd4a74f1baf068aa047decaad13/packages/open-collaboration-protocol/src/connection-provider.ts)、[Theia 协作贡献](https://github.com/eclipse-theia/theia/blob/v1.76.0/packages/collaboration/src/browser/collaboration-frontend-contribution.ts)。
## 网关与客户端约定
API 的工作区授权结果给出可信的上游地址:
```json
{
"tenantId": "tenant-id",
"projectId": "project-id",
"workspaceId": "workspace-id",
"role": "developer",
"upstreamUrl": "http://workspace-service:3000",
"collaborationUpstreamUrl": "http://workspace-service:8100"
}
```
只有 provisioner 能设置这些上游,公开调用方不能指定 OCT 地址。网关对 `/workspaces/<id>/collaboration/` 下的每个 HTTP 请求与 WebSocket 升级都要求 `edit` 权限,去掉前缀后转发到该工作区的 `collaborationUpstreamUrl`;保留 `x-oct-*` 协议头,去掉平台的 bearer 令牌与 Cookie,并定期复核已升级的连接。viewer 不能进入协作。
Theia 后端收到 `WF_COLLABORATION_GATEWAY_URL=https://ide.example/workspaces/<id>/collaboration/`。客户端适配器要求该地址与浏览器同源且属于当前工作区;初次握手使用轮询(便于携带 OCT 请求头),之后升级为 WebSocket。
## 运行
每个工作区一个协作进程,配置 `WF_WORKSPACE_ID`、`WF_TENANT_ID`、`WF_OCT_PORT=8100`、`WF_OCT_HOST=0.0.0.0` 与 `WISHFORGE_GATEWAY_ENFORCED=true`。在 Kubernetes 中放在工作区的 Kata Pod 内,8100 端口只允许网关访问,不对外暴露 Ingress;不需要工作区卷,根文件系统可以只读,去掉 Linux capability 并禁止提权。本机只在回环地址监听时可以使用默认的 `WF_OCT_HOST=127.0.0.1`。
```bash
docker build -t wishforge/oct-workspace:0.3.1-wf1 apps/ide/collaboration
```
`infra/compose.yaml` 中共享的开发 OCT 容器只用于协议检查,不承载工作区的房间。
## 测试
```bash
node --test apps/ide/collaboration/test/client-factory.test.cjs
```
```bash
WF_OCT_INTEGRATION=1 node --test --test-force-exit apps/ide/collaboration/test/isolated-oct.test.mjs
```
第二个测试需要 Docker:启动两个只监听回环地址的 OCT 容器,经真实的网关、不透明会话、固定版本的协议客户端、Socket.IO 加密与 Yjs 文档,验证主客双向编辑收敛、viewer 被拒绝、其他工作区的 Cookie 与复制的邀请被拒绝、跨实例 JWT 被拒绝,以及撤销权限后连接被关闭。其中控制面的授权接口是测试替身,因此它验证的是协议与路由,不是生产 OIDC 或 Kata 环境。Node 测试中 Engine.IO 在 `withCredentials=true` 时会替换手工注入的 Cookie,所以测试把它设为 false;浏览器客户端保持 true,依赖网关真实的 HttpOnly Cookie。
OCT 0.3.1 的房间只保存在内存中,不支持持久化的房间恢复。

View File

@ -1,59 +0,0 @@
/** Prefix-aware OCT adapter for Theia 1.76 / open-collaboration-protocol 0.3.x.
* Platform authentication remains the workspace gateway's HttpOnly session.
* OCT display names and room tokens never grant access to a workspace.
*/
function collaborationBase(raw, browserLocation) {
const location = new URL(browserLocation);
const base = new URL(raw, location.origin);
const match = /^\/workspaces\/([a-zA-Z0-9][a-zA-Z0-9_-]*)\//.exec(location.pathname);
if (
!match ||
base.origin !== location.origin ||
base.username ||
base.password ||
base.search ||
base.hash ||
base.pathname !== `/workspaces/${match[1]}/collaboration/`
)
throw new Error('Collaboration must use this workspace authenticated gateway path');
return base;
}
function normalizeAuthMetadata(meta) {
const providers = (meta.providers ?? [])
.filter(
provider =>
provider.type === 'form' && provider.name === 'unverified' && provider.endpoint === '/api/login/simple',
)
.map(provider => ({ ...provider, endpoint: 'api/login/simple' }));
if (providers.length !== 1) throw new Error('Workspace collaboration requires its isolated display-name provider');
return { ...meta, providers, loginPageUrl: undefined };
}
function createPrefixTransport({ io, SocketIoTransport }, baseUrl) {
const base = new URL(baseUrl);
return {
id: 'socket.io',
createTransport(_url, headers) {
// io(baseUrl) treats the pathname as a namespace and silently uses /socket.io.
// Explicit path and origin keep both Engine.IO polling and WS upgrade scoped.
const socket = io(base.origin, {
path: `${base.pathname}socket.io`,
extraHeaders: headers,
withCredentials: true,
transports: ['polling', 'websocket'],
});
return new SocketIoTransport(socket);
},
};
}
function createPrefixConnectionProvider(deps, options) {
const base = collaborationBase(options.url, options.browserLocation);
return new deps.ConnectionProvider({
url: base.href,
client: options.client,
fetch: (url, init) => options.fetch(url, { ...init, credentials: 'same-origin' }),
authenticationHandler: (token, metadata) => options.authenticationHandler(token, normalizeAuthMetadata(metadata)),
transports: [createPrefixTransport(deps, base.href)],
userToken: options.userToken,
});
}
module.exports = { collaborationBase, normalizeAuthMetadata, createPrefixTransport, createPrefixConnectionProvider };

View File

@ -1,34 +0,0 @@
import 'reflect-metadata';
import { randomBytes, webcrypto } from 'node:crypto';
import { Container } from 'inversify';
import { initializeProtocol } from 'open-collaboration-protocol';
import { CollaborationServer, CredentialsManager, AuthEndpoint, SimpleLoginEndpoint } from 'open-collaboration-server';
const id = value => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,199}$/.test(value);
if (!id(process.env.WF_WORKSPACE_ID) || !id(process.env.WF_TENANT_ID))
throw new Error('Each OCT instance requires its own WF_WORKSPACE_ID and WF_TENANT_ID');
const hostname = process.env.WF_OCT_HOST ?? '127.0.0.1';
if (!['127.0.0.1', '0.0.0.0'].includes(hostname)) throw new Error('Invalid isolated OCT listen address');
if (hostname !== '127.0.0.1' && process.env.WISHFORGE_GATEWAY_ENFORCED !== 'true')
throw new Error('Network binding requires an enforced workspace gateway and default-deny network policy');
const port = Number(process.env.WF_OCT_PORT ?? 8100);
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid isolated OCT port');
// Never use OCT's shared development signing key. A restart invalidates all room
// capabilities because upstream room state is in memory and cannot be recovered.
process.env.OCT_JWT_PRIVATE_KEY = randomBytes(48).toString('base64url');
process.env.OCT_ACTIVATE_SIMPLE_LOGIN = 'true';
process.env.OCT_SERVER_OWNER = `WishForge workspace ${process.env.WF_WORKSPACE_ID}`;
initializeProtocol({ cryptoModule: webcrypto });
const { default: serverModule } = await import(
new URL('./inversify-module.js', import.meta.resolve('open-collaboration-server')).href
);
const container = new Container();
container.load(serverModule);
// This deployment deliberately has one display-name form behind the gateway;
// no external OAuth providers or account registration flows are activated.
container.rebind(AuthEndpoint).toService(SimpleLoginEndpoint);
const credentials = container.get(CredentialsManager);
credentials.getJwtExpiration = async () => '8h';
const server = container.get(CollaborationServer);
// Call the typed API instead of the 0.3.1 Commander parseInt/radix port bug.
server.startServer({ hostname, port });

View File

@ -1,55 +0,0 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { collaborationBase, normalizeAuthMetadata, createPrefixTransport } = require('../client-factory.cjs');
test('collaboration URLs remain within the authenticated workspace and same origin', () => {
const location = 'https://ide.example/workspaces/alpha/index.html';
assert.equal(
collaborationBase('https://ide.example/workspaces/alpha/collaboration/', location).pathname,
'/workspaces/alpha/collaboration/',
);
for (const url of [
'https://external.example/workspaces/alpha/collaboration/',
'https://ide.example/workspaces/beta/collaboration/',
'https://ide.example/socket.io/',
'https://ide.example/workspaces/alpha/collaboration/?token=secret',
])
assert.throws(() => collaborationBase(url, location));
});
test('simple display-name form URL cannot escape the workspace basepath', () => {
const meta = normalizeAuthMetadata({
providers: [
{ type: 'form', name: 'unverified', endpoint: '/api/login/simple' },
{ type: 'web', name: 'github', endpoint: 'https://external.example' },
],
});
assert.equal(meta.providers.length, 1);
assert.equal(
new URL(meta.providers[0].endpoint, 'https://ide.example/workspaces/alpha/collaboration/').pathname,
'/workspaces/alpha/collaboration/api/login/simple',
);
assert.throws(() => normalizeAuthMetadata({ providers: [], loginPageUrl: 'https://external.example/login' }));
});
test('Socket.IO uses origin namespace plus a workspace-specific Engine.IO path', () => {
let observed;
const socket = {};
const adapter = createPrefixTransport(
{
io: (...args) => {
observed = args;
return socket;
},
SocketIoTransport: class {
constructor(value) {
this.socket = value;
}
},
},
'https://ide.example/workspaces/alpha/collaboration/',
);
const transport = adapter.createTransport('ignored', { 'x-oct-jwt': 'room-token' });
assert.equal(transport.socket, socket);
assert.equal(observed[0], 'https://ide.example');
assert.equal(observed[1].path, '/workspaces/alpha/collaboration/socket.io');
assert.deepEqual(observed[1].transports, ['polling', 'websocket']);
assert.equal(observed[1].extraHeaders['x-oct-jwt'], 'room-token');
});

View File

@ -1,281 +0,0 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { randomUUID, webcrypto } from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
import { createGateway } from '../../gateway/server.mjs';
import factory from '../client-factory.cjs';
const require = createRequire(new URL('../../package.json', import.meta.url));
const protocol = await import(pathToFileURL(require.resolve('open-collaboration-protocol')).href);
const { io } = await import(pathToFileURL(require.resolve('socket.io-client')).href);
const { OpenCollaborationYjsProvider } = await import(pathToFileURL(require.resolve('open-collaboration-yjs')).href);
const Y = await import('../../node_modules/yjs/dist/yjs.mjs');
const { Awareness } = await import('../../node_modules/y-protocols/awareness.js');
protocol.initializeProtocol({ cryptoModule: webcrypto });
const execute = promisify(execFile);
const docker = (...args) =>
execute('docker', ['--context', process.env.WF_TEST_DOCKER_CONTEXT ?? 'colima', ...args], { timeout: 30_000 });
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(check, message) {
const end = Date.now() + 10_000;
do {
if (await check()) return;
await sleep(25);
} while (Date.now() < end);
throw new Error(message);
}
async function listen(server) {
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return `http://127.0.0.1:${server.address().port}`;
}
test(
'two isolated OCT instances support scoped Socket.IO/Yjs collaboration and reject invite/token reuse across workspaces',
{ skip: process.env.WF_OCT_INTEGRATION !== '1', timeout: 60_000 },
async () => {
const names = [],
connections = [],
docs = [],
awareness = [],
sockets = [];
let api, gateway;
const revoked = new Set();
const members = {
alice: { workspace: 'workspace-a', role: 'developer' },
bob: { workspace: 'workspace-a', role: 'developer' },
charlie: { workspace: 'workspace-b', role: 'developer' },
viewer: { workspace: 'workspace-a', role: 'viewer' },
};
try {
const origins = {};
for (const workspace of ['workspace-a', 'workspace-b']) {
const name = `wishforge-oct-test-${randomUUID().slice(0, 8)}`;
names.push(name);
await docker(
'run',
'-d',
'--rm',
'--name',
name,
'--read-only',
'--cap-drop',
'ALL',
'--security-opt',
'no-new-privileges',
'--tmpfs',
'/tmp:rw,noexec,nosuid,size=16m',
'-p',
'127.0.0.1::8100',
'-e',
`WF_WORKSPACE_ID=${workspace}`,
'-e',
'WF_TENANT_ID=fixture-tenant',
'-e',
'WISHFORGE_GATEWAY_ENFORCED=true',
'wishforge/oct-workspace:0.3.1-wf1',
);
const port = (await docker('port', name, '8100/tcp')).stdout.trim().split(':').at(-1);
origins[workspace] = `http://127.0.0.1:${port}`;
await until(async () => {
try {
return (await fetch(`${origins[workspace]}/api/meta`)).ok;
} catch {
return false;
}
}, 'OCT did not start');
}
api = http.createServer(async (req, res) => {
let text = '';
for await (const bytes of req) text += bytes;
const request = JSON.parse(text),
who = members[request.userToken],
workspace = req.url.split('/')[3];
if (!who || revoked.has(request.userToken) || who.workspace !== workspace) {
res.writeHead(403);
res.end();
return;
}
assert.equal(request.operation, 'edit');
res.setHeader('content-type', 'application/json');
res.end(
JSON.stringify({
data: {
tenantId: 'fixture-tenant',
projectId: `project-${workspace}`,
workspaceId: workspace,
role: who.role,
upstreamUrl: origins[workspace],
collaborationUpstreamUrl: origins[workspace],
},
}),
);
});
const apiOrigin = await listen(api);
// Reserve a local port before gateway construction, which requires its public origin.
const reserve = http.createServer();
const publicUrl = await listen(reserve);
await new Promise(resolve => reserve.close(resolve));
gateway = createGateway({
publicUrl,
tenantId: 'fixture-tenant',
serviceToken: 'gateway-fixture-token',
apiOrigin,
allowedUpstreamOrigins: Object.values(origins),
allowedCollaborationOrigins: Object.values(origins),
reauthorizeMs: 50,
});
await new Promise(resolve => gateway.server.listen(Number(new URL(publicUrl).port), '127.0.0.1', resolve));
async function session(user) {
const workspace = members[user].workspace;
const launch = await fetch(`${publicUrl}/launch`, {
method: 'POST',
headers: { authorization: `Bearer ${user}`, 'content-type': 'application/json' },
body: JSON.stringify({ workspaceId: workspace }),
});
if (!launch.ok) return { status: launch.status };
const { launchUrl } = await launch.json();
const response = await fetch(launchUrl, { redirect: 'manual' });
return { status: response.status, cookie: response.headers.get('set-cookie').split(';')[0], workspace };
}
const alice = await session('alice'),
bob = await session('bob'),
charlie = await session('charlie');
assert.equal((await session('viewer')).status, 403);
function client(user, displayName) {
const url = `${publicUrl}/workspaces/${user.workspace}/collaboration/`;
const localFetch = (target, init = {}) =>
fetch(target, { ...init, headers: { ...init.headers, cookie: user.cookie, origin: publicUrl } });
return factory.createPrefixConnectionProvider(
{
...protocol,
io: (origin, options) => {
const socket = io(origin, {
...options,
withCredentials: false,
extraHeaders: { ...options.extraHeaders, Cookie: user.cookie, Origin: publicUrl },
});
sockets.push(socket);
socket.on('connect_error', error =>
console.error(
'OCT socket connection error:',
error.message,
error.description,
error.context?.status,
error.context?.responseText?.slice(0, 300),
),
);
return socket;
},
},
{
url,
browserLocation: `${publicUrl}/workspaces/${user.workspace}/`,
client: 'WishForge integration',
fetch: localFetch,
authenticationHandler: async (token, metadata) => {
assert.equal(metadata.providers[0].endpoint, 'api/login/simple');
return (
await localFetch(new URL(metadata.providers[0].endpoint, url), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token, user: displayName }),
})
).ok;
},
},
);
}
const hostProvider = client(alice, 'Host display name'),
guestProvider = client(bob, 'Guest display name');
const claim = await hostProvider.createRoom({ abortSignal: AbortSignal.timeout(10_000) });
const host = await hostProvider.connect(claim.roomToken);
connections.push(host);
let hostIdentity;
host.peer.onInfo((_origin, peer) => {
hostIdentity = peer;
});
host.peer.onJoinRequest(async () => ({ workspace: { name: 'fixture', folders: ['source'] } }));
host.room.onJoin((_origin, peer) =>
host.peer.init(peer.id, {
protocol: protocol.VERSION,
host: hostIdentity,
guests: [peer],
permissions: { readonly: false },
capabilities: {},
workspace: { name: 'fixture', folders: ['source'] },
}),
);
await until(() => !!hostIdentity, 'Host peer did not connect');
const guestClaim = await guestProvider.joinRoom({
roomId: claim.roomId,
abortSignal: AbortSignal.timeout(10_000),
});
const guest = await guestProvider.connect(guestClaim.roomToken, guestClaim.host);
connections.push(guest);
guest.peer.onInfo(() => {});
let initialized = false;
guest.peer.onInit(() => {
initialized = true;
});
await until(() => initialized, 'Guest did not receive encrypted initialization');
for (const connection of [host, guest]) {
const doc = new Y.Doc();
const state = new Awareness(doc);
docs.push(doc);
awareness.push(state);
const provider = new OpenCollaborationYjsProvider(connection, doc, state);
provider.connect();
}
docs[0].getText('source/example.ts').insert(0, 'const greeting = "hello";');
await until(
() => docs[1].getText('source/example.ts').toString().includes('hello'),
'Host edit did not reach guest',
);
docs[1].getText('source/example.ts').insert(docs[1].getText('source/example.ts').length, '\n// guest edit');
await until(
() => docs[0].getText('source/example.ts').toString().includes('guest edit'),
'Guest edit did not reach host',
);
assert.equal(docs[0].getText('source/example.ts').toString(), docs[1].getText('source/example.ts').toString());
assert.equal(
(
await fetch(`${publicUrl}/workspaces/workspace-a/collaboration/api/meta`, {
headers: { cookie: charlie.cookie },
})
).status,
401,
);
const outsider = client(charlie, 'Allowed in other workspace');
await assert.rejects(
() => outsider.joinRoom({ roomId: claim.roomId, abortSignal: AbortSignal.timeout(5_000) }),
/Room not found/,
);
const tokenCheck = await fetch(`${origins['workspace-b']}/api/login/validate`, {
method: 'POST',
headers: { 'x-oct-jwt': hostProvider.authToken },
});
assert.equal((await tokenCheck.json()).valid, false, 'Per-instance keys must reject another workspace OCT JWT');
revoked.add('bob');
await until(() => sockets[1].disconnected, 'Revoked member websocket was not closed');
assert.equal(
(await fetch(`${publicUrl}/workspaces/workspace-a/collaboration/api/meta`, { headers: { cookie: bob.cookie } }))
.status,
403,
);
} catch (error) {
for (const name of names) console.error((await docker('logs', '--tail', '15', name)).stdout);
throw error;
} finally {
for (const state of awareness) state.destroy();
for (const doc of docs) doc.destroy();
for (const connection of connections) connection.dispose();
for (const socket of sockets) socket.disconnect();
if (gateway) await gateway.close();
if (api) await new Promise(resolve => api.close(resolve));
await Promise.all(names.map(name => docker('stop', '-t', '1', name).catch(() => undefined)));
}
},
);

View File

@ -1,49 +0,0 @@
# IDE 网关
浏览器访问 Theia 的唯一入口,负责 HTTP 与 WebSocket 的身份校验。每个租户运行一个网关。本地用 `npm run dev:ide` 与 Theia 一起启动。
| 变量 | 说明 |
|---|---|
| `WF_DEPLOYMENT_MODE` | 只有 `development` 允许 HTTP 公网地址与默认的本机 Theia |
| `WF_API_URL` | 控制面 API 地址 |
| `WF_TENANT_ID` | 网关所属租户 |
| `WF_WORKSPACE_GATEWAY_TOKEN` | 调用 API `/internal/workspaces/*` 的网关令牌 |
| `WF_IDE_PUBLIC_URL` | 浏览器访问网关的地址,生产必须是 HTTPS(Cookie 才会带 Secure) |
| `WF_IDE_ALLOWED_UPSTREAM_ORIGINS` | 允许的 Theia 上游地址(本地为 `http://127.0.0.1:4300`) |
| `WF_IDE_ALLOWED_SERVICE_NAMESPACE` | Kubernetes 中工作区 Service 所在命名空间:上游必须是 `wf-ide-<24 位十六进制>.<命名空间>.svc:3000`,协作端口为 8100 |
| `WF_COLLABORATION_ALLOWED_UPSTREAM_ORIGINS` | 本地允许的协作服务上游 |
| `WF_IDE_GATEWAY_HOST`、`WF_IDE_GATEWAY_PORT` | 监听地址,默认 `127.0.0.1:4400` |
## 会话
1. Web 服务端用用户的 access token 调用 `POST /launch`(body `{workspaceId}`),网关向 API 校验后返回 `launchUrl`,其中只有 30 秒有效的一次性随机码,不含用户令牌。
2. 浏览器访问 `GET /session?code=…`,网关再次校验、消费启动码,设置不透明的 HttpOnly、SameSite=Strict Cookie 并跳转到 `/workspaces/:id/`。访问日志必须隐去启动码查询串。
3. 会话空闲 15 分钟失效;每次成功的请求与打开的 WebSocket 的周期复核都会续期,最长 12 小时。会话建立后,网关按已授权的用户 ID 复核,用户的 access token 过期不会中断正在使用的 IDE。
## 校验
- 每个 HTTP 请求与 WebSocket 握手都以网关令牌和固定的 `X-WishForge-Tenant` 调用 API `POST /internal/workspaces/:id/authorize`。打开的 WebSocket 每秒复核一次(复核超时 3 秒);被拒绝、会话过期、上游变化或控制面不可用时立即断开,因此撤销成员资格后现有连接会被关闭。
- 上游地址只来自 API 的授权结果,并且必须在允许列表内;调用方不能选择上游,也不能把操作降级为只读。viewer 不能进入编辑会话。
- 转发前去掉用户凭据、浏览器 Cookie 与调用方伪造的 `x-wishforge-*` 头。Theia 自己的 `theia-connection-token` 保存在网关进程中,不会下发给浏览器,也不会转发给协作服务。
- `/workspaces/:id/collaboration/*` 把 HTTP 与 Socket.IO 转发到授权结果中该工作区专用的 OCT 实例,每个请求都要求编辑权限。
- `POST /internal/lifecycle-state`(网关令牌)告诉控制面某个工作区当前的连接数,用于空闲自动暂停。
## 仓库凭据
- **申请**:会话建立时,以及打开的 WebSocket 复核时令牌快到期(剩 5 分钟),网关以会话用户的身份调用 API `POST /internal/workspaces/:id/git-credential`,取得 15 分钟的仓库令牌。这个令牌只能推送 `ide/` 开头的分支,由平台 Git 执行这条限制。
- **投递**:网关把令牌交给工作区的 `POST /wishforge-internal/git-credential`,并附带 Theia 的连接令牌(没有就先请求一次 Theia 首页取得;Theia 重启后会自动重新取得)。投递内容还包括项目、仓库地址、目标分支和提交身份。
- **提交身份**:取最近建立的会话用户,来自 API 首次授权时按 OIDC name/email 给出的 `author`。
- **失败与例外**:失败时 30 秒后重试。外部仓库的项目 API 返回 409;工作区没有配置仓库时 Theia 返回 404。这两种情况在 30 分钟内不再申请,重新打开 IDE 会立即再试。
- **路径保护**:浏览器请求 `/workspaces/:id/wishforge-internal/*` 一律返回 404,只有网关自己能投递凭据。
## 限制
- 会话与启动码保存在进程内存中:网关重启后需要重新打开 IDE;多副本需要共享会话存储或会话亲和。
- 生产中必须让 Theia 与 OCT 只能经由网关访问,这需要在真实集群上验证网络隔离。
## 测试
需要先 `npm run ide:install`,然后运行 `npm run test:ide`。
- `gateway.test.mjs` 使用真实的本地 HTTP/WebSocket 服务,覆盖凭据不转发、启动码不可重放、viewer 拒绝、上游允许列表、Origin 检查、撤销后断开、使用中的会话续期与生命周期接口。
- `gateway-handler.test.mjs` 不打开端口,直接驱动网关的请求处理器并使用伪造的 `fetch`,覆盖启动时提交用户令牌、仓库凭据的申请与投递、Theia 重启后重新取得连接令牌、凭据路径对浏览器不可见以及外部仓库不投递。

View File

@ -1,129 +0,0 @@
// While someone has a workspace open, the gateway keeps its Git credential fresh: the control
// plane mints a short-lived repository token for the session's user, and the gateway hands it
// to the workspace backend, which clones the project on the first delivery. Nothing in the
// workspace can mint a credential itself, so access ends with the last session.
const CONNECTION_COOKIE = 'theia-connection-token';
export const CREDENTIAL_PATH = '/wishforge-internal/git-credential';
const REFRESH_BEFORE_MS = 5 * 60_000;
const RETRY_MS = 30_000;
// A project without a platform repository, or a workspace without the endpoint, keeps
// answering the same way; ask again rarely.
const UNSUPPORTED_RETRY_MS = 30 * 60_000;
export function createGitCredentials(config) {
const fetchImpl = config.fetchImpl ?? fetch;
const now = config.now ?? Date.now;
const state = new Map();
const authors = new Map();
function connectionToken(response) {
for (const cookie of response.headers.getSetCookie?.() ?? []) {
const token = new RegExp(`^${CONNECTION_COOKIE}=([^;\\s]{1,512})(?:;|$)`).exec(cookie)?.[1];
if (token) return token;
}
return undefined;
}
/** Theia accepts the delivery only with its connection token, which the gateway alone holds. */
async function bootstrapToken(upstream) {
const response = await fetchImpl(upstream.href, { redirect: 'manual', signal: AbortSignal.timeout(5000) });
await response.body?.cancel();
const token = connectionToken(response);
if (token) config.setConnectionToken(upstream.href, token);
return token;
}
async function credentialFor(workspaceId, userId) {
const response = await fetchImpl(
`${config.apiOrigin}/internal/workspaces/${encodeURIComponent(workspaceId)}/git-credential`,
{
method: 'POST',
headers: {
authorization: `Bearer ${config.serviceToken}`,
'content-type': 'application/json',
'X-WishForge-Tenant': config.tenantId,
},
body: JSON.stringify({ userId }),
signal: AbortSignal.timeout(5000),
redirect: 'error',
},
);
if (response.status === 409) return { unsupported: true };
if (!response.ok) throw new Error('GIT_CREDENTIAL_UNAVAILABLE');
const payload = await response.json();
return payload.data ?? payload;
}
async function deliver(upstream, body) {
const target = new URL(upstream);
target.pathname = `${target.pathname.replace(/\/$/, '')}${CREDENTIAL_PATH}`;
for (let attempt = 0; attempt < 2; attempt++) {
const token = (attempt === 0 && config.connectionToken(upstream.href)) || (await bootstrapToken(upstream));
if (!token) throw new Error('WORKSPACE_CONNECTION_TOKEN_UNAVAILABLE');
const response = await fetchImpl(target, {
method: 'POST',
headers: { 'content-type': 'application/json', cookie: `${CONNECTION_COOKIE}=${token}` },
body: JSON.stringify(body),
signal: AbortSignal.timeout(10000),
redirect: 'error',
});
await response.body?.cancel();
// A restarted Theia has a new connection token; fetch it once and try again.
if (response.status === 403 && attempt === 0) continue;
// A workspace provisioned without the project's repository has no endpoint to deliver to.
if (response.status === 404) return { unsupported: true };
if (!response.ok) throw new Error('WORKSPACE_GIT_DELIVERY_FAILED');
return {};
}
}
async function refresh(workspaceId, upstream, userId) {
const current = state.get(workspaceId);
try {
const credential = await credentialFor(workspaceId, userId);
if (credential.unsupported) {
current.nextAt = now() + UNSUPPORTED_RETRY_MS;
return;
}
const author = authors.get(workspaceId);
const delivered = await deliver(upstream, {
projectId: credential.projectId,
projectName: credential.projectName,
repositoryUrl: credential.repositoryUrl,
branch: credential.branch,
token: credential.token,
expiresAt: credential.expiresAt,
...(author ? { author } : {}),
});
current.nextAt = delivered.unsupported
? now() + UNSUPPORTED_RETRY_MS
: Math.max(now() + 60_000, Date.parse(credential.expiresAt) - REFRESH_BEFORE_MS);
} catch {
current.nextAt = now() + RETRY_MS;
}
}
return {
/** A new session also makes its user the author of the workspace's next commits. */
opened(session, upstream) {
if (session.author) authors.set(session.workspaceId, session.author);
const current = state.get(session.workspaceId);
if (current) {
current.nextAt = 0;
// A delivery already under way may carry the previous author; send another after it.
if (current.inFlight) current.again = true;
}
return this.due(session, upstream);
},
/** Called whenever a session is used; refreshes at most one delivery per workspace at a time. */
due(session, upstream) {
if (!session.userId) return undefined;
const current = state.get(session.workspaceId) ?? { nextAt: 0 };
state.set(session.workspaceId, current);
if (current.inFlight || now() < current.nextAt) return current.inFlight;
current.inFlight = refresh(session.workspaceId, upstream, session.userId).finally(() => {
current.inFlight = undefined;
if (current.again) {
current.again = false;
current.nextAt = 0;
}
});
return current.inFlight;
},
};
}

View File

@ -1,27 +0,0 @@
import { createGateway } from './server.mjs';
// Fail closed: only an explicit development deployment may use plain HTTP and the local Theia default.
const production = process.env.WF_DEPLOYMENT_MODE !== 'development';
const publicUrl = process.env.WF_IDE_PUBLIC_URL ?? 'http://127.0.0.1:4400';
if (production && !publicUrl.startsWith('https://')) throw new Error('Production gateway requires HTTPS public URL');
const gateway = createGateway({
publicUrl,
apiOrigin: process.env.WF_API_URL ?? 'http://127.0.0.1:4000',
tenantId: process.env.WF_TENANT_ID ?? 'demo',
serviceToken: process.env.WF_WORKSPACE_GATEWAY_TOKEN,
allowedUpstreamOrigins: (process.env.WF_IDE_ALLOWED_UPSTREAM_ORIGINS ?? (production ? '' : 'http://127.0.0.1:4300'))
.split(',')
.filter(Boolean),
allowedServiceNamespace: process.env.WF_IDE_ALLOWED_SERVICE_NAMESPACE,
allowedCollaborationOrigins: (process.env.WF_COLLABORATION_ALLOWED_UPSTREAM_ORIGINS ?? '').split(',').filter(Boolean),
});
gateway.server.listen(
Number(process.env.WF_IDE_GATEWAY_PORT ?? 4400),
process.env.WF_IDE_GATEWAY_HOST ?? '127.0.0.1',
() => console.log(`Workspace gateway listening at ${publicUrl}`),
);
for (const signal of ['SIGTERM', 'SIGINT'])
process.on(signal, async () => {
await gateway.close();
process.exit(0);
});

View File

@ -1,36 +0,0 @@
{
"name": "@wishforge/ide-gateway",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@wishforge/ide-gateway",
"version": "0.1.0",
"dependencies": {
"ws": "8.21.0"
}
},
"node_modules/ws": {
"version": "8.21.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}

View File

@ -1,13 +0,0 @@
{
"name": "@wishforge/ide-gateway",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"start": "node main.mjs",
"test": "node --test test/*.test.mjs"
},
"dependencies": {
"ws": "8.21.0"
}
}

View File

@ -1,483 +0,0 @@
import http from 'node:http';
import https from 'node:https';
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { WebSocket, WebSocketServer } from 'ws';
import { createGitCredentials, CREDENTIAL_PATH } from './git-credentials.mjs';
const COOKIE = 'WF_IDE_SESSION';
const ID = /^[a-zA-Z0-9_-]{1,128}$/;
// 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);
this.status = status;
}
}
const random = () => randomBytes(32).toString('base64url');
/** The commit identity the control plane derived from the person's sign-in, if it is usable. */
function validAuthor(author) {
const text = value =>
typeof value === 'string' && value.length > 0 && value.length <= 200 && !/[\u0000-\u001f\u007f<>]/.test(value);
return author && text(author.name) && text(author.email) && /^[^\s@]+@[^\s@]+$/.test(author.email)
? { name: author.name, email: author.email }
: undefined;
}
export function createGateway(config) {
const publicUrl = new URL(config.publicUrl);
if (
!['http:', 'https:'].includes(publicUrl.protocol) ||
publicUrl.pathname !== '/' ||
publicUrl.search ||
publicUrl.username ||
publicUrl.password
)
throw new Error('publicUrl must be an HTTP(S) origin');
if (!ID.test(config.tenantId) || !config.serviceToken)
throw new Error('A fixed tenantId and gateway serviceToken are required');
const upstreamOrigins = new Set(config.allowedUpstreamOrigins);
const collaborationOrigins = new Set(config.allowedCollaborationOrigins ?? []);
const serviceNamespace = config.allowedServiceNamespace;
if (serviceNamespace && (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(serviceNamespace) || serviceNamespace.length > 63))
throw new Error('Invalid service namespace');
if (!upstreamOrigins.size && !serviceNamespace) throw new Error('Explicit upstream allowlist required');
const fetchImpl = config.fetchImpl ?? fetch;
const sessions = new Map();
const launches = new Map();
// Theia's own process token is distinct from the caller's authentication.
// Keep it server-side, scoped to an allowed upstream, never in browser cookies.
const upstreamTokens = new Map();
const sockets = new Set();
const workspaceSockets = new Map();
const rawSockets = new Set();
// A session ends after 15 idle minutes; while it is used it is renewed, for at most 12 hours.
const sessionTtl = Math.min(config.sessionTtlMs ?? 900000, 900000);
const sessionMaxMs = Math.min(config.sessionMaxMs ?? 12 * 3600_000, 12 * 3600_000);
const pollMs = Math.min(config.reauthorizeMs ?? 1000, 1000);
// An upstream that stays silent this long is given up. OCT holds each login poll open for 30 s
// before answering, so collaboration requests get longer than that.
const upstreamTimeoutMs = config.upstreamTimeoutMs ?? 30_000;
const collaborationTimeoutMs = Math.max(upstreamTimeoutMs, 65_000);
const now = () => Date.now();
const purge = () => {
for (const map of [sessions, launches])
for (const [key, value] of map) if (value.expiresAt <= now()) map.delete(key);
};
const timer = setInterval(purge, 5000);
timer.unref();
// One person cannot use up the capacity everyone shares: beyond these, their own oldest
// launch code or session ends. An ended session's open connections close at their next check.
const LAUNCHES_PER_USER = 20,
SESSIONS_PER_USER = 20;
const keepNewest = (map, userId, limit, age) => {
const own = [...map].filter(([, value]) => value.userId === userId).sort(([, a], [, b]) => age(a) - age(b));
for (const [key, value] of own.slice(0, Math.max(0, own.length - limit))) {
value.expiresAt = 0;
map.delete(key);
}
};
const wss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024, perMessageDeflate: false });
const gitCredentials = createGitCredentials({
apiOrigin: config.apiOrigin,
tenantId: config.tenantId,
serviceToken: config.serviceToken,
fetchImpl,
now,
connectionToken: href => upstreamTokens.get(href),
setConnectionToken: (href, token) => upstreamTokens.set(href, token),
});
/**
* `credential` is the user's access token for a new session, or the user id an established
* session was granted to: the API still checks the current membership and role each time.
*/
async function authorize(workspaceId, credential, operation, collaboration = false) {
const { userToken, userId } = credential;
if (!ID.test(workspaceId) || (!userToken && !userId) || (userToken?.length ?? 0) > 16384)
throw new HttpError(401, 'Authentication required');
let response;
try {
response = await fetchImpl(
`${config.apiOrigin}/internal/workspaces/${encodeURIComponent(workspaceId)}/authorize`,
{
method: 'POST',
headers: {
authorization: `Bearer ${config.serviceToken}`,
'content-type': 'application/json',
'X-WishForge-Tenant': config.tenantId,
},
body: JSON.stringify(userId ? { userId, operation } : { userToken, operation }),
signal: AbortSignal.timeout(3000),
redirect: 'error',
},
);
} catch {
throw new HttpError(503, 'Workspace authorization unavailable');
}
if (!response.ok)
throw new HttpError([401, 403, 404].includes(response.status) ? response.status : 503, 'Workspace access denied');
const payload = await response.json();
const grant = payload.data ?? payload;
if (
grant.tenantId !== config.tenantId ||
grant.workspaceId !== workspaceId ||
!grant.projectId ||
!EDIT_ROLES.has(grant.role)
)
throw new HttpError(403, 'Workspace grant mismatch');
let upstream;
try {
upstream = new URL(collaboration ? grant.collaborationUpstreamUrl : grant.upstreamUrl);
} catch {
throw new HttpError(502, 'Invalid workspace upstream');
}
const origins = collaboration ? collaborationOrigins : upstreamOrigins;
const serviceAllowed =
serviceNamespace &&
upstream.protocol === 'http:' &&
upstream.port === (collaboration ? '8100' : '3000') &&
new RegExp(`^wf-ide-[a-f0-9]{24}\\.${serviceNamespace}\\.svc(?:\\.cluster\\.local)?$`).test(upstream.hostname);
if (
(!origins.has(upstream.origin) && !serviceAllowed) ||
!['http:', 'https:'].includes(upstream.protocol) ||
upstream.username ||
upstream.password ||
upstream.search ||
upstream.hash
)
throw new HttpError(502, 'Workspace upstream is not permitted');
return { ...grant, upstream };
}
/** Checks access for a request or socket, and renews a cookie session that is in use. */
async function authorizeSession(session, workspaceId, operation, collaboration) {
const grant = await authorize(
workspaceId,
session.userId ? { userId: session.userId } : { userToken: session.userToken },
operation,
collaboration,
);
if (session.createdAt !== undefined) {
if (session.userId === undefined) session.userId = grant.userId;
else if (session.userId !== grant.userId) throw new HttpError(403, 'Workspace grant mismatch');
session.expiresAt = Math.min(now() + sessionTtl, session.createdAt + sessionMaxMs);
}
return grant;
}
function tokenFor(req, workspaceId) {
const authorization = req.headers.authorization;
if (authorization?.startsWith('Bearer '))
return { userToken: authorization.slice(7), expiresAt: Number.MAX_SAFE_INTEGER };
const opaque = req.headers.cookie
?.split(';')
.map(v => v.trim())
.find(v => v.startsWith(`${COOKIE}=`))
?.slice(COOKIE.length + 1);
const session = opaque && sessions.get(opaque);
if (!session || session.expiresAt <= now() || session.workspaceId !== workspaceId)
throw new HttpError(401, 'Launch an authenticated IDE session');
return session;
}
function originCheck(req, required = false) {
if ((required && !req.headers.origin) || (req.headers.origin && req.headers.origin !== publicUrl.origin))
throw new HttpError(403, 'Origin not allowed');
}
function route(req) {
const parsed = new URL(req.url, publicUrl);
const match = parsed.pathname.match(/^\/workspaces\/([a-zA-Z0-9_-]{1,128})(\/.*)?$/);
if (!match) throw new HttpError(404, 'Workspace route not found');
let suffix = match[2] ?? '/';
// Only the gateway itself delivers Git credentials to the workspace backend. Theia's
// Express routes ignore case, so this check does too.
const internal = suffix.toLowerCase();
if (
internal === CREDENTIAL_PATH ||
internal === '/wishforge-internal' ||
internal.startsWith('/wishforge-internal/')
)
throw new HttpError(404, 'Workspace route not found');
const collaboration = suffix === '/collaboration' || suffix.startsWith('/collaboration/');
if (collaboration) suffix = suffix.slice('/collaboration'.length) || '/';
// Multiplexed Theia services need edit permission. Callers cannot downgrade
// this to preview by supplying a query parameter or header.
const operation = collaboration
? 'edit'
: /\/terminals?(?:\/|$)/.test(suffix)
? 'terminal'
: /\/debug(?:\/|$)/.test(suffix)
? 'debug'
: 'edit';
return { workspaceId: match[1], suffix, query: parsed.search, operation, collaboration };
}
function targetFor(grant, routing) {
const target = new URL(grant.upstream);
target.pathname = `${target.pathname.replace(/\/$/, '')}${routing.suffix}`;
target.search = routing.query;
return target;
}
function proxyHeaders(req, target, grant) {
const headers = { ...req.headers };
for (const key of Object.keys(headers))
if (
[
'authorization',
'cookie',
'connection',
'upgrade',
'proxy-authorization',
'proxy-authenticate',
'te',
'trailer',
'transfer-encoding',
].includes(key) ||
key.startsWith('x-forwarded-') ||
key.startsWith('x-wishforge-') ||
key.startsWith('sec-websocket-')
)
delete headers[key];
headers.host = target.host;
headers.origin = target.origin;
headers['x-forwarded-host'] = publicUrl.host;
headers['x-forwarded-proto'] = publicUrl.protocol.slice(0, -1);
headers['x-wishforge-tenant'] = grant.tenantId;
headers['x-wishforge-workspace'] = grant.workspaceId;
const token = upstreamTokens.get(grant.upstream.href);
if (token) headers.cookie = `theia-connection-token=${token}`;
return headers;
}
function fail(res, error) {
if (res.headersSent) {
res.destroy();
return;
}
res.writeHead(error.status ?? 500, {
'content-type': 'application/json',
'cache-control': 'no-store',
'referrer-policy': 'no-referrer',
});
res.end(JSON.stringify({ error: error.status ? error.message : 'Gateway error' }));
}
async function readJson(req) {
let body = '';
for await (const chunk of req) {
body += chunk;
if (body.length > 2048) throw new HttpError(413, 'Request too large');
}
try {
return JSON.parse(body);
} catch {
throw new HttpError(400, 'Invalid JSON');
}
}
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, publicUrl);
if (url.pathname === '/healthz' && req.method === 'GET') {
res.writeHead(200);
res.end('ok');
return;
}
// 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))
throw new HttpError(401, 'Service authentication required');
const body = await readJson(req);
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' });
res.end(
JSON.stringify({
workspaceId: body.workspaceId,
known: true,
gatewayConnections: workspaceSockets.get(body.workspaceId)?.size ?? 0,
}),
);
return;
}
if (url.pathname === '/launch' && req.method === 'POST') {
originCheck(req);
const userToken = req.headers.authorization?.startsWith('Bearer ')
? req.headers.authorization.slice(7)
: undefined;
const body = await readJson(req);
if (!body || Object.keys(body).some(key => key !== 'workspaceId') || !ID.test(body.workspaceId ?? ''))
throw new HttpError(400, 'workspaceId is required');
const { userId } = await authorize(body.workspaceId, { userToken }, 'edit');
purge();
keepNewest(launches, userId, LAUNCHES_PER_USER - 1, launch => launch.expiresAt);
if (launches.size >= 1000 || sessions.size >= 1000) throw new HttpError(429, 'Session capacity reached');
const code = random();
launches.set(code, { workspaceId: body.workspaceId, userToken, userId, expiresAt: now() + 30000 });
res.writeHead(200, {
'content-type': 'application/json',
'cache-control': 'no-store',
'referrer-policy': 'no-referrer',
});
res.end(
JSON.stringify({ launchUrl: `${publicUrl.origin}/session?code=${encodeURIComponent(code)}`, expiresIn: 30 }),
);
return;
}
if (url.pathname === '/session' && req.method === 'GET') {
const code = url.searchParams.get('code');
const launch = launches.get(code);
launches.delete(code);
if (!launch || launch.expiresAt <= now()) throw new HttpError(401, 'Launch code is invalid or expired');
const grant = await authorize(launch.workspaceId, { userToken: launch.userToken }, 'edit');
if (typeof grant.userId !== 'string' || !grant.userId) throw new HttpError(403, 'Workspace grant mismatch');
const opaque = random();
// The token was just checked; the session keeps only the person it was granted to.
const session = {
workspaceId: launch.workspaceId,
userId: grant.userId,
author: validAuthor(grant.author),
createdAt: now(),
expiresAt: now() + sessionTtl,
};
sessions.set(opaque, session);
keepNewest(sessions, session.userId, SESSIONS_PER_USER, value => value.createdAt);
void gitCredentials.opened(session, grant.upstream);
res.writeHead(303, {
location: `/workspaces/${launch.workspaceId}/`,
'set-cookie': `${COOKIE}=${opaque}; HttpOnly; SameSite=Strict; Path=/workspaces/${launch.workspaceId}/; Max-Age=${Math.floor(sessionMaxMs / 1000)}${publicUrl.protocol === 'https:' ? '; Secure' : ''}`,
'cache-control': 'no-store',
'referrer-policy': 'no-referrer',
});
res.end();
return;
}
originCheck(req);
const routing = route(req);
const session = tokenFor(req, routing.workspaceId);
const grant = await authorizeSession(session, routing.workspaceId, routing.operation, routing.collaboration);
const target = targetFor(grant, routing);
const proxy = (target.protocol === 'https:' ? https : http).request(
target,
{ method: req.method, headers: proxyHeaders(req, target, grant) },
upstream => {
const headers = { ...upstream.headers, 'referrer-policy': 'no-referrer', 'cache-control': 'no-store' };
for (const cookie of upstream.headers['set-cookie'] ?? []) {
const token = /^theia-connection-token=([^;\s]{1,512})(?:;|$)/.exec(cookie)?.[1];
if (token) upstreamTokens.set(grant.upstream.href, token);
}
delete headers['set-cookie'];
if (headers.location) {
const location = new URL(headers.location, target);
if (location.origin === target.origin)
headers.location = `/workspaces/${routing.workspaceId}${routing.collaboration ? '/collaboration' : ''}${location.pathname}${location.search}${location.hash}`;
}
res.writeHead(upstream.statusCode ?? 502, headers);
upstream.pipe(res);
},
);
proxy.on('error', () => fail(res, new HttpError(502, 'Workspace upstream unavailable')));
proxy.setTimeout(routing.collaboration ? collaborationTimeoutMs : upstreamTimeoutMs, () => proxy.destroy());
req.on('aborted', () => proxy.destroy());
res.on('close', () => proxy.destroy());
req.pipe(proxy);
} catch (error) {
fail(res, error);
}
});
server.on('connection', socket => {
rawSockets.add(socket);
socket.once('close', () => rawSockets.delete(socket));
});
server.on('upgrade', async (req, socket, head) => {
socket.on('error', () => {});
try {
originCheck(req, !req.headers.authorization);
const routing = route(req);
const session = tokenFor(req, routing.workspaceId);
const grant = await authorizeSession(session, routing.workspaceId, routing.operation, routing.collaboration);
const target = targetFor(grant, routing);
target.protocol = target.protocol === 'https:' ? 'wss:' : 'ws:';
const protocols = req.headers['sec-websocket-protocol']
?.split(',')
.map(p => p.trim())
.filter(Boolean);
const upstream = new WebSocket(target, protocols, {
headers: proxyHeaders(req, grant.upstream, grant),
maxPayload: 16 * 1024 * 1024,
handshakeTimeout: 5000,
perMessageDeflate: false,
});
let accepted = false;
upstream.once('error', () => {
if (!accepted) socket.destroy();
});
socket.once('close', () => {
if (!accepted) upstream.terminate();
});
upstream.once('open', () =>
wss.handleUpgrade(req, socket, head, client => {
accepted = true;
sockets.add(client);
const workspaceSet = workspaceSockets.get(routing.workspaceId) ?? new Set();
workspaceSockets.set(routing.workspaceId, workspaceSet);
workspaceSet.add(client);
const close = () => {
clearInterval(poll);
sockets.delete(client);
workspaceSet.delete(client);
if (!workspaceSet.size) workspaceSockets.delete(routing.workspaceId);
client.terminate();
upstream.terminate();
};
client.on('message', (data, binary) => {
if (upstream.readyState === WebSocket.OPEN) upstream.send(data, { binary });
});
upstream.on('message', (data, binary) => {
if (client.readyState === WebSocket.OPEN) client.send(data, { binary });
});
if (!routing.collaboration) void gitCredentials.due(session, grant.upstream);
client.on('close', close);
upstream.on('close', close);
client.on('error', close);
upstream.on('error', close);
let checking = false;
const poll = setInterval(async () => {
if (checking) return;
checking = true;
try {
if (session.expiresAt <= now()) throw new Error('Session expired');
const fresh = await authorizeSession(
session,
routing.workspaceId,
routing.operation,
routing.collaboration,
);
if (fresh.upstream.href !== grant.upstream.href) throw new Error('Workspace moved');
if (!routing.collaboration) void gitCredentials.due(session, fresh.upstream);
} catch {
close();
} finally {
checking = false;
}
}, pollMs);
poll.unref();
}),
);
} catch (error) {
socket.end(`HTTP/1.1 ${error.status ?? 500} Access Denied\r\nConnection: close\r\n\r\n`);
}
});
server.on('close', () => {
clearInterval(timer);
for (const client of sockets) client.terminate();
wss.close();
});
return {
server,
close: async () => {
for (const client of sockets) client.terminate();
for (const socket of rawSockets) socket.destroy();
await new Promise(resolve => server.close(resolve));
},
sessionCount: () => sessions.size,
};
}

View File

@ -1,215 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Readable } from 'node:stream';
import { createGateway } from '../server.mjs';
// These drive the gateway's request handler directly with a fake fetch, so they also run where
// opening sockets is not permitted. gateway.test.mjs covers proxying over real connections.
const publicUrl = 'http://gateway.test:4400';
const apiOrigin = 'http://api.test:4000';
const upstreamUrl = 'http://theia.test:3000/';
function fakeFetch(options = {}) {
const state = { calls: [], deliveries: [], connectionToken: 'connection-token-1', rejectDelivery: 0 };
const json = (value, status = 200) =>
new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } });
state.fetch = async (input, init = {}) => {
const url = String(input);
const body = init.body ? JSON.parse(init.body) : undefined;
state.calls.push({ url, method: init.method ?? 'GET', headers: init.headers ?? {}, body });
if (url === `${apiOrigin}/internal/workspaces/w1/authorize`)
return json({
data: {
tenantId: 'tenant-a',
projectId: 'p1',
workspaceId: 'w1',
// The launch presents a person's token; later checks name the person it was granted to.
userId: body.userToken ? (options.userFor?.(body.userToken) ?? 'authenticated-user') : body.userId,
role: 'developer',
upstreamUrl,
...(body.userToken ? { author: { name: 'Ada Lovelace', email: 'ada@example.com' } } : {}),
},
});
if (url === `${apiOrigin}/internal/workspaces/w1/git-credential`) {
if (options.unsupported) return json({ error: 'WORKSPACE_REPOSITORY_UNSUPPORTED' }, 409);
return json({
data: {
projectId: 'p1',
projectName: 'Todo App',
repositoryUrl: 'https://git.test/git/tenant-a/p1.git',
branch: 'main',
token: 'payload.signature',
expiresAt: new Date(Date.now() + 900_000).toISOString(),
},
});
}
if (url === upstreamUrl)
return new Response('<html></html>', {
headers: { 'set-cookie': `theia-connection-token=${state.connectionToken}; HttpOnly; SameSite=Strict; Path=/` },
});
if (url === `${upstreamUrl}wishforge-internal/git-credential`) {
if (state.rejectDelivery > 0 || init.headers.cookie !== `theia-connection-token=${state.connectionToken}`) {
state.rejectDelivery -= 1;
return new Response('', { status: 403 });
}
state.deliveries.push({ cookie: init.headers.cookie, body });
return json({ status: 'cloning' });
}
throw new Error(`Unexpected fetch ${url}`);
};
return state;
}
function send(gateway, { method = 'GET', url, headers = {}, body }) {
const req = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]);
Object.assign(req, { method, url, headers: { host: 'gateway.test:4400', ...headers } });
return new Promise(resolve => {
const res = {
headersSent: false,
writeHead(status, responseHeaders = {}) {
this.status = status;
this.headers = responseHeaders;
this.headersSent = true;
return this;
},
end(chunk) {
resolve({ status: this.status, headers: this.headers, body: chunk ? String(chunk) : '' });
},
destroy() {
resolve({ status: 0, headers: {}, body: '' });
},
on() {
return this;
},
};
gateway.server.emit('request', req, res);
});
}
async function eventually(check) {
for (let i = 0; i < 100; i++) {
if (check()) return;
await new Promise(resolve => setTimeout(resolve, 5));
}
assert.fail('condition was not reached');
}
function setup(t, options) {
const state = fakeFetch(options);
const gateway = createGateway({
publicUrl,
apiOrigin,
tenantId: 'tenant-a',
serviceToken: 'gateway-secret',
allowedUpstreamOrigins: [new URL(upstreamUrl).origin],
fetchImpl: state.fetch,
});
t.after(() => gateway.close());
return { gateway, state };
}
async function launch(gateway, token = 'user-token') {
const response = await send(gateway, {
method: 'POST',
url: '/launch',
headers: { origin: publicUrl, authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: { workspaceId: 'w1' },
});
assert.equal(response.status, 200, response.body);
return new URL(JSON.parse(response.body).launchUrl).searchParams.get('code');
}
const redeem = (gateway, code) => send(gateway, { url: `/session?code=${encodeURIComponent(code)}` });
async function openSession(gateway, token) {
const session = await redeem(gateway, await launch(gateway, token));
assert.equal(session.status, 303, session.body);
return session.headers['set-cookie'].split(';')[0];
}
test('launching presents the person’s token, and the session keeps only who it was granted to', async t => {
const { gateway, state } = setup(t);
await openSession(gateway);
const checks = state.calls.filter(call => call.url.endsWith('/authorize'));
assert.deepEqual(
checks.map(call => call.body),
[
{ userToken: 'user-token', operation: 'edit' },
{ userToken: 'user-token', operation: 'edit' },
],
);
assert.equal(checks[0].headers.authorization, 'Bearer gateway-secret');
});
test('a new session delivers a fresh repository credential and its author to the workspace', async t => {
const { gateway, state } = setup(t);
await openSession(gateway);
await eventually(() => state.deliveries.length === 1);
const minted = state.calls.find(call => call.url.endsWith('/git-credential'));
assert.deepEqual(minted.body, { userId: 'authenticated-user' });
assert.equal(minted.headers['X-WishForge-Tenant'], 'tenant-a');
const [delivery] = state.deliveries;
assert.equal(delivery.cookie, 'theia-connection-token=connection-token-1');
assert.deepEqual(delivery.body, {
projectId: 'p1',
projectName: 'Todo App',
repositoryUrl: 'https://git.test/git/tenant-a/p1.git',
branch: 'main',
token: 'payload.signature',
expiresAt: delivery.body.expiresAt,
author: { name: 'Ada Lovelace', email: 'ada@example.com' },
});
});
test('a restarted workspace gets the delivery after the gateway fetches its new connection token', async t => {
const { gateway, state } = setup(t);
state.rejectDelivery = 1;
await openSession(gateway);
await eventually(() => state.deliveries.length === 1);
assert.equal(state.calls.filter(call => call.url === upstreamUrl).length, 2);
});
test('people cannot reach the credential endpoint of the workspace through the gateway', async t => {
const { gateway, state } = setup(t);
const cookie = await openSession(gateway);
await eventually(() => state.deliveries.length === 1);
const before = state.calls.length;
for (const path of [
'/workspaces/w1/wishforge-internal/git-credential',
'/workspaces/w1/wishforge-internal/other',
'/workspaces/w1/wishforge-internal',
// Theia's Express routes match regardless of case.
'/workspaces/w1/Wishforge-Internal/git-credential',
'/workspaces/w1/WISHFORGE-INTERNAL/GIT-CREDENTIAL',
]) {
const response = await send(gateway, { method: 'POST', url: path, headers: { origin: publicUrl, cookie } });
assert.equal(response.status, 404);
}
assert.equal(state.calls.length, before);
});
test('a project without a platform repository is not delivered anything', async t => {
const { gateway, state } = setup(t, { unsupported: true });
await openSession(gateway);
await eventually(() => state.calls.some(call => call.url.endsWith('/git-credential')));
await new Promise(resolve => setTimeout(resolve, 20));
assert.equal(state.deliveries.length, 0);
assert.equal(
state.calls.some(call => call.url.startsWith(upstreamUrl)),
false,
);
});
test('one person cannot use up the capacity everyone shares; their own oldest codes and sessions end', async t => {
const { gateway } = setup(t, { userFor: token => (token === 'other-token' ? 'other-user' : 'authenticated-user') });
const codes = [];
for (let i = 0; i < 21; i++) codes.push(await launch(gateway));
assert.equal((await redeem(gateway, codes[0])).status, 401);
const cookies = [];
for (let i = 0; i < 21; i++) cookies.push(await openSession(gateway));
assert.equal(gateway.sessionCount(), 20);
const page = cookie => send(gateway, { url: '/workspaces/w1/', headers: { origin: publicUrl, cookie } });
assert.equal((await page(cookies[0])).status, 401);
// Someone else still gets in.
await openSession(gateway, 'other-token');
assert.equal(gateway.sessionCount(), 21);
});

View File

@ -1,307 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { once } from 'node:events';
import { WebSocket, WebSocketServer } from 'ws';
import { createGateway } from '../server.mjs';
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 = {}) {
const state = { revoked: false, role: 'developer', calls: [], credentialRequests: [], receivedHeaders: undefined };
const upstream = http.createServer(async (req, res) => {
state.receivedHeaders = req.headers;
// Like OCT's login poll, which answers only after holding the request open.
if (state.delayMs && (req.url === '/slow' || req.url.startsWith('/api/login/poll/')))
await new Promise(resolve => setTimeout(resolve, state.delayMs));
if (state.connectionToken) {
res.setHeader('set-cookie', `theia-connection-token=${state.connectionToken}; HttpOnly; SameSite=Strict; Path=/`);
if (req.url === '/protected' && req.headers.cookie !== `theia-connection-token=${state.connectionToken}`) {
res.writeHead(403);
res.end();
return;
}
}
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ path: req.url }));
});
const websocket = new WebSocketServer({ server: upstream });
websocket.on('connection', socket => socket.on('message', (data, binary) => socket.send(data, { binary })));
const upstreamUrl = await listen(upstream);
state.upstreamUrl = upstreamUrl;
state.collaborationUpstreamUrl = upstreamUrl;
const auth = http.createServer(async (req, res) => {
let raw = '';
for await (const part of req) raw += part;
const body = JSON.parse(raw);
// Repository credentials are covered by gateway-handler.test.mjs; this project has none,
// so the gateway never contacts Theia on its own here.
if (req.url.endsWith('/git-credential')) {
state.credentialRequests.push(body);
res.writeHead(409);
res.end();
return;
}
state.calls.push({ path: req.url, headers: req.headers, body });
// A new session presents the user's token; an established one names the granted user.
if (state.revoked || (body.userToken !== 'user-token' && body.userId !== 'authenticated-user')) {
res.writeHead(403);
res.end();
return;
}
res.writeHead(200, { 'content-type': 'application/json' });
res.end(
JSON.stringify({
data: {
tenantId: 'tenant-a',
projectId: 'p1',
workspaceId: 'w1',
userId: 'authenticated-user',
role: state.role,
upstreamUrl: state.upstreamUrl,
collaborationUpstreamUrl: state.collaborationUpstreamUrl,
},
}),
);
});
const apiOrigin = await listen(auth);
// Reserve a local port, then bind the gateway with its actual public origin.
const reservation = http.createServer();
const publicUrl = await listen(reservation);
await new Promise(r => reservation.close(r));
const gateway = createGateway({
publicUrl,
apiOrigin,
tenantId: 'tenant-a',
serviceToken: 'gateway-secret',
allowedUpstreamOrigins: [upstreamUrl],
allowedCollaborationOrigins: [upstreamUrl],
reauthorizeMs: 50,
...options,
});
gateway.server.listen(Number(new URL(publicUrl).port), '127.0.0.1');
await once(gateway.server, 'listening');
t.after(async () => {
await gateway.close();
for (const socket of websocket.clients) socket.terminate();
websocket.close();
await Promise.all([new Promise(r => upstream.close(r)), new Promise(r => auth.close(r))]);
});
const requestLaunch = () =>
fetch(`${publicUrl}/launch`, {
method: 'POST',
headers: { authorization: 'Bearer user-token', 'content-type': 'application/json' },
body: JSON.stringify({ workspaceId: 'w1' }),
});
async function session() {
const response = await requestLaunch();
assert.equal(response.status, 200);
const { launchUrl } = await response.json();
assert.ok(!launchUrl.includes('user-token'));
const exchanged = await fetch(launchUrl, { redirect: 'manual' });
assert.equal(exchanged.status, 303);
return { launchUrl, exchanged, cookie: exchanged.headers.get('set-cookie').split(';')[0] };
}
return { state, publicUrl, requestLaunch, session };
}
test('gives up on a silent Theia upstream but waits out an OCT login poll', async t => {
const f = await fixture(t, { upstreamTimeoutMs: 100 });
const s = await f.session();
f.state.delayMs = 400;
const headers = { cookie: s.cookie, origin: f.publicUrl };
assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/slow`, { headers })).status, 502);
const poll = await fetch(`${f.publicUrl}/workspaces/w1/collaboration/api/login/poll/token-1`, {
method: 'POST',
headers,
});
assert.equal(poll.status, 200);
assert.deepEqual(await poll.json(), { path: '/api/login/poll/token-1' });
});
test('requires authentication, exchanges a one-time code, and never forwards bearer/cookie', async t => {
const f = await fixture(t);
assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/`)).status, 401);
const s = await f.session();
assert.match(s.exchanged.headers.get('set-cookie'), /HttpOnly/);
assert.match(s.exchanged.headers.get('set-cookie'), /SameSite=Strict/);
assert.equal(s.exchanged.headers.get('referrer-policy'), 'no-referrer');
assert.equal((await fetch(s.launchUrl, { redirect: 'manual' })).status, 401);
const response = await fetch(`${f.publicUrl}/workspaces/w1/file?name=test`, { headers: { cookie: s.cookie } });
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { path: '/file?name=test' });
assert.equal(f.state.receivedHeaders.authorization, undefined);
assert.equal(f.state.receivedHeaders.cookie, undefined);
assert.equal(f.state.receivedHeaders['x-wishforge-tenant'], 'tenant-a');
assert.ok(
f.state.calls.every(
c => c.headers.authorization === 'Bearer gateway-secret' && c.headers['x-wishforge-tenant'] === 'tenant-a',
),
);
assert.equal((await fetch(`${f.publicUrl}/workspaces/w2/`, { headers: { cookie: s.cookie } })).status, 401);
});
test('viewer cannot obtain edit access and caller cannot choose an upstream or downgrade operation', async t => {
const f = await fixture(t);
f.state.role = 'viewer';
assert.equal((await f.requestLaunch()).status, 403);
f.state.role = 'developer';
f.state.upstreamUrl = 'http://169.254.169.254/';
assert.equal((await f.requestLaunch()).status, 502);
const malformed = await fetch(`${f.publicUrl}/launch`, {
method: 'POST',
headers: { authorization: 'Bearer user-token', 'content-type': 'application/json' },
body: JSON.stringify({ workspaceId: 'w1', upstreamUrl: 'http://evil.invalid' }),
});
assert.equal(malformed.status, 400);
await fetch(`${f.publicUrl}/workspaces/w1/?operation=preview`, { headers: { authorization: 'Bearer user-token' } });
assert.equal(f.state.calls.at(-1).body.operation, 'edit');
});
test('HTTP rechecks revocation and rejects cross-origin cookie requests', async t => {
const f = await fixture(t);
const s = await f.session();
assert.equal(
(
await fetch(`${f.publicUrl}/workspaces/w1/`, {
headers: { cookie: s.cookie, origin: 'https://attacker.invalid' },
})
).status,
403,
);
f.state.revoked = true;
assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/`, { headers: { cookie: s.cookie } })).status, 403);
});
test('preserves the upstream Theia process token server-side without forwarding client cookies', async t => {
const f = await fixture(t);
f.state.connectionToken = 'server-only-process-token';
const s = await f.session();
const first = await fetch(`${f.publicUrl}/workspaces/w1/`, { headers: { cookie: `${s.cookie}; unrelated=secret` } });
assert.equal(first.status, 200);
assert.equal(first.headers.get('set-cookie'), null);
const protectedResponse = await fetch(`${f.publicUrl}/workspaces/w1/protected`, {
headers: { cookie: `${s.cookie}; theia-connection-token=attacker-value` },
});
assert.equal(protectedResponse.status, 200);
assert.equal(f.state.receivedHeaders.cookie, 'theia-connection-token=server-only-process-token');
});
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-tenant': 'tenant-b', 'x-wishforge-user': 'attacker' },
});
assert.equal(response.status, 200);
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);
});
test('WebSocket traffic is authenticated and a revoked member is disconnected', { timeout: 5000 }, async t => {
const f = await fixture(t);
const s = await f.session();
const ws = new WebSocket(`${f.publicUrl.replace('http:', 'ws:')}/workspaces/w1/services`, {
origin: f.publicUrl,
headers: { cookie: s.cookie },
});
await once(ws, 'open');
ws.send('editor-frame');
const [frame] = await once(ws, 'message');
assert.equal(frame.toString(), 'editor-frame');
const closed = once(ws, 'close');
f.state.revoked = true;
await closed;
assert.ok(f.state.calls.length >= 4);
});
test(
'an IDE in use outlives the idle timeout, rechecking the granted user rather than their token',
{ timeout: 5000 },
async t => {
const f = await fixture(t, { sessionTtlMs: 300 });
const s = await f.session();
const ws = new WebSocket(`${f.publicUrl.replace('http:', 'ws:')}/workspaces/w1/services`, {
origin: f.publicUrl,
headers: { cookie: s.cookie },
});
await once(ws, 'open');
// Longer than the idle timeout: the open socket's periodic checks keep renewing the session.
await new Promise(resolve => setTimeout(resolve, 800));
ws.send('still-working');
const [frame] = await once(ws, 'message');
assert.equal(frame.toString(), 'still-working');
assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/`, { headers: { cookie: s.cookie } })).status, 200);
const last = f.state.calls.at(-1).body;
assert.equal(last.userId, 'authenticated-user');
assert.equal(last.userToken, undefined);
// Revocation still ends the session.
const closed = once(ws, 'close');
f.state.revoked = true;
await closed;
},
);
test(
'collaboration HTTP/WS stays behind workspace edit authorization and cannot select another upstream',
{ timeout: 5000 },
async t => {
const f = await fixture(t);
const s = await f.session();
const reply = await fetch(`${f.publicUrl}/workspaces/w1/collaboration/api/meta`, {
headers: { cookie: s.cookie, 'x-oct-client': 'test' },
});
assert.equal(reply.status, 200);
assert.deepEqual(await reply.json(), { path: '/api/meta' });
assert.equal(f.state.calls.at(-1).body.operation, 'edit');
assert.equal(f.state.receivedHeaders['x-oct-client'], 'test');
const ws = new WebSocket(`${f.publicUrl.replace('http:', 'ws:')}/workspaces/w1/collaboration/socket.io/`, {
origin: f.publicUrl,
headers: { cookie: s.cookie },
});
await once(ws, 'open');
ws.send('room-frame');
const [frame] = await once(ws, 'message');
assert.equal(frame.toString(), 'room-frame');
const closed = once(ws, 'close');
f.state.revoked = true;
await closed;
f.state.revoked = false;
f.state.collaborationUpstreamUrl = 'http://169.254.169.254/';
assert.equal(
(await fetch(`${f.publicUrl}/workspaces/w1/collaboration/api/meta`, { headers: { cookie: s.cookie } })).status,
502,
);
},
);
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 ${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(), { 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,
headers: { cookie: session.cookie },
});
await once(ws, 'open');
response = await inspect();
assert.equal((await response.json()).gatewayConnections, 1);
ws.close();
await once(ws, 'close');
response = await inspect();
assert.equal((await response.json()).gatewayConnections, 0);
});

12978
apps/ide/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,69 +0,0 @@
{
"name": "@wishforge/ide",
"version": "0.1.0",
"private": true,
"engines": {
"node": ">=22.14.0 <27"
},
"scripts": {
"build": "theia build --mode development",
"build:production": "theia build --mode production",
"start": "node scripts/start.mjs",
"test": "node --test gateway/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"
},
"dependencies": {
"@theia/core": "1.76.0",
"@theia/editor": "1.76.0",
"@theia/filesystem": "1.76.0",
"@theia/workspace": "1.76.0",
"@theia/navigator": "1.76.0",
"@theia/preferences": "1.76.0",
"@theia/messages": "1.76.0",
"@theia/terminal": "1.76.0",
"@theia/process": "1.76.0",
"@theia/monaco": "1.76.0",
"@theia/scm": "1.76.0",
"@theia/debug": "1.76.0",
"@theia/markers": "1.76.0",
"@theia/search-in-workspace": "1.76.0",
"@theia/outline-view": "1.76.0",
"@theia/callhierarchy": "1.76.0",
"@theia/typehierarchy": "1.76.0",
"@theia/file-search": "1.76.0",
"@theia/mini-browser": "1.76.0",
"@theia/plugin-ext": "1.76.0",
"@theia/plugin-ext-vscode": "1.76.0",
"@theia/vsx-registry": "1.76.0",
"@theia/collaboration": "1.76.0",
"@theia/editor-preview": "1.76.0",
"@wishforge/ide-policy": "file:./policy"
},
"devDependencies": {
"@theia/cli": "1.76.0"
},
"theia": {
"target": "browser",
"frontend": {
"config": {
"applicationName": "WishForge IDE",
"defaultTheme": "dark",
"defaultIconTheme": "theia-file-icons",
"applicationVersion": "0.1.0",
"preferences": {
"telemetry.telemetryLevel": "off"
}
}
},
"backend": {
"config": {
"frontendConnectionTimeout": 0
}
}
},
"theiaPlugins": {
"vscode-builtin-extensions": "https://github.com/eclipse-theia/vscode-builtin-extensions/releases/download/1.108.2/vscode-builtin-extensions-1.108.2.tar.gz"
}
}

View File

@ -1,27 +0,0 @@
# IDE 策略扩展(`@wishforge/ide-policy`)
随 IDE 一起构建的 Theia 1.76 前后端扩展,做三件事:
1. **扩展白名单**(FR-H5):后端替换 Theia 的插件服务与部署器。安装、卸载、启用、停用一律返回 `EXTENSIONS_MANAGED_BY_ADMIN`;启动时只加载 `WF_IDE_MANAGED_PLUGINS_DIR` 中、列在 `managed-plugins.lock.json`(以及 `scripts/python-debugger.lock.json`)里的扩展,并逐个核对扩展 ID、版本与目录内容摘要。符号链接与特殊文件被拒绝,目录未配置时后端拒绝启动插件部署。前端在用户尝试安装扩展时说明扩展由管理员通过镜像构建统一管理。
2. **按工作区隔离的协作**(FR-H3):替换 `@theia/collaboration` 的前端贡献,只有当 `WF_COLLABORATION_GATEWAY_URL` 指向当前已认证工作区的网关协作路由时才注册房间命令与状态栏入口,否则协作保持关闭,不会退回公共 OCT 服务。OCT 令牌按实例保存,不复用其他工作区的令牌。协作连接的地址计算在 `../collaboration/client-factory.cjs` 中。
3. **项目仓库**(FR-H2):后端提供 `POST /wishforge-internal/git-credential`,接收网关投递的仓库令牌(见 [gateway/README.md](../gateway/README.md))。
- **访问控制**:要求 Theia 的连接令牌,这个令牌只有网关持有。
- **校验**:请求必须严格符合格式,仓库地址必须与工作区配置一致。provisioner 设置 `WISHFORGE_GIT_REMOTE` 时只接受这一个仓库;本地共享的 Theia 设置 `WISHFORGE_GIT_ORIGIN`,接受这个 Git 服务上属于所投递项目的仓库。
- **令牌存放**:写入 `WISHFORGE_GIT_CREDENTIAL_DIR` 下的 `<项目>.gitconfig`(权限 0600,内容是 `http.<仓库>.extraHeader` 与提交身份),克隆通过 `include.path` 引用它。令牌不进入命令行、仓库文件或 `.git/config`;Kubernetes 中这个目录是内存卷。
- **克隆**:工作区中还没有该仓库的克隆时,把项目克隆到以项目命名的文件夹。同名文件夹已被占用时在名称后加上项目 ID 的前 8 位,两者都被占用时不克隆,从不覆盖已有文件。之后的投递只刷新令牌,项目改名后仍沿用原来的克隆。
- **工作分支**:克隆后切换到 `ide/work`(远端已有这个分支时跟踪它,否则从目标分支创建),并设置 `push.default=current` 与 `push.autoSetupRemote=true`,这样不带参数的 `git push` 就会发布这个分支。令牌只能推送 `ide/` 开头的分支。
- **身份覆盖**:用户自己设置的 `git config user.name` / `user.email` 优先于平台给的身份。
IDE 与 Agent 之间只通过 Git commit 交接,扩展不提供保存屏障、草稿恢复或调试控制租约。
## 测试
```bash
node --test apps/ide/policy/test/*.test.cjs
```
测试覆盖插件安装接口被拒绝、白名单内容摘要校验与符号链接拒绝,以及用真实 Git 验证仓库的克隆、令牌刷新、提交身份、工作分支的发布与继续、不覆盖已有文件夹和拒绝其他仓库。需要先安装 IDE 依赖(`npm run ide:install`);`npm run test:ide` 会一并运行。
## 边界
Theia 后端与用户终端以同一个系统用户运行,扩展的限制可以被同一工作区中的恶意终端绕过;它约束的是正常使用路径,不是同一工作区内协作者之间的隔离。工作区之间的隔离依赖每个工作区独立的 Kata Pod 与网关。

View File

@ -1,12 +0,0 @@
const { ContainerModule } = require('@theia/core/shared/inversify');
const { BackendApplicationContribution } = require('@theia/core/lib/node/backend-application');
const { GitCredentialEndpoint } = require('./git-credential-endpoint.cjs');
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).
require('./plugin-install-policy.cjs').bindManagedPlugins(rebind);
// The project's repository is cloned and kept authorized while the IDE is open (see git-workspace.cjs).
bind(GitCredentialEndpoint).toSelf().inSingletonScope();
bind(BackendApplicationContribution).toService(GitCredentialEndpoint);
});

View File

@ -1,59 +0,0 @@
const { ContainerModule, injectable } = require('@theia/core/shared/inversify');
const {
CollaborationFrontendContribution,
} = require('@theia/collaboration/lib/browser/collaboration-frontend-contribution');
const { CollaborationWorkspaceService } = require('@theia/collaboration/lib/browser/collaboration-workspace-service');
const { FrontendApplicationConfigProvider } = require('@theia/core/lib/browser/frontend-application-config-provider');
const { ConnectionProvider, SocketIoTransport } = require('open-collaboration-protocol');
const { io } = require('socket.io-client');
const { collaborationBase, createPrefixConnectionProvider } = require('../collaboration/client-factory.cjs');
Object.defineProperty(exports, '__esModule', { value: true });
// Register room commands only for this workspace's authenticated gateway route.
// An absent/mismatched URL keeps collaboration disabled with no public fallback.
class ScopedCollaborationContribution extends CollaborationFrontendContribution {
async scopedUrl() {
const url = await this.getCollaborationServerUrl();
return collaborationBase(url, window.location.href).href;
}
init() {
this.scopedUrl()
.then(() => this.setStatusBarEntryDefault())
.catch(() => {});
}
registerCommands(commands) {
this.scopedUrl()
.then(() => super.registerCommands(commands))
.catch(() => {});
}
async createConnectionProvider() {
const url = await this.scopedUrl();
return createPrefixConnectionProvider(
{ ConnectionProvider, SocketIoTransport, io },
{
url,
browserLocation: window.location.href,
client: FrontendApplicationConfigProvider.get().applicationName,
fetch: window.fetch.bind(window),
authenticationHandler: (token, metadata) => this.handleAuth(url, token, metadata),
// OCT tokens are instance-local; never reuse a different workspace token
// from the upstream global localStorage key.
userToken: undefined,
},
);
}
}
injectable()(ScopedCollaborationContribution);
// Every backend already belongs to one provisioned project. A guest's virtual
// collaboration URI must not overwrite the backend-wide default for other tabs.
class DedicatedWorkspaceService extends CollaborationWorkspaceService {
isRemoteSession() {
return true;
}
}
injectable()(DedicatedWorkspaceService);
module.exports.default = new ContainerModule((_bind, _unbind, _isBound, rebind) => {
require('./plugin-install-frontend.cjs').bindManagedExtensionNotice(_bind);
rebind(CollaborationWorkspaceService).to(DedicatedWorkspaceService).inSingletonScope();
rebind(CollaborationFrontendContribution).to(ScopedCollaborationContribution).inSingletonScope();
});

View File

@ -1,43 +0,0 @@
'use strict';
const { decorate, inject, injectable } = require('@theia/core/shared/inversify');
const express = require('@theia/core/shared/express');
const { HttpConnectionValidator } = require('@theia/core/lib/node');
const {
CREDENTIAL_PATH,
GitWorkspaceError,
createGitWorkspace,
readGitWorkspaceConfig,
} = require('./git-workspace.cjs');
/**
* Receives the repository credential from the workspace gateway. Theia's connection token,
* which only the gateway holds, is required; the gateway refuses to forward this path for people.
*/
class GitCredentialEndpoint {
configure(app) {
const config = readGitWorkspaceConfig(process.env);
if (!config) return;
const workspace = createGitWorkspace(config);
app.post(
CREDENTIAL_PATH,
(req, res, next) => this.connectionValidator.validateRequest(req, res, next),
express.json({ limit: '16kb' }),
async (req, res) => {
try {
const { status, directory } = await workspace.apply(req.body);
res.status(200).json({ status, directory });
} catch (error) {
const known = error instanceof GitWorkspaceError;
if (!known || error.code !== 'INVALID_GIT_CREDENTIAL')
console.error(`WishForge Git workspace update failed: ${error.message}`);
res
.status(known && error.code === 'INVALID_GIT_CREDENTIAL' ? 400 : 500)
.json({ error: known ? error.code : 'GIT_WORKSPACE_FAILED' });
}
},
);
}
}
decorate(inject(HttpConnectionValidator), GitCredentialEndpoint.prototype, 'connectionValidator');
decorate(injectable(), GitCredentialEndpoint);
module.exports = { GitCredentialEndpoint };

View File

@ -1,241 +0,0 @@
'use strict';
// Brings the project's repository into the IDE workspace. While someone has the workspace open,
// the gateway delivers a short-lived repository token (see gateway/git-credentials.mjs); it is
// written to a Git config file outside the repository that the clone includes, so nothing secret
// lands in the repository or its .git/config. The first delivery clones the project into a folder
// named after it and switches to the ide/work branch: the token may push ide/ branches only, and
// a wish starting from such a branch verifies and merges it into the target branch.
const { spawn } = require('node:child_process');
const fs = require('node:fs/promises');
const path = require('node:path');
const CREDENTIAL_PATH = '/wishforge-internal/git-credential';
const WORK_BRANCH = 'ide/work';
const ID = /^[A-Za-z0-9_-]{1,128}$/;
const TOKEN = /^[A-Za-z0-9_-]{1,4096}\.[A-Za-z0-9_-]{1,512}$/;
const PLATFORM_REPOSITORY = /^\/git\/[A-Za-z0-9][A-Za-z0-9_-]{0,100}\/([A-Za-z0-9][A-Za-z0-9_-]{0,100})\.git$/;
class GitWorkspaceError extends Error {
constructor(code, message) {
super(message);
this.code = code;
}
}
const invalid = message => new GitWorkspaceError('INVALID_GIT_CREDENTIAL', message);
function branchName(value) {
if (
typeof value !== 'string' ||
!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/.test(value) ||
/\.\.|\/\/|\/\.|@\{/.test(value) ||
/(?:\/|\.|\.lock)$/.test(value)
)
throw invalid('Invalid branch');
return value;
}
function personText(value) {
return typeof value === 'string' && value.length > 0 && value.length <= 200 && !/[\u0000-\u001f\u007f<>]/.test(value);
}
/** The workspace's Git settings; without them the credential endpoint stays off. */
function readGitWorkspaceConfig(env) {
const root = env.WISHFORGE_WORKSPACE_PATH;
const credentialDir = env.WISHFORGE_GIT_CREDENTIAL_DIR;
if (!root || !credentialDir) return undefined;
// A workspace of its own accepts exactly its project's repository; the one local Theia
// shared by every project accepts any repository of the platform Git service it is given.
if (env.WISHFORGE_GIT_REMOTE) return { root, credentialDir, remote: new URL(env.WISHFORGE_GIT_REMOTE).href };
if (env.WISHFORGE_GIT_ORIGIN) return { root, credentialDir, origin: new URL(env.WISHFORGE_GIT_ORIGIN).origin };
return undefined;
}
function validate(payload, config) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw invalid('Expected an object');
const fields = ['projectId', 'projectName', 'repositoryUrl', 'branch', 'token', 'expiresAt', 'author'];
if (Object.keys(payload).some(key => !fields.includes(key))) throw invalid('Unexpected field');
if (!ID.test(payload.projectId ?? '')) throw invalid('Invalid project');
if (
payload.projectName !== undefined &&
(typeof payload.projectName !== 'string' || payload.projectName.length > 200)
)
throw invalid('Invalid project name');
let repository;
try {
repository = new URL(payload.repositoryUrl);
} catch {
throw invalid('Invalid repository');
}
if (config.remote) {
if (repository.href !== config.remote) throw invalid('This workspace belongs to another repository');
} else if (
repository.origin !== config.origin ||
repository.username ||
repository.password ||
repository.search ||
repository.hash ||
PLATFORM_REPOSITORY.exec(repository.pathname)?.[1] !== payload.projectId
)
throw invalid('Repository is not the project’s platform repository');
if (!TOKEN.test(payload.token ?? '')) throw invalid('Invalid token');
if (!Number.isFinite(Date.parse(payload.expiresAt))) throw invalid('Invalid expiry');
const author = payload.author;
if (
author !== undefined &&
(!author ||
typeof author !== 'object' ||
Object.keys(author).some(key => !['name', 'email'].includes(key)) ||
!personText(author.name) ||
!personText(author.email) ||
!/^[^\s@]+@[^\s@]+$/.test(author.email))
)
throw invalid('Invalid author');
return {
projectId: payload.projectId,
projectName: payload.projectName,
repositoryUrl: repository.href,
branch: branchName(payload.branch),
token: payload.token,
author: author && { name: author.name, email: author.email },
};
}
/** Quotes a value or subsection name for a Git config file. */
const quote = value => `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
function runGit(args, { cwd, include } = {}) {
return new Promise((resolve, reject) => {
const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never' };
// Passing the credential file by path keeps the token out of the command line.
if (include)
Object.assign(env, { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'include.path', GIT_CONFIG_VALUE_0: include });
const child = spawn('git', args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
child.stdout.on('data', chunk => {
stdout = (stdout + chunk).slice(-65536);
});
child.stderr.on('data', chunk => {
stderr = (stderr + chunk).slice(-2048);
});
const timer = setTimeout(() => child.kill('SIGKILL'), 10 * 60_000);
child.on('error', () => {
clearTimeout(timer);
reject(new GitWorkspaceError('GIT_UNAVAILABLE', 'Git is not installed in this workspace'));
});
child.on('close', code => {
clearTimeout(timer);
if (code === 0) resolve(stdout.trim());
else reject(new GitWorkspaceError('GIT_FAILED', `git ${args[0]} exited ${code}: ${stderr.trim()}`));
});
});
}
async function exists(file) {
return fs.lstat(file).then(
() => true,
error => {
if (error.code === 'ENOENT') return false;
throw error;
},
);
}
function createGitWorkspace(config, { git = runGit } = {}) {
const clones = new Map();
const authors = new Map();
async function writeCredential(file, input) {
// A delivery without an author (for example after the gateway restarted) keeps the last one.
const author = input.author ?? authors.get(input.projectId);
if (author) authors.set(input.projectId, author);
const lines = [
'# Written by WishForge while the IDE is open; the token expires on its own.',
`[http ${quote(input.repositoryUrl)}]`,
`\textraHeader = ${quote(`Authorization: Bearer ${input.token}`)}`,
...(author ? ['[user]', `\tname = ${quote(author.name)}`, `\temail = ${quote(author.email)}`] : []),
];
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
await fs.writeFile(temporary, `${lines.join('\n')}\n`, { mode: 0o600 });
await fs.rename(temporary, file);
}
async function origin(directory) {
if (!(await exists(path.join(directory, '.git')))) return undefined;
return git(['config', '--get', 'remote.origin.url'], { cwd: directory }).catch(() => undefined);
}
/** An earlier clone keeps working even after the project was renamed or the folder moved. */
async function findClone(repositoryUrl) {
if ((await origin(config.root)) === repositoryUrl) return config.root;
const entries = await fs.readdir(config.root, { withFileTypes: true }).catch(() => []);
for (const entry of entries.slice(0, 200))
if (entry.isDirectory() && !entry.name.startsWith('.')) {
const directory = path.join(config.root, entry.name);
if ((await origin(directory)) === repositoryUrl) return directory;
}
return undefined;
}
async function freeDirectory(input) {
const name =
(input.projectName ?? '')
.normalize('NFKC')
.toLowerCase()
.replace(/[^\p{L}\p{N}._-]+/gu, '-')
.replace(/^[-.]+|[-.]+$/g, '')
.slice(0, 60) || 'project';
for (const candidate of [name, `${name}-${input.projectId.slice(0, 8)}`]) {
const directory = path.join(config.root, candidate);
if (!(await exists(directory))) return directory;
}
return undefined;
}
/** People commit on ide/work; a plain `git push` publishes it, `git pull origin <target>` updates it. */
async function startWorkBranch(directory) {
const published = await git(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${WORK_BRANCH}`], {
cwd: directory,
}).catch(() => '');
await git(
published
? ['switch', '--create', WORK_BRANCH, '--track', `origin/${WORK_BRANCH}`]
: ['switch', '--create', WORK_BRANCH],
{ cwd: directory },
);
await git(['config', '--local', 'push.default', 'current'], { cwd: directory });
await git(['config', '--local', 'push.autoSetupRemote', 'true'], { cwd: directory });
}
async function includeCredential(directory, file) {
const included = await git(['config', '--local', '--get-all', 'include.path'], { cwd: directory }).catch(() => '');
if (!included.split('\n').includes(file))
await git(['config', '--local', '--add', 'include.path', file], { cwd: directory });
}
return {
/** Stores the delivered credential and clones the repository when the workspace lacks it. */
async apply(payload) {
const input = validate(payload, config);
const file = path.join(config.credentialDir, `${input.projectId}.gitconfig`);
await writeCredential(file, input);
const pending = clones.get(input.repositoryUrl);
if (pending) return { status: 'cloning', directory: pending.directory, cloning: pending.done };
const existing = await findClone(input.repositoryUrl);
if (existing) {
await includeCredential(existing, file);
return { status: 'ready', directory: existing };
}
const directory = await freeDirectory(input);
if (!directory) return { status: 'conflict' };
const done = (async () => {
await git(['clone', '--origin', 'origin', '--branch', input.branch, '--', input.repositoryUrl, directory], {
include: file,
});
await includeCredential(directory, file);
await startWorkBranch(directory);
})().finally(() => clones.delete(input.repositoryUrl));
clones.set(input.repositoryUrl, { directory, done });
// A failed clone is retried with the next delivery.
done.catch(error => console.error(`WishForge could not clone the project: ${error.message}`));
return { status: 'cloning', directory, cloning: done };
},
};
}
module.exports = { CREDENTIAL_PATH, WORK_BRANCH, GitWorkspaceError, readGitWorkspaceConfig, createGitWorkspace };

View File

@ -1,108 +0,0 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { createHash } = require('node:crypto');
const { execFileSync } = require('node:child_process');
const sha256 = value => createHash('sha256').update(value).digest('hex');
const managedError = () =>
new Error('EXTENSIONS_MANAGED_BY_ADMIN: Extensions are installed and updated only through the operator image build.');
function treeDigest(root) {
const files = [];
function visit(directory, prefix = '') {
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
const name = path.join(directory, entry.name);
if (entry.isSymbolicLink()) throw new Error('EXTENSION_SYMLINK_REJECTED');
if (entry.isDirectory()) visit(name, relative);
else if (entry.isFile()) files.push([relative, sha256(fs.readFileSync(name))]);
else throw new Error('EXTENSION_SPECIAL_FILE_REJECTED');
}
}
visit(root);
files.sort((left, right) => (left[0] < right[0] ? -1 : left[0] > right[0] ? 1 : 0));
return sha256(files.map(([name, digest]) => `${name}\0${digest}\n`).join(''));
}
function assertIdentity(directory, expected) {
if (fs.lstatSync(directory).isSymbolicLink()) throw new Error('EXTENSION_SYMLINK_REJECTED');
const manifest = JSON.parse(fs.readFileSync(path.join(directory, 'extension/package.json'), 'utf8'));
if (`${manifest.publisher}.${manifest.name}` !== expected.id || manifest.version !== expected.version)
throw new Error('EXTENSION_ID_VERSION_REJECTED');
}
function validateManagedPlugins(
root,
{
catalog = require('./managed-plugins.lock.json'),
pythonLock = require('../scripts/python-debugger.lock.json'),
platform = `${process.platform}-${process.arch}`,
} = {},
) {
if (fs.lstatSync(root).isSymbolicLink()) throw new Error('EXTENSION_SYMLINK_REJECTED');
const extensions = [...catalog.plugins];
if (pythonLock)
extensions.push(
{ directory: pythonLock.id, id: pythonLock.id, version: pythonLock.version },
{
directory: pythonLock.pythonDependency.id,
id: pythonLock.pythonDependency.id,
version: pythonLock.pythonDependency.version,
},
{
directory: pythonLock.languageServer.id,
id: pythonLock.languageServer.id,
version: pythonLock.languageServer.version,
},
);
const allowed = new Set(extensions.map(extension => extension.directory));
const found = fs.readdirSync(root).filter(name => !name.startsWith('.'));
if (found.length !== allowed.size || found.some(name => !allowed.has(name)))
throw new Error('EXTENSION_ALLOWLIST_MISMATCH');
for (const extension of extensions) {
const directory = path.join(root, extension.directory);
assertIdentity(directory, extension);
if (extension.sha256 && treeDigest(directory) !== extension.sha256)
throw new Error(`EXTENSION_DIGEST_REJECTED: ${extension.id}`);
}
if (pythonLock) {
const expected = pythonLock.platforms[platform];
if (!expected) throw new Error('EXTENSION_PLATFORM_NOT_PINNED');
const dependency = pythonLock.pythonDependency;
const packages = [
{ id: pythonLock.id, file: `${pythonLock.id}-${pythonLock.version}@${platform}.vsix`, sha256: expected },
{ id: dependency.id, file: `${dependency.id}-${dependency.version}.vsix`, sha256: dependency.sha256 },
{
id: pythonLock.languageServer.id,
file: `${pythonLock.languageServer.id}-${pythonLock.languageServer.version}.vsix`,
sha256: pythonLock.languageServer.sha256,
},
];
// Compare the unpacked bytes against the checksum-pinned official VSIX files,
// never against a manifest self-generated from the current runtime directory.
execFileSync(
'python3',
[
'-c',
`
import hashlib,json,pathlib,stat,sys,zipfile
root=pathlib.Path(sys.argv[1])
for package in json.loads(sys.argv[2]):
archive=root/'.downloads'/package['file']
if archive.is_symlink() or archive.stat().st_size>67108864: raise ValueError('EXTENSION_ARCHIVE_REJECTED')
if hashlib.sha256(archive.read_bytes()).hexdigest()!=package['sha256']: raise ValueError('EXTENSION_ARCHIVE_DIGEST_REJECTED')
target=root/package['id']
with zipfile.ZipFile(archive) as z:
expected={i.filename:hashlib.sha256(z.read(i)).hexdigest() for i in z.infolist() if not i.is_dir()}
actual={}
for p in target.rglob('*'):
if p.is_symlink(): raise ValueError('EXTENSION_SYMLINK_REJECTED')
if p.is_file(): actual[p.relative_to(target).as_posix()]=hashlib.sha256(p.read_bytes()).hexdigest()
if actual!=expected: raise ValueError('EXTENSION_CONTENT_DIGEST_REJECTED: '+package['id'])
`,
root,
JSON.stringify(packages),
],
{ timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'] },
);
}
return extensions;
}
module.exports = { treeDigest, assertIdentity, validateManagedPlugins, managedError };

View File

@ -1,561 +0,0 @@
{
"schemaVersion": 1,
"source": {
"url": "https://github.com/eclipse-theia/vscode-builtin-extensions/releases/download/1.108.2/vscode-builtin-extensions-1.108.2.tar.gz",
"sha256": "05a20cf3e671c8d328b04d9ce72b25688b0e762e4a3f5592f31a21ee38280367"
},
"plugins": [
{
"directory": "ms-vscode.js-debug",
"id": "ms-vscode.js-debug",
"version": "1.105.0",
"sha256": "47b974a9cf4f2d030efbbd00d21ad7c4c8b406dade21652aa95686427fd96a76"
},
{
"directory": "ms-vscode.js-debug-companion",
"id": "ms-vscode.js-debug-companion",
"version": "1.1.3",
"sha256": "3d567809ed536ad5ead4732f83b4433113f6bba0d56ee57ba80cdb7fc90e87b6"
},
{
"directory": "ms-vscode.vscode-js-profile-table",
"id": "ms-vscode.vscode-js-profile-table",
"version": "1.0.10",
"sha256": "6db1bdc953c0c055480eca4a867059ea36a71b2f28eb22631abe5d807d9d992a"
},
{
"directory": "vscode.bat",
"id": "vscode.bat",
"version": "1.108.2",
"sha256": "049a52d9bd4934464eabe1318ccc164f734d0e080e39df9c02f54c32d6a1480a"
},
{
"directory": "vscode.builtin-notebook-renderers",
"id": "vscode.builtin-notebook-renderers",
"version": "1.108.2",
"sha256": "28198f48d05ba683c4a1ce490377543f4c89fd65e44c18da0a1b9f3faa010f2b"
},
{
"directory": "vscode.clojure",
"id": "vscode.clojure",
"version": "1.108.2",
"sha256": "5ba5793cf1797861aa58410079cc1a542784053bc9b038afd758db5336319dd5"
},
{
"directory": "vscode.coffeescript",
"id": "vscode.coffeescript",
"version": "1.108.2",
"sha256": "ef1d7e0149349a73550c7359c5d9186c406c941dba3771230ce82f9e8cd709cf"
},
{
"directory": "vscode.configuration-editing",
"id": "vscode.configuration-editing",
"version": "1.108.2",
"sha256": "d5c82fa70a7ac06e53d55dd0ad943be42b7206da918887582701b63dd318ced9"
},
{
"directory": "vscode.cpp",
"id": "vscode.cpp",
"version": "1.108.2",
"sha256": "e890a89907e8bed3718962f7f56fea93cd639eb8d3f87078b24c4fc26767d30a"
},
{
"directory": "vscode.csharp",
"id": "vscode.csharp",
"version": "1.108.2",
"sha256": "f70330001f788a62592b5d5d9639fdabddbffa616ece32fb3deed47edd15d926"
},
{
"directory": "vscode.css",
"id": "vscode.css",
"version": "1.108.2",
"sha256": "e16cc9e6ba83af3b8b2dac7a58326d8d49dccf11d0ce4ddc450c3a529bc43b12"
},
{
"directory": "vscode.css-language-features",
"id": "vscode.css-language-features",
"version": "1.108.2",
"sha256": "9c61d13d105e4fa35b6d430e3afde416e47e5691ca72cff84226a54a8a7a2925"
},
{
"directory": "vscode.dart",
"id": "vscode.dart",
"version": "1.108.2",
"sha256": "65594c659e862f0eaebbcc1b68652ebe70e6c9d1a90340d078eb1697c1166913"
},
{
"directory": "vscode.debug-auto-launch",
"id": "vscode.debug-auto-launch",
"version": "1.108.2",
"sha256": "408b192f4c5913b6fc3294ad661dabddea56d7c57ea8bbe10919bc06a9239660"
},
{
"directory": "vscode.debug-server-ready",
"id": "vscode.debug-server-ready",
"version": "1.108.2",
"sha256": "8deb733ffbf4198cef3cbb73d6b5307de9ba6c18d8a4249432d71ba47d06b864"
},
{
"directory": "vscode.diff",
"id": "vscode.diff",
"version": "1.108.2",
"sha256": "ecbdda82e1072bce5d375a4b6d267da041a936c3cabfda3011dddb21e5a48e98"
},
{
"directory": "vscode.docker",
"id": "vscode.docker",
"version": "1.108.2",
"sha256": "2a957acd235c9a5d3580e46389f16cb840a34d3a70f9d66df8c0691bcede878d"
},
{
"directory": "vscode.dotenv",
"id": "vscode.dotenv",
"version": "1.108.2",
"sha256": "eb84848cc43176288f815c554ab03636a5d5472c6314e956041d95b2d7b0bf8f"
},
{
"directory": "vscode.emmet",
"id": "vscode.emmet",
"version": "1.108.2",
"sha256": "b6b5dc5df353e4ecbca48aca599bfe51cdcba7f63b9fb0ef79b8022ac9a4ddf1"
},
{
"directory": "vscode.extension-editing",
"id": "vscode.extension-editing",
"version": "1.108.2",
"sha256": "2885dabf8b502f45a402f500a4bd43b338cc9b64764d758ef250c8b1aad0bcf6"
},
{
"directory": "vscode.fsharp",
"id": "vscode.fsharp",
"version": "1.108.2",
"sha256": "1167d5c4c0bf022aeacf859803d5552071d42cec848684546a68a4ebb99628a1"
},
{
"directory": "vscode.git",
"id": "vscode.git",
"version": "1.108.2",
"sha256": "882cbb7556376f513629ed3fba1711c77b80890cb284646b6391518276609075"
},
{
"directory": "vscode.git-base",
"id": "vscode.git-base",
"version": "1.108.2",
"sha256": "26d3c189c0890b8bff9ec56391cea74f378b815c5aedbd5ec583ca297ae23f55"
},
{
"directory": "vscode.github",
"id": "vscode.github",
"version": "1.108.2",
"sha256": "616a6f2b139be59b00725aa28111512e11f8354d3433f84681a9dee54956f422"
},
{
"directory": "vscode.github-authentication",
"id": "vscode.github-authentication",
"version": "1.108.2",
"sha256": "7f772b6f9241509efba786f4ff9184374740516084b2e3b1c231163f143da208"
},
{
"directory": "vscode.go",
"id": "vscode.go",
"version": "1.108.2",
"sha256": "c848c972ae6d559fbfb10702e3dcf95ad94d16cd0edb2dde45dcc72054efa1e3"
},
{
"directory": "vscode.groovy",
"id": "vscode.groovy",
"version": "1.108.2",
"sha256": "00ca5455163d0ec0dbc5d50fade93f94e2b93f1dc5bce3d22395508e256ec619"
},
{
"directory": "vscode.grunt",
"id": "vscode.grunt",
"version": "1.108.2",
"sha256": "68bc5e71189089032abc187ff97666cc873b1cf6bfecd37a93721e8710633f86"
},
{
"directory": "vscode.gulp",
"id": "vscode.gulp",
"version": "1.108.2",
"sha256": "fd073848831e8d3c148e4daf085e7f54fdc48bfc91a3136f6491df99f99f9c01"
},
{
"directory": "vscode.handlebars",
"id": "vscode.handlebars",
"version": "1.108.2",
"sha256": "c9446c5192f64cb8cd70300577a69961ef83fab430898db36421d07b62660fdf"
},
{
"directory": "vscode.hlsl",
"id": "vscode.hlsl",
"version": "1.108.2",
"sha256": "482db38e94f8505f12458b051793bb3d937c3e2e560e6adeaa31e41609396441"
},
{
"directory": "vscode.html",
"id": "vscode.html",
"version": "1.108.2",
"sha256": "3420b09f3f1fd441dacf842041db14045584dea25b2d3f675453a9ba6fd9b599"
},
{
"directory": "vscode.html-language-features",
"id": "vscode.html-language-features",
"version": "1.108.2",
"sha256": "ccc11f2b9c7ba04f6f9f31c49e16587a165fd4f71a5d8345314d2509393b01bb"
},
{
"directory": "vscode.ini",
"id": "vscode.ini",
"version": "1.108.2",
"sha256": "00f9170d7311b1a75484e63c2ac0abe374934bb38dff5a0c342153f93fc69164"
},
{
"directory": "vscode.ipynb",
"id": "vscode.ipynb",
"version": "1.108.2",
"sha256": "d5be113eeaf2d9735044c5db42983a3f7c9f81b5fc0ce6c7864ff69f15ac5e27"
},
{
"directory": "vscode.jake",
"id": "vscode.jake",
"version": "1.108.2",
"sha256": "9ff40dd4dcbb130f52b4a39cbf630fab468d9d5f1ef91d6b1ac4433ffda55a9c"
},
{
"directory": "vscode.java",
"id": "vscode.java",
"version": "1.108.2",
"sha256": "af9b242d4bfcd33683013f3af4ceddae96324f6a242e9055718a431a157dca75"
},
{
"directory": "vscode.javascript",
"id": "vscode.javascript",
"version": "1.108.2",
"sha256": "9936e0f60e9f6130edb3cc5c1a8727582519c29cb882ea53f8ab2728193695e5"
},
{
"directory": "vscode.json",
"id": "vscode.json",
"version": "1.108.2",
"sha256": "0047b7b7e590fed1fd5a30c7d06d167c9fb23f9d6155a65e9b57a3b9703da68d"
},
{
"directory": "vscode.json-language-features",
"id": "vscode.json-language-features",
"version": "1.108.2",
"sha256": "51971aef66c5af444e04042b6a3d6cebc7e20422d0c2cee4219b775caf567446"
},
{
"directory": "vscode.julia",
"id": "vscode.julia",
"version": "1.108.2",
"sha256": "109bf99c4cbe2e02082d952d72da97984bf90bbfe1c5a53683040a1b98e18c82"
},
{
"directory": "vscode.latex",
"id": "vscode.latex",
"version": "1.108.2",
"sha256": "8e664d4c99645338f2d85d7013270e072a494df4db61be027cfccafab3a1dcb4"
},
{
"directory": "vscode.less",
"id": "vscode.less",
"version": "1.108.2",
"sha256": "10027163ff231ab5ad5b964f87538793dd4f0430ea71a0575ec66514c63dbe6e"
},
{
"directory": "vscode.log",
"id": "vscode.log",
"version": "1.108.2",
"sha256": "f48bcc16c41b1789496341d883141dc1105d458529390299ddd924909c5e31c8"
},
{
"directory": "vscode.lua",
"id": "vscode.lua",
"version": "1.108.2",
"sha256": "2de7c36f55c75a9167f9a58ad17012c6567a87928a5bfdc0a42ea8839c8069c5"
},
{
"directory": "vscode.make",
"id": "vscode.make",
"version": "1.108.2",
"sha256": "a4f6189f96df05bf08e2c6d8fa0e0d5eabe2e1d61056654fc5f8e5581f279937"
},
{
"directory": "vscode.markdown",
"id": "vscode.markdown",
"version": "1.108.2",
"sha256": "d4b364c6e2edad2b1ae50ece5cee20b130aa94efc5f8f8eb1b696b0eda563ba9"
},
{
"directory": "vscode.markdown-language-features",
"id": "vscode.markdown-language-features",
"version": "1.108.2",
"sha256": "ced48a41ed75021d1a4ea5afd7f51c08631f70f04e323d351d7260824083a7a6"
},
{
"directory": "vscode.markdown-math",
"id": "vscode.markdown-math",
"version": "1.108.2",
"sha256": "b58711f19ecca7df14e13979ec675c1bdaa9f3968a6e756ff5c7105105dbb86e"
},
{
"directory": "vscode.media-preview",
"id": "vscode.media-preview",
"version": "1.108.2",
"sha256": "179e0778ac606e254f59018fde83ea9caf5f90e0f99ac0ecc347d5ad66af330c"
},
{
"directory": "vscode.merge-conflict",
"id": "vscode.merge-conflict",
"version": "1.108.2",
"sha256": "a1b347a40c96cccf73a102808b768140bf5d3c1dfeddbfa1dca1da2b7f7f477b"
},
{
"directory": "vscode.mermaid-chat-features",
"id": "vscode.mermaid-chat-features",
"version": "1.108.2",
"sha256": "b6d18d40c0b1e0b2585b99a0488b984d1b30a2a1140206ca34c9557165b78455"
},
{
"directory": "vscode.npm",
"id": "vscode.npm",
"version": "1.108.2",
"sha256": "0f11c99fe30648d7c444361298749d0b8d5ff60472b5a0eabc3904d07397876e"
},
{
"directory": "vscode.objective-c",
"id": "vscode.objective-c",
"version": "1.108.2",
"sha256": "8319b21c30bb8fcb897687991165909e359ec0c075c1d014602f38da9865864a"
},
{
"directory": "vscode.perl",
"id": "vscode.perl",
"version": "1.108.2",
"sha256": "5727730f86da49921388ea8276a1c11bb1438796c02815f980fd5239ebd2e430"
},
{
"directory": "vscode.php",
"id": "vscode.php",
"version": "1.108.2",
"sha256": "70c19b21bc32837872145a0a1e76ee216b51d012321087f4ef7380e289d77715"
},
{
"directory": "vscode.php-language-features",
"id": "vscode.php-language-features",
"version": "1.108.2",
"sha256": "01159d120c597f2663367277c1e9d4f8e9866a88c3c30776d48485d061bbd8ad"
},
{
"directory": "vscode.powershell",
"id": "vscode.powershell",
"version": "1.108.2",
"sha256": "83d8cbf4801aaddee86ddd3c3f61a9fcfde74a1049497c8db4e890598beeffe6"
},
{
"directory": "vscode.prompt",
"id": "vscode.prompt",
"version": "1.108.2",
"sha256": "a0d70ebb1f4189419dbb963e1024e0b3a5e7d977697b32b1d9686a9f315c8fa9"
},
{
"directory": "vscode.pug",
"id": "vscode.pug",
"version": "1.108.2",
"sha256": "288d461d6a7ec29b7ec2f4d11a3065690e9315c719e64cf1baa1dea542d1b57a"
},
{
"directory": "vscode.python",
"id": "vscode.python",
"version": "1.108.2",
"sha256": "8683bf05b9c8ab797d2a75ddf23eee1f979d4272fbbcb5b0b963f62e16ea8f2f"
},
{
"directory": "vscode.r",
"id": "vscode.r",
"version": "1.108.2",
"sha256": "a2f642e8905e67bb73737e457fa079bf76aad644fdaa2f1cdf0fd0ecdcfc73f5"
},
{
"directory": "vscode.razor",
"id": "vscode.razor",
"version": "1.108.2",
"sha256": "6d24d115419c70dd22329d82d5a06b965c8f4c4890543edb11ff0bf4f71fa7bb"
},
{
"directory": "vscode.references-view",
"id": "vscode.references-view",
"version": "1.108.2",
"sha256": "d2bdc0161a107eaa844c6bb2f4c287bb8a1319f7107370ee9f60a3621859e42c"
},
{
"directory": "vscode.restructuredtext",
"id": "vscode.restructuredtext",
"version": "1.108.2",
"sha256": "19a9dbcd2fc1f7ac087dd3f056e4d69ea50aaac43195cb7762513245f39dd089"
},
{
"directory": "vscode.ruby",
"id": "vscode.ruby",
"version": "1.108.2",
"sha256": "958e0bbe7c1cd09da68e7794abd85a99ed8fb0f588d7a3d73bf36b118a842caa"
},
{
"directory": "vscode.rust",
"id": "vscode.rust",
"version": "1.108.2",
"sha256": "bb29d84d161754274f80f605b627cc11de67458b826fa13e0eebf30e12ab979e"
},
{
"directory": "vscode.scss",
"id": "vscode.scss",
"version": "1.108.2",
"sha256": "a66ee14fedc6225c672ddc73fd457034baf90f9fac23b2987d6404c8a937b737"
},
{
"directory": "vscode.search-result",
"id": "vscode.search-result",
"version": "1.108.2",
"sha256": "4f579e97277485d9861554bdedb9cbecf761b37e70be74d5144c66affdc00d7e"
},
{
"directory": "vscode.shaderlab",
"id": "vscode.shaderlab",
"version": "1.108.2",
"sha256": "ce9c866d5f4fff9d3c2e3fd4f5f5a2e0c789be7daf0db88387d74e884d0b29e8"
},
{
"directory": "vscode.shellscript",
"id": "vscode.shellscript",
"version": "1.108.2",
"sha256": "ac6048f34e998b969fda2698583983627b5a957db35270d3d056df7946f7b0f6"
},
{
"directory": "vscode.simple-browser",
"id": "vscode.simple-browser",
"version": "1.108.2",
"sha256": "64a0ad33a16501227125ac2c994b668ba8772b213bb246fa60281b4aaba9a9f9"
},
{
"directory": "vscode.sql",
"id": "vscode.sql",
"version": "1.108.2",
"sha256": "fb9285cd41cff6e70da9a6f7017307be12cbf49abe06627854ea8eb254db1013"
},
{
"directory": "vscode.swift",
"id": "vscode.swift",
"version": "1.108.2",
"sha256": "fc74ef0b507b235e07dd905b82e8efc69824f7f7dfdbbd12d6a5cd7b23bbece1"
},
{
"directory": "vscode.terminal-suggest",
"id": "vscode.terminal-suggest",
"version": "1.108.2",
"sha256": "12b7713afd5028bc3978c652d555ec4737bc4d29d2c236318a60b20c5c7e2d80"
},
{
"directory": "vscode.theme-abyss",
"id": "vscode.theme-abyss",
"version": "1.108.2",
"sha256": "f4f5256d0a95c11442f8b758cae95c22240cc209e45f284ac9afe70b242cf4fa"
},
{
"directory": "vscode.theme-defaults",
"id": "vscode.theme-defaults",
"version": "1.108.2",
"sha256": "220a90a481dd4ffb0587d727ca02122f03d7befc26a6649d709f13e3a50c29f0"
},
{
"directory": "vscode.theme-kimbie-dark",
"id": "vscode.theme-kimbie-dark",
"version": "1.108.2",
"sha256": "eb1cf1a0362f82b6e23f5383cc3b691afb6a0d60d79955aa858263ecfbd797ec"
},
{
"directory": "vscode.theme-monokai",
"id": "vscode.theme-monokai",
"version": "1.108.2",
"sha256": "ba7abbb9ab04ece745aced2269003d65316ee487638308fc0f1a08476a91de83"
},
{
"directory": "vscode.theme-monokai-dimmed",
"id": "vscode.theme-monokai-dimmed",
"version": "1.108.2",
"sha256": "00d5d056d6f3773c5314feaae1adae3c061a8188ba3231961f4a5707176f62e0"
},
{
"directory": "vscode.theme-quietlight",
"id": "vscode.theme-quietlight",
"version": "1.108.2",
"sha256": "f0f018f4de1a3f93de5a9ed40069dc8614d981339273f8bfc244c1f5cad8d2aa"
},
{
"directory": "vscode.theme-red",
"id": "vscode.theme-red",
"version": "1.108.2",
"sha256": "3065330894fdb026a9b6278108be00e5dbc71bfa218575b7b0db6f29f2d3d7be"
},
{
"directory": "vscode.theme-solarized-dark",
"id": "vscode.theme-solarized-dark",
"version": "1.108.2",
"sha256": "ff0b771b8ac188e5025c9d2f79aff66dbb9092cee54fdad5c5ef55493e741576"
},
{
"directory": "vscode.theme-solarized-light",
"id": "vscode.theme-solarized-light",
"version": "1.108.2",
"sha256": "90d275f62c97c6db813f4b8328dfbb6a2416d3ffbe3086f5b6b0c336e0b129d9"
},
{
"directory": "vscode.theme-tomorrow-night-blue",
"id": "vscode.theme-tomorrow-night-blue",
"version": "1.108.2",
"sha256": "ec253677124f41a815d63dfa970f0a25a98bf805d9172c9e539b4ed037320c7e"
},
{
"directory": "vscode.tunnel-forwarding",
"id": "vscode.tunnel-forwarding",
"version": "1.108.2",
"sha256": "dc6f8419f6544455b42afd1b729b50d07705be1ce001007ddc208e2594397fb9"
},
{
"directory": "vscode.typescript",
"id": "vscode.typescript",
"version": "1.108.2",
"sha256": "879b9686a08845f43c2d9f89334f3bf747aaf9de9ea12fb3c3b161bc19e4ea48"
},
{
"directory": "vscode.typescript-language-features",
"id": "vscode.typescript-language-features",
"version": "1.108.2",
"sha256": "819e93858b013f24a6e102a71e8e1922515b310071d11ccbb98a82be6ab99dd9"
},
{
"directory": "vscode.vb",
"id": "vscode.vb",
"version": "1.108.2",
"sha256": "49b14b8e8668434f86fa997e1168a86168f92c237662af6d8b6c0d25790caf30"
},
{
"directory": "vscode.vscode-theme-seti",
"id": "vscode.vscode-theme-seti",
"version": "1.108.2",
"sha256": "e0383c41fedc343b6b2e02ef6ba77e5edac78ce72c06ae45d84fd940f2b8975e"
},
{
"directory": "vscode.xml",
"id": "vscode.xml",
"version": "1.108.2",
"sha256": "4656d86b85078ba1673a36050439013339aa58e855e7695a6ef201e9333d6e6c"
},
{
"directory": "vscode.yaml",
"id": "vscode.yaml",
"version": "1.108.2",
"sha256": "b03408b1cc8cb82c2c1961ea480e6b04d9a054ebc034af71f4d91cb29408aca6"
}
]
}

View File

@ -1,15 +0,0 @@
{
"name": "@wishforge/ide-policy",
"version": "0.1.0",
"private": true,
"theiaExtensions": [
{
"frontend": "frontend.cjs",
"backend": "backend.cjs"
}
],
"peerDependencies": {
"@theia/core": "1.76.0",
"@theia/collaboration": "1.76.0"
}
}

View File

@ -1,41 +0,0 @@
'use strict';
const { injectable, inject } = require('@theia/core/shared/inversify');
const { WidgetManager } = require('@theia/core/lib/browser/widget-manager');
const { FrontendApplicationContribution } = require('@theia/core/lib/browser/frontend-application-contribution');
const React = require('@theia/core/shared/react');
class ManagedExtensionsNotice {
onStart() {
const label = widget => {
if (widget.id !== 'vsx-extensions-view-container') return;
widget.title.label = 'Extensions · 管理员管理';
widget.title.caption = '扩展由管理员固定版本安装。可查看已安装扩展;安装、更新与移除须通过平台镜像发布。';
// ViewContainer restores its title from saved layout/part titles. Put the
// durable notice in the extension search widget as well as the caption.
if (!widget.searchBar || widget.searchBar.wishforgeManagedNotice) return;
const search = widget.searchBar;
search.wishforgeManagedNotice = true;
const render = search.render.bind(search);
search.render = () =>
React.createElement(
'div',
{ style: { width: '100%' } },
React.createElement(
'p',
{ style: { margin: '0 0 8px', fontSize: '12px', lineHeight: '1.6' } },
'扩展由管理员管理。安装与更新须通过平台镜像发布。',
),
render(),
);
search.update();
};
this.widgets.getWidgets('vsx-extensions-view-container').forEach(label);
this.widgets.onDidCreateWidget(({ widget }) => label(widget));
}
}
injectable()(ManagedExtensionsNotice);
inject(WidgetManager)(ManagedExtensionsNotice.prototype, 'widgets');
function bindManagedExtensionNotice(bind) {
bind(ManagedExtensionsNotice).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(ManagedExtensionsNotice);
}
module.exports = { bindManagedExtensionNotice };

View File

@ -1,72 +0,0 @@
'use strict';
const path = require('node:path');
const { injectable } = require('@theia/core/shared/inversify');
const { PluginServer, PluginDeployer, PluginType } = require('@theia/plugin-ext/lib/common/plugin-protocol');
const { PluginServerImpl } = require('@theia/plugin-ext/lib/main/node/plugin-server-impl');
const { PluginDeployerImpl } = require('@theia/plugin-ext/lib/main/node/plugin-deployer-impl');
const { validateManagedPlugins, managedError } = require('./managed-plugins.cjs');
class ManagedPluginServer extends PluginServerImpl {
async install() {
throw managedError();
}
async doInstall() {
throw managedError();
}
async uninstall() {
throw managedError();
}
async enablePlugin() {
throw managedError();
}
async disablePlugin() {
throw managedError();
}
}
injectable()(ManagedPluginServer);
class ManagedPluginDeployer extends PluginDeployerImpl {
async doStart() {
if (!process.env.WF_IDE_MANAGED_PLUGINS_DIR) throw new Error('MANAGED_EXTENSIONS_UNCONFIGURED');
const root = path.resolve(process.env.WF_IDE_MANAGED_PLUGINS_DIR);
const allowed = validateManagedPlugins(root);
await this.initResolvers();
// Do not consult THEIA_PLUGINS, user directories, extension recommendations
// or resolver participants. All system content was verified before resolution.
const entries = await this.resolveAndHandle(`local-dir:${root}`, PluginType.System);
const paths = new Set(allowed.map(extension => path.join(root, extension.directory)));
if (
entries.length !== paths.size ||
entries.some(entry => !paths.has(entry.originalPath()) || entry.type !== PluginType.System)
) {
throw new Error('EXTENSION_DEPLOYMENT_SCOPE_REJECTED');
}
return super.deployPlugins(entries);
}
async deploy() {
throw managedError();
}
async deployMultipleEntries() {
throw managedError();
}
async deployPlugins() {
throw managedError();
}
async uninstall() {
throw managedError();
}
async undeploy() {
throw managedError();
}
async enablePlugin() {
throw managedError();
}
async disablePlugin() {
throw managedError();
}
}
injectable()(ManagedPluginDeployer);
function bindManagedPlugins(rebind) {
rebind(PluginServer).to(ManagedPluginServer).inSingletonScope();
rebind(PluginDeployer).to(ManagedPluginDeployer).inSingletonScope();
}
module.exports = { ManagedPluginServer, ManagedPluginDeployer, bindManagedPlugins };

View File

@ -1,191 +0,0 @@
'use strict';
require('reflect-metadata');
const test = require('node:test');
const assert = require('node:assert/strict');
const { execFileSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { createGitWorkspace, readGitWorkspaceConfig } = require('../git-workspace.cjs');
const git = (cwd, ...args) =>
execFileSync('git', args, {
cwd,
encoding: 'utf8',
env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' },
}).trim();
function fixture(t) {
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'wishforge-git-workspace-'));
t.after(() => fs.rmSync(base, { recursive: true, force: true }));
const source = path.join(base, 'p1.git');
git(base, 'init', '--quiet', '--bare', '--initial-branch=main', source);
const seed = path.join(base, 'seed');
git(base, 'clone', '--quiet', source, seed);
fs.writeFileSync(path.join(seed, 'README.md'), '# Todo\n');
git(seed, 'add', 'README.md');
git(seed, '-c', 'user.name=Seed', '-c', 'user.email=seed@example.com', 'commit', '--quiet', '-m', 'Initial');
git(seed, 'push', '--quiet', 'origin', 'HEAD:main');
const root = path.join(base, 'workspace');
fs.mkdirSync(root);
const config = { root, credentialDir: path.join(base, 'credentials'), remote: `file://${source}` };
const delivery = (overrides = {}) => ({
projectId: 'p1',
projectName: 'Todo App',
repositoryUrl: config.remote,
branch: 'main',
token: 'payload.signature-1',
expiresAt: new Date(Date.now() + 900_000).toISOString(),
author: { name: 'Ada Lovelace', email: 'ada@example.com' },
...overrides,
});
return { base, source, root, config, delivery };
}
test('the first delivery clones the target branch and keeps the token out of the repository', async t => {
const f = fixture(t);
const workspace = createGitWorkspace(f.config);
const result = await workspace.apply(f.delivery());
assert.equal(result.status, 'cloning');
await result.cloning;
const clone = path.join(f.root, 'todo-app');
assert.equal(result.directory, clone);
assert.equal(fs.readFileSync(path.join(clone, 'README.md'), 'utf8'), '# Todo\n');
const credential = path.join(f.config.credentialDir, 'p1.gitconfig');
assert.equal(fs.statSync(credential).mode & 0o777, 0o600);
assert.doesNotMatch(fs.readFileSync(path.join(clone, '.git/config'), 'utf8'), /payload\.signature/);
assert.equal(
git(clone, 'config', `http.${f.config.remote}.extraHeader`),
'Authorization: Bearer payload.signature-1',
);
assert.equal(git(clone, 'config', 'user.name'), 'Ada Lovelace');
assert.equal(git(clone, 'config', 'user.email'), 'ada@example.com');
});
test('later deliveries only refresh the token, even after the project was renamed', async t => {
const f = fixture(t);
const workspace = createGitWorkspace(f.config);
await (
await workspace.apply(f.delivery())
).cloning;
const result = await workspace.apply(
f.delivery({ projectName: 'Renamed', token: 'payload.signature-2', author: undefined }),
);
assert.deepEqual(result, { status: 'ready', directory: path.join(f.root, 'todo-app') });
assert.equal(
git(result.directory, 'config', `http.${f.config.remote}.extraHeader`),
'Authorization: Bearer payload.signature-2',
);
// A delivery without an author keeps the last one.
assert.equal(git(result.directory, 'config', 'user.name'), 'Ada Lovelace');
assert.equal(git(result.directory, 'config', '--get-all', 'include.path').split('\n').length, 1);
});
test('people commit on ide/work, and a plain push publishes it without touching the target branch', async t => {
const f = fixture(t);
const workspace = createGitWorkspace(f.config);
const { directory, cloning } = await workspace.apply(f.delivery());
await cloning;
assert.equal(git(directory, 'branch', '--show-current'), 'ide/work');
const target = git(f.source, 'rev-parse', 'main');
git(directory, 'config', 'user.name', 'Grace Hopper');
fs.writeFileSync(path.join(directory, 'notes.md'), 'edited in the IDE\n');
git(directory, 'add', 'notes.md');
git(directory, 'commit', '--quiet', '-m', 'Edit in the IDE');
git(directory, 'push', '--quiet');
assert.equal(
git(f.source, 'log', '-1', '--format=%an <%ae> %s', 'ide/work'),
'Grace Hopper <ada@example.com> Edit in the IDE',
);
assert.equal(git(f.source, 'rev-parse', 'main'), target);
// A later clone, for example of a recreated workspace, continues the published branch.
fs.rmSync(directory, { recursive: true });
const again = await workspace.apply(f.delivery());
await again.cloning;
assert.equal(git(again.directory, 'rev-parse', 'HEAD'), git(f.source, 'rev-parse', 'ide/work'));
assert.equal(git(again.directory, 'rev-parse', '--abbrev-ref', '@{upstream}'), 'origin/ide/work');
});
test('an existing folder with the project’s name is never overwritten', async t => {
const f = fixture(t);
fs.mkdirSync(path.join(f.root, 'todo-app'));
fs.writeFileSync(path.join(f.root, 'todo-app', 'mine.txt'), 'keep\n');
const workspace = createGitWorkspace(f.config);
const result = await workspace.apply(f.delivery());
await result.cloning;
assert.equal(result.directory, path.join(f.root, 'todo-app-p1'));
assert.equal(fs.readFileSync(path.join(f.root, 'todo-app', 'mine.txt'), 'utf8'), 'keep\n');
fs.mkdirSync(path.join(f.root, 'other'));
fs.rmSync(result.directory, { recursive: true });
fs.mkdirSync(result.directory);
assert.deepEqual(await workspace.apply(f.delivery()), { status: 'conflict' });
});
test('deliveries for another repository or with unexpected content are refused', async t => {
const f = fixture(t);
const workspace = createGitWorkspace(f.config);
for (const payload of [
f.delivery({ repositoryUrl: 'https://git.example/git/tenant/other.git' }),
f.delivery({ branch: '../main' }),
f.delivery({ token: 'not a token' }),
f.delivery({ author: { name: 'Eve <eve@example.com>', email: 'eve@example.com' } }),
{ ...f.delivery(), command: 'rm -rf /' },
])
await assert.rejects(workspace.apply(payload), { code: 'INVALID_GIT_CREDENTIAL' });
assert.deepEqual(fs.readdirSync(f.root), []);
const shared = createGitWorkspace({ ...f.config, remote: undefined, origin: 'http://127.0.0.1:4504' });
await assert.rejects(
shared.apply(f.delivery({ repositoryUrl: 'http://127.0.0.1:4504/git/demo/p2.git' })),
{ code: 'INVALID_GIT_CREDENTIAL' },
'the repository must belong to the delivered project',
);
await assert.rejects(shared.apply(f.delivery({ repositoryUrl: 'http://127.0.0.1:9999/git/demo/p1.git' })), {
code: 'INVALID_GIT_CREDENTIAL',
});
});
test('the endpoint is only configured for a workspace with Git settings', () => {
assert.equal(readGitWorkspaceConfig({ WISHFORGE_WORKSPACE_PATH: '/w' }), undefined);
assert.deepEqual(
readGitWorkspaceConfig({
WISHFORGE_WORKSPACE_PATH: '/w',
WISHFORGE_GIT_CREDENTIAL_DIR: '/run/wishforge/git',
WISHFORGE_GIT_REMOTE: 'https://git.example/git/t/p1.git',
}),
{ root: '/w', credentialDir: '/run/wishforge/git', remote: 'https://git.example/git/t/p1.git' },
);
const { GitCredentialEndpoint } = require('../git-credential-endpoint.cjs');
const routes = [];
const app = { post: (...args) => routes.push(args) };
const keys = [
'WISHFORGE_WORKSPACE_PATH',
'WISHFORGE_GIT_CREDENTIAL_DIR',
'WISHFORGE_GIT_REMOTE',
'WISHFORGE_GIT_ORIGIN',
];
const previous = Object.fromEntries(keys.map(key => [key, process.env[key]]));
try {
delete process.env.WISHFORGE_GIT_REMOTE;
delete process.env.WISHFORGE_GIT_ORIGIN;
new GitCredentialEndpoint().configure(app);
assert.equal(routes.length, 0);
Object.assign(process.env, {
WISHFORGE_WORKSPACE_PATH: '/w',
WISHFORGE_GIT_CREDENTIAL_DIR: '/run/wishforge/git',
WISHFORGE_GIT_ORIGIN: 'http://127.0.0.1:4504',
});
const endpoint = new GitCredentialEndpoint();
let validated = false;
endpoint.connectionValidator = { validateRequest: () => (validated = true) };
endpoint.configure(app);
assert.equal(routes.length, 1);
assert.equal(routes[0][0], '/wishforge-internal/git-credential');
routes[0][1]({}, {}, () => {});
assert.equal(validated, true, 'Theia’s connection token is checked first');
} finally {
for (const key of keys)
if (previous[key] === undefined) delete process.env[key];
else process.env[key] = previous[key];
}
});

View File

@ -1,91 +0,0 @@
'use strict';
require('reflect-metadata');
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 { treeDigest, validateManagedPlugins } = require('../managed-plugins.cjs');
const { ManagedPluginServer, ManagedPluginDeployer } = require('../plugin-install-policy.cjs');
function fixture(t) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wishforge-managed-plugins-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const directory = path.join(root, 'test.approved');
fs.mkdirSync(path.join(directory, 'extension'), { recursive: true });
fs.writeFileSync(
path.join(directory, 'extension/package.json'),
JSON.stringify({ publisher: 'test', name: 'approved', version: '1.0.0' }),
);
fs.writeFileSync(path.join(directory, 'extension/main.js'), 'exports.activate = () => {};\n');
const catalog = {
plugins: [{ directory: 'test.approved', id: 'test.approved', version: '1.0.0', sha256: treeDigest(directory) }],
};
return { root, directory, options: { catalog, pythonLock: null } };
}
test('approved ID/version/content loads while unrelated hidden cache is ignored', t => {
const f = fixture(t);
fs.mkdirSync(path.join(f.root, '.downloads'));
assert.equal(validateManagedPlugins(f.root, f.options).length, 1);
});
test('same ID and version with changed implementation fails digest validation', t => {
const f = fixture(t);
fs.appendFileSync(path.join(f.directory, 'extension/main.js'), 'malicious();');
assert.throws(() => validateManagedPlugins(f.root, f.options), /DIGEST_REJECTED/);
});
test('changed version and additional plugin are refused', t => {
const f = fixture(t);
fs.writeFileSync(
path.join(f.directory, 'extension/package.json'),
JSON.stringify({ publisher: 'test', name: 'approved', version: '2.0.0' }),
);
assert.throws(() => validateManagedPlugins(f.root, f.options), /ID_VERSION_REJECTED/);
fs.mkdirSync(path.join(f.root, 'unapproved.plugin'));
assert.throws(() => validateManagedPlugins(f.root, f.options), /ALLOWLIST_MISMATCH/);
});
test('symlinks cannot substitute plugin code or plugin directories', t => {
const f = fixture(t);
fs.symlinkSync('/tmp', path.join(f.directory, 'escape'));
assert.throws(() => validateManagedPlugins(f.root, f.options), /SYMLINK_REJECTED/);
});
test('actual Theia PluginServer install routes reject registry, VSIX, update and forged system type before calling deployer', async () => {
const server = new ManagedPluginServer();
server.pluginDeployer = new Proxy(
{},
{
get() {
throw new Error('Unsafe deployer reached');
},
},
);
for (const id of [
'vscode:untrusted.extension',
'file:///tmp/plugin.vsix',
'https://example.invalid/plugin.vsix',
'vscode:ms-python.debugpy@2026.6.0',
]) {
await assert.rejects(server.install(id, 0, { ignoreDependencies: true }), /EXTENSIONS_MANAGED_BY_ADMIN/);
}
for (const method of ['doInstall', 'uninstall', 'enablePlugin', 'disablePlugin'])
await assert.rejects(server[method]('test.approved'), /EXTENSIONS_MANAGED_BY_ADMIN/);
});
test('direct deployer mutation paths and bulk/update paths are closed', async () => {
const deployer = new ManagedPluginDeployer();
for (const method of [
'deploy',
'deployMultipleEntries',
'deployPlugins',
'uninstall',
'undeploy',
'enablePlugin',
'disablePlugin',
]) {
await assert.rejects(deployer[method]({ id: 'local-dir:/tmp/evil', type: 0 }), /EXTENSIONS_MANAGED_BY_ADMIN/);
}
});
test('installed plugin reads still reach the normal Theia implementation', async () => {
const server = new ManagedPluginServer();
server.pluginDeployerHandler = { getDeployedPluginIds: () => ['test.approved@1.0.0'] };
assert.deepEqual(await server.getInstalledPlugins(), ['test.approved@1.0.0']);
});

View File

@ -1,43 +0,0 @@
// Operator-only lockfile maintenance. Input must be the exact official release
// archive; this never signs or approves an arbitrary installed runtime directory.
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
const source = {
url: 'https://github.com/eclipse-theia/vscode-builtin-extensions/releases/download/1.108.2/vscode-builtin-extensions-1.108.2.tar.gz',
sha256: '05a20cf3e671c8d328b04d9ce72b25688b0e762e4a3f5592f31a21ee38280367',
};
if (process.argv.length !== 3)
throw new Error('Usage: node scripts/catalog-builtin-plugins.mjs /path/to/vscode-builtin-extensions-1.108.2.tar.gz');
const archive = process.argv[2];
if (
createHash('sha256')
.update(await readFile(archive))
.digest('hex') !== source.sha256
)
throw new Error('BUILTIN_ARCHIVE_DIGEST_REJECTED');
const plugins = JSON.parse(
execFileSync(
'python3',
[
'-c',
`
import hashlib,io,json,pathlib,sys,tarfile,zipfile
plugins=[]
with tarfile.open(sys.argv[1],'r:gz') as tar:
for item in tar.getmembers():
if item.isdir(): continue
if not item.isfile() or not item.name.endswith('.vsix'): raise ValueError('Unexpected release entry')
with zipfile.ZipFile(io.BytesIO(tar.extractfile(item).read())) as z:
manifest=json.loads(z.read('extension/package.json'))
files=sorted((i.filename,hashlib.sha256(z.read(i)).hexdigest()) for i in z.infolist() if not i.is_dir())
digest=hashlib.sha256(''.join(name+'\\0'+sha+'\\n' for name,sha in files).encode()).hexdigest()
plugins.append({'directory':pathlib.PurePosixPath(item.name).stem,'id':manifest['publisher']+'.'+manifest['name'],'version':manifest['version'],'sha256':digest})
print(json.dumps(sorted(plugins,key=lambda p:p['directory'])))
`,
archive,
],
{ encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 },
),
);
console.log(JSON.stringify({ schemaVersion: 1, source, plugins }, null, 2));

View File

@ -1,180 +0,0 @@
import { createHash, randomUUID } from 'node:crypto';
import { execFile } from 'node:child_process';
import { readFile, writeFile, mkdir, rename, rm, stat } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { promisify } from 'node:util';
const lock = JSON.parse(await readFile(new URL('./python-debugger.lock.json', import.meta.url), 'utf8'));
const maxBytes = 64 * 1024 * 1024;
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
const run = promisify(execFile);
export async function installPythonDebugger({
platform = `${process.platform}-${process.arch}`,
archive,
pythonArchive,
pyrightArchive,
directory = fileURLToPath(new URL('../plugins/', import.meta.url)),
fetcher = fetch,
} = {}) {
const expected = lock.platforms[platform];
if (!expected) throw new Error(`Python debugger package is not pinned for ${platform}`);
const filename = `${lock.id}-${lock.version}@${platform}.vsix`;
const dependency = lock.pythonDependency;
const python = await installArchive({
expected: dependency.sha256,
filename: `${dependency.id}-${dependency.version}.vsix`,
id: dependency.id,
version: dependency.version,
url: dependency.url,
archive: pythonArchive,
directory,
fetcher,
});
const debuggerExtension = await installArchive({
expected,
filename,
archive,
directory,
fetcher,
id: lock.id,
version: lock.version,
url: `https://open-vsx.org/api/ms-python/debugpy/${platform}/${lock.version}/file/${filename}`,
});
const languageServer = await installArchive({
expected: lock.languageServer.sha256,
filename: `${lock.languageServer.id}-${lock.languageServer.version}.vsix`,
id: lock.languageServer.id,
version: lock.languageServer.version,
url: lock.languageServer.url,
archive: pyrightArchive,
directory,
fetcher,
});
return { version: lock.version, platform, python, debugger: debuggerExtension, languageServer };
}
async function installArchive({ expected, filename, url, archive, directory, fetcher, id, version }) {
const target = join(directory, '.downloads', filename);
let bytes;
let cached = false;
if (!archive) {
try {
bytes = await readFile(target);
if (sha256(bytes) !== expected) throw new Error(`Cached Python debugger checksum mismatch: ${target}`);
cached = true;
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
}
if (archive) {
if ((await stat(archive)).size > maxBytes) throw new Error('Python debugger archive exceeds 64 MiB');
bytes = await readFile(archive);
} else if (!cached) {
const response = await fetcher(url, { signal: AbortSignal.timeout(120_000) });
if (!response.ok || !response.body) throw new Error(`Python debugger download failed: HTTP ${response.status}`);
if (Number(response.headers.get('content-length')) > maxBytes)
throw new Error('Python debugger archive exceeds 64 MiB');
const chunks = [];
let size = 0;
for await (const chunk of response.body) {
size += chunk.length;
if (size > maxBytes) throw new Error('Python debugger archive exceeds 64 MiB');
chunks.push(chunk);
}
bytes = Buffer.concat(chunks);
}
if (sha256(bytes) !== expected) throw new Error('Python debugger checksum mismatch; nothing was installed');
await mkdir(dirname(target), { recursive: true });
const temporary = `${target}.${randomUUID()}.partial`;
try {
await writeFile(temporary, bytes, { flag: 'wx', mode: 0o644 });
await rename(temporary, target);
} finally {
await rm(temporary, { force: true });
}
// Theia's local-dir resolver requires unpacked system plugins. Keep VSIX files
// in its explicitly ignored dot-directory and verify before every extraction.
const unpacked = join(directory, `.${id}-${randomUUID()}`);
const plugin = join(directory, id);
const previous = `${unpacked}-previous`;
let moved = false;
try {
await run(
'python3',
[
'-c',
`
import json,os,pathlib,stat,sys,zipfile
archive,target,expected_id,expected_version=sys.argv[1:]
with zipfile.ZipFile(archive) as z:
entries=z.infolist()
if len(entries)>100000 or sum(i.file_size for i in entries)>268435456: raise ValueError('Plugin extraction size limit')
for item in entries:
p=pathlib.PurePosixPath(item.filename)
if p.is_absolute() or '..' in p.parts or '\\\\' in item.filename or stat.S_ISLNK(item.external_attr>>16): raise ValueError('Unsafe plugin archive path')
manifest=json.loads(z.read('extension/package.json'))
if manifest.get('publisher')+'.'+manifest.get('name')!=expected_id or manifest.get('version')!=expected_version: raise ValueError('Plugin identity mismatch')
z.extractall(target)
for item in entries:
if not item.is_dir(): os.chmod(pathlib.Path(target)/item.filename, 0o755 if (item.external_attr>>16)&0o111 else 0o644)
`,
target,
unpacked,
id,
version,
],
{ timeout: 30_000 },
);
try {
await rename(plugin, previous);
moved = true;
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
try {
await rename(unpacked, plugin);
} catch (error) {
if (moved) await rename(previous, plugin);
throw error;
}
await rm(previous, { recursive: true, force: true });
} finally {
await rm(unpacked, { recursive: true, force: true });
}
return { target: plugin, archive: target, sha256: expected, cached };
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const args = process.argv.slice(2);
const flags = new Map();
for (let index = 0; index < args.length; index += 2) flags.set(args[index], args[index + 1]);
if (
args.length % 2 ||
[...flags].some(
([key, value]) => !['--archive', '--python-archive', '--pyright-archive'].includes(key) || !value,
) ||
flags.size * 2 !== args.length
) {
console.error(
'Usage: node scripts/download-python-debugger.mjs [--archive /path/to/debugpy.vsix] [--python-archive /path/to/python.vsix] [--pyright-archive /path/to/pyright.vsix]',
);
process.exitCode = 1;
} else {
try {
console.log(
JSON.stringify(
await installPythonDebugger({
archive: flags.get('--archive'),
pythonArchive: flags.get('--python-archive'),
pyrightArchive: flags.get('--pyright-archive'),
}),
),
);
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}
}

View File

@ -1,26 +0,0 @@
{
"id": "ms-python.debugpy",
"version": "2026.6.0",
"vscodeEngine": "^1.92.0",
"source": "https://open-vsx.org/extension/ms-python/debugpy/2026.6.0",
"pythonDependency": {
"id": "ms-python.python",
"version": "2026.4.0",
"vscodeEngine": "^1.95.0",
"url": "https://open-vsx.org/api/ms-python/python/2026.4.0/file/ms-python.python-2026.4.0.vsix",
"sha256": "232aeafb01f069824fdd92d3e628c1c442bbcfa1d3cc945ff97076340bb2b4a6"
},
"languageServer": {
"id": "ms-pyright.pyright",
"version": "1.1.402",
"vscodeEngine": "^1.99.0",
"url": "https://open-vsx.org/api/ms-pyright/pyright/1.1.402/file/ms-pyright.pyright-1.1.402.vsix",
"sha256": "7ffa5a8649fa800b282c25ad70ce290367e036238d52727da7cdcac3d57439e9"
},
"platforms": {
"darwin-arm64": "3425b5251b0f0642b569e64397effe72ab141d138abd966b567041baa5609b4b",
"darwin-x64": "7a87aeba6a4dc1f46cfb8e6d457e53256c80b5be75a1781d51d3e0ad5dbb1574",
"linux-x64": "c7744af4bf72978f5792624a71c80e2b622a1118574fada3a903d70ac03d5bca",
"linux-arm64": "4e7aa92b0459c1010ee010a79b35ecc16328b943a84589bd9e8ead3d4eb0010b"
}
}

View File

@ -1,51 +0,0 @@
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { existsSync, mkdirSync } from 'node:fs';
const appRoot = fileURLToPath(new URL('../', import.meta.url));
const cli = fileURLToPath(new URL('../node_modules/@theia/cli/bin/theia.js', import.meta.url));
const production = process.env.NODE_ENV === 'production';
if (!existsSync(cli) || !existsSync(`${appRoot}lib/frontend/index.html`)) {
// Theia releases may emit frontend assets under lib; use backend generation
// as the authoritative build prerequisite below.
if (!existsSync(`${appRoot}src-gen/backend/main.js`)) {
console.error('Install and build this independent package first: npm install && npm run build');
process.exit(1);
}
}
if (production && process.env.WISHFORGE_GATEWAY_ENFORCED !== 'true') {
console.error('Production requires an authenticated workspace gateway. See README.md.');
process.exit(1);
}
const port = process.env.WISHFORGE_IDE_PORT ?? '4300';
if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535) throw new Error('Invalid WISHFORGE_IDE_PORT');
const hostname = process.env.WISHFORGE_IDE_HOST ?? '127.0.0.1';
const workspace = process.env.WISHFORGE_WORKSPACE_PATH ?? `${appRoot}workspace`;
if (!process.env.WISHFORGE_WORKSPACE_PATH) mkdirSync(workspace, { recursive: true });
if (!existsSync(workspace)) throw new Error('Configured workspace path does not exist');
const child = spawn(
process.execPath,
[cli, 'start', workspace, '--hostname', hostname, '--port', port, '--plugins', `local-dir:${appRoot}plugins`],
{
cwd: appRoot,
detached: process.platform !== 'win32',
stdio: 'inherit',
env: {
...process.env,
PYTHONDONTWRITEBYTECODE: '1',
WF_IDE_MANAGED_PLUGINS_DIR: `${appRoot}plugins`,
// No public/default OCT fallback while project-bound room admission is absent.
COLLABORATION_SERVER_URL: process.env.WF_COLLABORATION_GATEWAY_URL ?? 'https://collaboration-disabled.invalid/',
},
},
);
for (const signal of ['SIGINT', 'SIGTERM'])
process.on(signal, () => {
try {
if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, signal);
else child.kill(signal);
} catch {
child.kill(signal);
}
});
child.on('exit', code => process.exit(code ?? 1));

View File

@ -1,5 +0,0 @@
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const { validateManagedPlugins } = createRequire(import.meta.url)('../policy/managed-plugins.cjs');
const plugins = validateManagedPlugins(fileURLToPath(new URL('../plugins', import.meta.url)));
console.log(`Verified ${plugins.length} operator-managed extensions against pinned IDs, versions and content digests.`);

View File

@ -1,11 +1,11 @@
# Provisioner
为每个运行代次创建执行环境(一个 executor、一个 verifier),并为云 IDE 创建工作区。控制面的派发器通过 HTTP 调用它;它本身不访问数据库,也不持有令牌签名密钥。
为每个运行代次创建执行环境(一个 executor、一个 verifier)。控制面的派发器通过 HTTP 调用它;它本身不访问数据库,也不持有令牌签名密钥。
| 后端 | `WF_PROVISIONER_BACKEND` | 用途 |
|---|---|---|
| `local` | `local` | 本地开发。为每个代次在本机启动两个 worker 进程(`WF_SANDBOX_MODE=host`),**没有隔离**;只在 `WF_DEPLOYMENT_MODE=development` 下启动。所有工作区指向同一个本机 Theia。 |
| `kubernetes` | `kubernetes` | 生产。用 `kubectl --context … --namespace …` 创建 Kata Job、PVC、Secret、ServiceAccount 与 NetworkPolicy,IDE 工作区为独立的 Deployment。 |
| `local` | `local` | 本地开发。为每个代次在本机启动两个 worker 进程(`WF_SANDBOX_MODE=host`),**没有隔离**;只在 `WF_DEPLOYMENT_MODE=development` 下启动。 |
| `kubernetes` | `kubernetes` | 生产。用 `kubectl --context … --namespace …` 创建 Kata Job、PVC、Secret、ServiceAccount 与 NetworkPolicy。 |
## 接口
@ -16,8 +16,6 @@
| `POST /runs` | `{tenantId, runId, generation, executorToken, verifierToken, resourceGrant}` | 为该代次启动 executor 与 verifier。同一代次重复请求不会重复启动。返回 `{status: "provisioned", …}`。 |
| `POST /runs/release` | `{tenantId, runId, generation, resourceGrant}` | 停止该代次的计算资源。返回 `{status: "released", computeReleased, persistentStorageRetained}`,控制面收到后才归还并发名额。 |
| `POST /runs/purge` | 同上(使用最近一个代次的授权,允许过期) | 删除该运行所有代次保留的卷(本地后端删除运行目录)。运行仍有活动的 Pod 或进程时返回 `{status: "busy"}`,否则返回 `{status: "purged", persistentStorageRetained: false}`。控制面在保留期过后调用。 |
| `POST /workspaces` | `{tenantId, projectId, workspaceId}` | 创建或返回工作区,`{status: "ready" \| "pending", upstreamUrl}`;`local` 后端另返回 `lifecycle: "unmanaged"`(不支持暂停/恢复)。 |
| `GET/PUT /workspaces/:id/lifecycle` | — | 仅 `kubernetes` 后端:观察与调整工作区的暂停/运行状态。 |
| `GET /healthz` | — | `{status: "ok", service: "wishforge-provisioner", backend}` |
资源授权(`resourceGrant`)由 API 用 `WF_RESOURCE_GRANT_SECRET` 做 HMAC 签名,绑定租户、运行、代次、套餐、CPU/内存/存储与运行镜像,有效期 5 分钟。两个后端都校验签名、租户与有效期;`kubernetes` 后端还要求镜像在当前或上一版的允许列表内,并按授权限制资源(两个角色各一半)。
@ -35,7 +33,6 @@ executor 与 verifier 各自只拿到自己的运行级令牌(由 API 签发
| `WF_TENANT_ID` | 本服务的唯一租户(本地为 `demo`) |
| `WF_RESOURCE_GRANT_SECRET` | 与 API 共享的资源授权签名密钥 |
| `WF_LOCAL_RUN_ROOT` | 运行目录,默认 `~/.local/share/wishforge/runs`,必须位于 WishForge 源码目录之外;每个代次为 `<租户>/<运行>/<代次>/{executor,verifier}` |
| `WF_LOCAL_IDE_URL` | 本机 Theia 地址(`npm run dev:ide` 启动在 `http://127.0.0.1:4300/`);能访问时工作区才变为 ready |
| `WF_CONTROL_PLANE_URL`、`TEMPORAL_ADDRESS`、`TEMPORAL_NAMESPACE` | 传给 worker 进程 |
worker 进程只继承 `PATH`、`HOME`、`LANG`、`TMPDIR`、代理变量、`WF_GIT_ALLOW_LOCAL_HTTP`、`WF_CODEBUDDY_BIN`、`WF_CLAUDE_BIN`、`WF_DOCKER_CONFIG` 与 Temporal 的 TLS 设置,拿不到数据库、签名密钥等其他配置。代次结束后进程被停止,目录保留在磁盘上便于排查,保留期过后由控制面清理(同 `POST /runs/purge`)。provisioner 重启时会停止它启动的进程;仍在进行的运行会在 5 分钟后进入 `worker_unavailable` 等待,点击「继续」即可用新的代次重新执行。
@ -51,7 +48,7 @@ worker 进程只继承 `PATH`、`HOME`、`LANG`、`TMPDIR`、代理变量、`WF_
| `WF_RUN_WORKER_IMAGE` | worker 镜像,必须是 `仓库/镜像@sha256:…` |
| `WF_RUN_PREVIOUS_IMAGES` | 可选,仍允许运行的上一版镜像(逗号分隔) |
| `WF_RUN_STORAGE_CLASS` | PVC 存储类 |
| `WF_RUN_STORAGE_SIZE` | 单个运行的存储上限(两个角色各一半)与 IDE 工作区卷的大小,默认 `10Gi` |
| `WF_RUN_STORAGE_SIZE` | 单个运行的存储上限(两个角色各一半),默认 `10Gi` |
| `WF_CONTROL_PLANE_URL` | API 的 HTTPS 地址 |
| `WF_CONTROL_NAMESPACE` | 控制面命名空间(网络策略放行其中的 API、Temporal 与平台 Git) |
| `WF_GIT_SERVICE_PORT` | 平台 Git 服务端口,默认 4504 |
@ -63,21 +60,9 @@ worker 进程只继承 `PATH`、`HOME`、`LANG`、`TMPDIR`、代理变量、`WF_
| `WF_VERIFIER_DOCKER_CONFIG_SECRET` | 可选,仅 verifier 挂载的镜像仓库凭据(`DOCKER_CONFIG`) |
| `WF_VERIFIER_DOCKER_HOST`、`WF_VERIFIER_DOCKER_TLS_SECRET`、`WF_VERIFIER_BUILDER_NAMESPACE` | 可选,远程构建器(`tcp://主机:端口`,Pod 标签 `wishforge.io/component: image-builder`)及其 TLS 客户端证书(`ca.pem`、`cert.pem`、`key.pem`,生产必填)和所在命名空间(默认控制面命名空间);只有 verifier 能连到它 |
| `WF_RUN_INSTALL_PROXY_URL`、`WF_RUN_INSTALL_PROXY_NAMESPACE` | 可选,依赖安装使用的出站代理(`http(s)://主机:端口`,Pod 标签 `wishforge.io/component: egress-proxy`)及其命名空间(默认控制面命名空间) |
| `WF_THEIA_IMAGE` | IDE 工作区镜像(`apps/ide/Dockerfile` 默认目标),必须是 digest 引用 |
| `WF_OCT_WORKSPACE_IMAGE`、`WF_IDE_PUBLIC_URL` | 可选,协作 sidecar 镜像(digest)与网关的公开 HTTPS 源站(与网关的 `WF_IDE_PUBLIC_URL` 相同);`WF_OCT_WORKSPACE_IMAGE` 配置后工作区启用协作。本地开发集群(`WF_ALLOW_INSECURE_HTTP=true`)中网关地址与工作区的平台 Git 地址可以是 HTTP |
每个代次创建:两个 RWO PVC、两个能力 Secret(各含一个角色的令牌)、两个不挂载令牌的 ServiceAccount、两个 Kata Job(`backoffLimit: 0`,非 root,只读根文件系统,丢弃全部 capability)以及一条 NetworkPolicy。新代次开始前只删除同一运行的旧 Job。`POST /runs/release` 删除属于该代次标签的 Job,Pod 全部结束后再删除该代次的 Secret、ServiceAccount 与 NetworkPolicy。PVC 保留用于排查,保留期过后由控制面通过 `POST /runs/purge` 按运行标签删除。
每个 IDE 工作区创建一个 PVC、一个 Kata Deployment(Theia,可选 OCT sidecar)、一个 Service 与一条 NetworkPolicy(只允许控制面中 `wishforge.io/component: workspace-gateway` 的 Pod 访问 3000/8100 端口,出站只有 DNS)。所需的 RBAC 与命名空间基线见 [infra/k8s](../../infra/k8s/README.md)。
请求带 `repositoryUrl`(API 只为平台托管仓库发送,地址必须是 HTTPS 的 `/git/<租户>/<项目>.git`)时:
- Theia 收到 `WISHFORGE_GIT_REMOTE`,只接受这个仓库的凭据;
- 内存卷挂载为 `WISHFORGE_GIT_CREDENTIAL_DIR`(`/run/wishforge/git`),令牌只存在这里;
- 网络策略额外放行控制面中 `wishforge.io/component: git-storage` 的 Pod(`WF_GIT_SERVICE_PORT`)。
克隆与凭据的投递见 [apps/ide/README.md](../ide/README.md)。
网络策略只放行 DNS、控制面 API(含模型代理)、Temporal 与平台 Git 服务(`WF_GIT_SERVICE_PORT`,默认 4504,Pod 标签 `wishforge.io/component: git-storage`)。配置了出站代理与构建器时,再分别放行它们:代理给两个角色,构建器只给 verifier(单独的 `<前缀>-builder` 策略,释放时一并删除)。代理与构建器本身由运维提供(见 [operations.md](../../docs/operations.md))。
## 测试

View File

@ -66,7 +66,6 @@ export function readLocalConfig(env = process.env, cwd = process.cwd()) {
runRoot: path.resolve(cwd, env.WF_LOCAL_RUN_ROOT ?? path.join(homedir(), '.local/share/wishforge/runs')),
cwd,
workerEntry: path.resolve(cwd, env.WF_LOCAL_WORKER_ENTRY ?? 'apps/worker/src/main.ts'),
ideUrl: env.WF_LOCAL_IDE_URL,
claudeAuthHome: env.WF_CLAUDE_LOCAL_AUTH_HOME,
passthrough: Object.fromEntries(PASSTHROUGH.filter(name => env[name]).map(name => [name, env[name]])),
// Grants are verified like in production, but the host has no image and no fixed caps.
@ -90,11 +89,6 @@ export function readLocalConfig(env = process.env, cwd = process.cwd()) {
throw new Error('WF_CLAUDE_LOCAL_AUTH_HOME must be an absolute path');
if (config.resourceGrantSecret.length < 32)
throw new Error('WF_RESOURCE_GRANT_SECRET must be at least 32 characters');
if (config.ideUrl) {
const url = new URL(config.ideUrl);
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
throw new Error('WF_LOCAL_IDE_URL must be an HTTP(S) URL without credentials');
}
return config;
}
@ -122,10 +116,7 @@ function stopProcess(child, timeoutMs = 10_000) {
});
}
export function createLocalBackend(
config,
{ spawnProcess = spawn, log = line => console.log(line), fetcher = fetch } = {},
) {
export function createLocalBackend(config, { spawnProcess = spawn, log = line => console.log(line) } = {}) {
/** Live worker processes per tenant, run and generation. */
const generations = new Map();
return {
@ -229,24 +220,6 @@ export function createLocalBackend(
persistentStorageRetained: true,
};
},
/** Every workspace opens the one local Theia, once it answers; its lifecycle is not managed. */
async provisionWorkspace(input) {
if (
!input ||
// The one local Theia is told the Git service origin instead (scripts/dev-ide.mjs).
Object.keys(input).some(key => !['tenantId', 'projectId', 'workspaceId', 'repositoryUrl'].includes(key)) ||
input.tenantId !== config.tenantId ||
!id.test(input.projectId ?? '') ||
!id.test(input.workspaceId ?? '')
)
throw new Error('INVALID_WORKSPACE_REQUEST');
if (!config.ideUrl) return { status: 'pending', upstreamUrl: '', lifecycle: 'unmanaged' };
const reachable = await fetcher(config.ideUrl, { signal: AbortSignal.timeout(2000) }).then(
response => response.status < 500,
() => false,
);
return { status: reachable ? 'ready' : 'pending', upstreamUrl: config.ideUrl, lifecycle: 'unmanaged' };
},
async close() {
await Promise.all([...generations.values()].flat().map(child => stopProcess(child, 3000)));
generations.clear();

View File

@ -1,13 +1,11 @@
import http from 'node:http';
import { timingSafeEqual } from 'node:crypto';
import { readConfig, provisionRun } from './kubernetes.mjs';
import { provisionWorkspace } from './workspaces.mjs';
import { purgeRunStorage, releaseRun } from './run-release.mjs';
import { observeWorkspaceLifecycle, reconcileWorkspaceLifecycle } from './workspace-lifecycle.mjs';
import { createRunOperationQueue } from './run-operations.mjs';
import { createLocalBackend, readLocalConfig } from './local.mjs';
/** `local` runs workers as host processes for development; `kubernetes` creates Kata Jobs and IDE Deployments. */
/** `local` runs workers as host processes for development; `kubernetes` creates Kata Jobs. */
function backendFor(name) {
if (name === 'local') return createLocalBackend(readLocalConfig());
if (name === 'kubernetes') {
@ -17,9 +15,6 @@ function backendFor(name) {
provisionRun: input => provisionRun(config, input),
releaseRun: input => releaseRun(config, input),
purgeRun: input => purgeRunStorage(config, input),
provisionWorkspace: input => provisionWorkspace(config, input),
observeWorkspace: input => observeWorkspaceLifecycle(config, input),
reconcileWorkspace: input => reconcileWorkspaceLifecycle(config, input),
async close() {},
};
}
@ -60,40 +55,19 @@ const server = http.createServer(async (req, res) => {
res.end(JSON.stringify({ error: 'UNAUTHORIZED' }));
return;
}
const target = new URL(req.url, 'http://provisioner.local');
const lifecycle = /^\/workspaces\/([a-zA-Z0-9_-]{1,128})\/lifecycle$/.exec(target.pathname);
if (lifecycle && backend.observeWorkspace && req.method === 'GET') {
const input = {
tenantId: target.searchParams.get('tenantId'),
projectId: target.searchParams.get('projectId'),
workspaceId: lifecycle[1],
};
res.end(JSON.stringify(await backend.observeWorkspace(input)));
return;
}
if (lifecycle && backend.reconcileWorkspace && req.method === 'PUT') {
const input = await body(req, 4000);
if (input.workspaceId !== lifecycle[1]) throw new Error('INVALID_WORKSPACE_SCOPE');
res.writeHead(202);
res.end(JSON.stringify(await backend.reconcileWorkspace(input)));
return;
}
if (!['/runs', '/runs/release', '/runs/purge', '/workspaces'].includes(req.url) || req.method !== 'POST') {
if (!['/runs', '/runs/release', '/runs/purge'].includes(req.url) || req.method !== 'POST') {
res.writeHead(404);
res.end(JSON.stringify({ error: 'NOT_FOUND' }));
return;
}
const input = await body(req, 40000);
const result =
req.url === '/workspaces'
? await backend.provisionWorkspace(input)
: await runOperation(input.tenantId, input.runId, () =>
req.url === '/runs/release'
? backend.releaseRun(input)
: req.url === '/runs/purge'
? backend.purgeRun(input)
: backend.provisionRun(input),
);
const result = await runOperation(input.tenantId, input.runId, () =>
req.url === '/runs/release'
? backend.releaseRun(input)
: req.url === '/runs/purge'
? backend.purgeRun(input)
: backend.provisionRun(input),
);
res.writeHead(202);
res.end(JSON.stringify(result));
} catch (error) {

View File

@ -220,21 +220,3 @@ test('rejects forged, foreign or malformed requests before starting anything', a
await f.cleanup();
}
});
test('points workspaces at the local Theia once it answers, without a managed lifecycle', async () => {
const f = await fixture({ WF_LOCAL_IDE_URL: 'http://127.0.0.1:4300/' });
try {
const input = { tenantId: 'demo', projectId: 'project-1', workspaceId: 'workspace-1' };
const down = createLocalBackend(f.config, { fetcher: async () => Promise.reject(new Error('ECONNREFUSED')) });
assert.deepEqual(await down.provisionWorkspace(input), {
status: 'pending',
upstreamUrl: 'http://127.0.0.1:4300/',
lifecycle: 'unmanaged',
});
const up = createLocalBackend(f.config, { fetcher: async () => new Response('ok') });
assert.equal((await up.provisionWorkspace(input)).status, 'ready');
await assert.rejects(up.provisionWorkspace({ ...input, tenantId: 'other' }), /INVALID_WORKSPACE_REQUEST/);
} finally {
await f.cleanup();
}
});

View File

@ -1,126 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { renderWorkspaceResources } from '../workspaces.mjs';
import { observeWorkspaceLifecycle, reconcileWorkspaceLifecycle } from '../workspace-lifecycle.mjs';
const config = {
tenantId: 'alpha',
namespace: 'wf-alpha',
context: 'fixture',
controlNamespace: 'wf-control',
runtimeClass: 'kata',
storageClass: 'fixture',
storageSize: '10Gi',
};
const input = { tenantId: 'alpha', projectId: 'project', workspaceId: 'workspace' };
function fixture() {
const rendered = renderWorkspaceResources(config, input, `registry.example/theia@sha256:${'a'.repeat(64)}`);
const d = rendered.resources.find(r => r.kind === 'Deployment');
d.metadata.uid = 'immutable-uid';
d.metadata.resourceVersion = '1';
d.metadata.generation = 1;
d.status = { observedGeneration: 1, availableReplicas: 1, updatedReplicas: 1, replicas: 1 };
let pods = [];
let lose = false;
const calls = [];
const execute = async (_config, args) => {
calls.push(args);
if (args[0] === 'get' && args[1] === 'pods') return { items: pods };
if (args[0] === 'get') return structuredClone(d);
assert.equal(args[0], 'patch');
assert.equal(args[1], 'deployment');
assert.equal(args[2], rendered.name);
const patch = JSON.parse(args[args.indexOf('-p') + 1]);
assert.equal(patch[0].value, d.metadata.resourceVersion);
assert.equal(patch[1].value, d.metadata.uid);
d.metadata.annotations = patch[2].value;
d.spec.replicas = patch[3].value;
d.metadata.resourceVersion = String(Number(d.metadata.resourceVersion) + 1);
d.metadata.generation++;
if (lose) throw new Error('KUBERNETES_LIFECYCLE_UNKNOWN');
return structuredClone(d);
};
return {
d,
calls,
execute,
setPods: value => {
pods = value;
},
lose: () => {
lose = true;
},
converge: () => {
d.status = {
observedGeneration: d.metadata.generation,
replicas: d.spec.replicas,
availableReplicas: d.spec.replicas,
updatedReplicas: d.spec.replicas,
};
},
};
}
test('pause only patches the owned IDE deployment, retains all PVCs, and waits for observed termination', async () => {
const f = fixture();
const request = { ...input, revision: 1, desired: 'paused' };
assert.equal((await reconcileWorkspaceLifecycle(config, request, { execute: f.execute })).status, 'pending');
f.converge();
f.setPods([{ status: { phase: 'Running' }, metadata: { deletionTimestamp: new Date().toISOString() } }]);
assert.equal((await observeWorkspaceLifecycle(config, input, { execute: f.execute })).status, 'pending');
f.setPods([]);
assert.equal((await observeWorkspaceLifecycle(config, input, { execute: f.execute })).status, 'paused');
assert.ok(f.calls.every(args => !args.includes('pvc') && !args.includes('delete') && !args.includes('service')));
});
test('resume does not claim ready until updated and available replica is observed', async () => {
const f = fixture();
await reconcileWorkspaceLifecycle(config, { ...input, revision: 1, desired: 'paused' }, { execute: f.execute });
f.converge();
assert.equal(
(await reconcileWorkspaceLifecycle(config, { ...input, revision: 2, desired: 'running' }, { execute: f.execute }))
.status,
'pending',
);
f.converge();
assert.equal((await observeWorkspaceLifecycle(config, input, { execute: f.execute })).status, 'ready');
});
test('lost mutation response reconciles by observation and does not send a duplicate patch', async () => {
const f = fixture();
f.lose();
const request = { ...input, revision: 1, desired: 'paused' };
await assert.rejects(reconcileWorkspaceLifecycle(config, request, { execute: f.execute }), /UNKNOWN/);
f.converge();
assert.equal((await reconcileWorkspaceLifecycle(config, request, { execute: f.execute })).status, 'paused');
assert.equal(f.calls.filter(a => a[0] === 'patch').length, 1);
});
test('tenant, namespace, managed labels and revision fencing reject without mutations', async () => {
const f = fixture();
await assert.rejects(
reconcileWorkspaceLifecycle(
config,
{ ...input, tenantId: 'other', revision: 1, desired: 'paused' },
{ execute: f.execute },
),
/SCOPE/,
);
f.d.metadata.labels['wishforge.io/component'] = 'production-app';
await assert.rejects(
reconcileWorkspaceLifecycle(config, { ...input, revision: 1, desired: 'paused' }, { execute: f.execute }),
/OWNERSHIP/,
);
f.d.metadata.labels['wishforge.io/component'] = 'ide';
f.d.metadata.namespace = 'production';
await assert.rejects(
reconcileWorkspaceLifecycle(config, { ...input, revision: 1, desired: 'paused' }, { execute: f.execute }),
/OWNERSHIP/,
);
f.d.metadata.namespace = config.namespace;
f.d.metadata.annotations = { 'wishforge.io/lifecycle-revision': '3', 'wishforge.io/lifecycle-desired': 'running' };
await assert.rejects(
reconcileWorkspaceLifecycle(config, { ...input, revision: 2, desired: 'paused' }, { execute: f.execute }),
/STALE/,
);
await assert.rejects(
reconcileWorkspaceLifecycle(config, { ...input, revision: 3, desired: 'paused' }, { execute: f.execute }),
/CONFLICT/,
);
assert.equal(f.calls.filter(a => a[0] === 'patch').length, 0);
});

View File

@ -1,102 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { renderWorkspaceResources, provisionWorkspace } from '../workspaces.mjs';
const config = {
tenantId: 'alpha',
namespace: 'wf-alpha',
controlNamespace: 'wf-control',
gitServicePort: 4504,
runtimeClass: 'wishforge-kata',
storageClass: 'test-storage',
storageSize: '10Gi',
};
const input = { tenantId: 'alpha', projectId: 'project-1', workspaceId: 'workspace-1' };
const image = `registry.invalid/theia@sha256:${'a'.repeat(64)}`;
test('workspace provisioning uses the actual Theia start contract and a private isolated endpoint', () => {
const rendered = renderWorkspaceResources(config, input, image);
const pod = rendered.resources.find(r => r.kind === 'Deployment').spec.template.spec;
assert.equal(pod.runtimeClassName, 'wishforge-kata');
assert.equal(pod.automountServiceAccountToken, false);
const env = Object.fromEntries(pod.containers[0].env.map(e => [e.name, e.value]));
assert.equal(env.WISHFORGE_IDE_PORT, '3000');
assert.equal(env.WISHFORGE_GATEWAY_ENFORCED, 'true');
assert.equal(env.WISHFORGE_WORKSPACE_PATH, '/home/theia/data/workspace');
assert.equal(env.WISHFORGE_COLLABORATION_ENABLED, 'false');
assert.equal(rendered.resources.find(r => r.kind === 'Service').spec.type, 'ClusterIP');
});
test('creating manifests does not mark an unready IDE available', async () => {
let applied = false;
const result = await provisionWorkspace(config, input, {
image,
apply: async () => {
applied = true;
},
observe: async () => false,
});
assert.ok(applied);
assert.equal(result.status, 'pending');
assert.throws(() => renderWorkspaceResources(config, { ...input, tenantId: 'beta' }, image));
});
test('a workspace of a platform repository may reach the Git service and keeps its token in memory', () => {
const repositoryUrl = 'https://git.example/git/alpha/project-1.git';
const rendered = renderWorkspaceResources(config, { ...input, repositoryUrl }, image);
const pod = rendered.resources.find(r => r.kind === 'Deployment').spec.template.spec;
const env = Object.fromEntries(pod.containers[0].env.map(e => [e.name, e.value]));
assert.equal(env.WISHFORGE_GIT_REMOTE, repositoryUrl);
assert.equal(env.WISHFORGE_GIT_CREDENTIAL_DIR, '/run/wishforge/git');
assert.deepEqual(pod.volumes.find(v => v.name === 'git-credentials').emptyDir, {
medium: 'Memory',
sizeLimit: '1Mi',
});
const egress = rendered.resources.find(r => r.kind === 'NetworkPolicy').spec.egress;
assert.deepEqual(egress.at(-1), {
to: [
{
namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': 'wf-control' } },
podSelector: { matchLabels: { 'wishforge.io/component': 'git-storage' } },
},
],
ports: [{ protocol: 'TCP', port: 4504 }],
});
// Without a platform repository nothing beyond DNS is reachable.
const plain = renderWorkspaceResources(config, input, image);
assert.equal(plain.resources.find(r => r.kind === 'NetworkPolicy').spec.egress.length, 1);
for (const other of [
'http://git.example/git/alpha/project-1.git',
'https://token@git.example/git/alpha/project-1.git',
'https://git.example/git/beta/project-1.git',
'https://git.example/git/alpha/project-2.git',
])
assert.throws(() => renderWorkspaceResources(config, { ...input, repositoryUrl: other }, image), /REPOSITORY/);
});
test('only a local development cluster serves the repository and the gateway over plain HTTP', () => {
const repositoryUrl = 'http://git-storage.wf-control.svc.cluster.local:4504/git/alpha/project-1.git';
const collaboration = { image, gatewayBase: 'http://localhost:4400/' };
const local = { ...config, runtimeClass: undefined, insecureHttp: true };
const rendered = renderWorkspaceResources(local, { ...input, repositoryUrl }, image, collaboration);
const env = Object.fromEntries(
rendered.resources
.find(r => r.kind === 'Deployment')
.spec.template.spec.containers[0].env.map(e => [e.name, e.value]),
);
assert.equal(env.WISHFORGE_GIT_REMOTE, repositoryUrl);
assert.equal(env.WF_COLLABORATION_GATEWAY_URL, 'http://localhost:4400/workspaces/workspace-1/collaboration/');
assert.throws(() => renderWorkspaceResources(config, { ...input, repositoryUrl }, image), /REPOSITORY/);
assert.throws(() => renderWorkspaceResources(config, input, image, collaboration), /GATEWAY/);
});
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(!JSON.stringify(pod).includes('PRIVATE_KEY'));
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');
assert.ok(rendered.collaborationUpstreamUrl.endsWith(':8100'));
}
});

View File

@ -1,132 +0,0 @@
import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
const id = /^[a-zA-Z0-9_-]{1,128}$/;
const revisionKey = 'wishforge.io/lifecycle-revision';
const desiredKey = 'wishforge.io/lifecycle-desired';
function scope(config, input) {
if (
!input ||
input.tenantId !== config.tenantId ||
!id.test(input.projectId ?? '') ||
!id.test(input.workspaceId ?? '')
)
throw new Error('INVALID_WORKSPACE_SCOPE');
return `wf-ide-${createHash('sha256').update(`${input.tenantId}/${input.workspaceId}`).digest('hex').slice(0, 24)}`;
}
function assertOwned(config, name, value) {
if (
value?.metadata?.name !== name ||
value.metadata.namespace !== config.namespace ||
value.metadata.labels?.['app.kubernetes.io/managed-by'] !== 'wishforge-provisioner' ||
value.metadata.labels?.['wishforge.io/component'] !== 'ide' ||
value.metadata.labels?.['wishforge.io/workspace'] !== name
)
throw new Error('WORKSPACE_OWNERSHIP_MISMATCH');
}
export function kubectlJson(config, args) {
return new Promise((resolve, reject) => {
const child = spawn('kubectl', ['--context', config.context, '--namespace', config.namespace, ...args], {
stdio: ['ignore', 'pipe', 'pipe'],
});
let output = '';
let settled = false;
const fail = () => {
if (!settled) {
settled = true;
reject(new Error('KUBERNETES_LIFECYCLE_UNKNOWN'));
}
};
const timeout = setTimeout(() => {
child.kill('SIGTERM');
fail();
}, 10000);
child.stdout.on('data', part => {
output += part;
if (output.length > 2 * 1024 * 1024) {
child.kill('SIGTERM');
fail();
}
});
child.stderr.resume();
child.on('error', fail);
child.on('close', code => {
clearTimeout(timeout);
if (settled) return;
try {
if (code !== 0) throw Error();
const value = JSON.parse(output);
settled = true;
resolve(value);
} catch {
fail();
}
});
});
}
export async function observeWorkspaceLifecycle(config, input, options = {}) {
const name = scope(config, input);
const execute = options.execute ?? kubectlJson;
const deployment = await execute(config, ['get', 'deployment', name, '-o', 'json']);
assertOwned(config, name, deployment);
const revision = Number(deployment.metadata.annotations?.[revisionKey] ?? 0);
const desired = deployment.metadata.annotations?.[desiredKey] ?? 'running';
if (!Number.isSafeInteger(revision) || revision < 0 || !['running', 'paused'].includes(desired))
throw new Error('INVALID_WORKSPACE_LIFECYCLE_STATE');
let status = 'pending';
const observed = deployment.status?.observedGeneration >= deployment.metadata.generation;
if (
desired === 'running' &&
deployment.spec?.replicas === 1 &&
observed &&
deployment.status.availableReplicas === 1 &&
deployment.status.updatedReplicas === 1
)
status = 'ready';
if (desired === 'paused' && deployment.spec?.replicas === 0 && observed && (deployment.status.replicas ?? 0) === 0) {
const selector = `wishforge.io/workspace=${name},wishforge.io/component=ide,app.kubernetes.io/managed-by=wishforge-provisioner`;
const pods = await execute(config, ['get', 'pods', '--selector', selector, '-o', 'json']);
if (!Array.isArray(pods.items)) throw new Error('KUBERNETES_LIFECYCLE_UNKNOWN');
if (pods.items.every(p => ['Succeeded', 'Failed'].includes(p.status?.phase))) status = 'paused';
}
return {
workspaceId: input.workspaceId,
revision,
desired,
status,
deploymentUid: deployment.metadata.uid,
resourceVersion: deployment.metadata.resourceVersion,
};
}
export async function reconcileWorkspaceLifecycle(config, input, options = {}) {
if (
!['running', 'paused'].includes(input?.desired) ||
!Number.isSafeInteger(input.revision) ||
input.revision < 1 ||
Object.keys(input).some(k => !['tenantId', 'projectId', 'workspaceId', 'revision', 'desired'].includes(k))
)
throw new Error('INVALID_WORKSPACE_LIFECYCLE_REQUEST');
const execute = options.execute ?? kubectlJson;
const name = scope(config, input);
const deployment = await execute(config, ['get', 'deployment', name, '-o', 'json']);
assertOwned(config, name, deployment);
const previous = Number(deployment.metadata.annotations?.[revisionKey] ?? 0);
if (!Number.isSafeInteger(previous) || previous > input.revision) throw new Error('STALE_WORKSPACE_REVISION');
if (previous === input.revision) {
if (deployment.metadata.annotations?.[desiredKey] !== input.desired) throw new Error('WORKSPACE_REVISION_CONFLICT');
return observeWorkspaceLifecycle(config, input, { execute });
}
if (!deployment.metadata.resourceVersion || !deployment.metadata.uid) throw new Error('KUBERNETES_LIFECYCLE_UNKNOWN');
const annotations = {
...deployment.metadata.annotations,
[revisionKey]: String(input.revision),
[desiredKey]: input.desired,
};
const patch = [
{ op: 'test', path: '/metadata/resourceVersion', value: deployment.metadata.resourceVersion },
{ op: 'test', path: '/metadata/uid', value: deployment.metadata.uid },
{ op: 'add', path: '/metadata/annotations', value: annotations },
{ op: 'replace', path: '/spec/replicas', value: input.desired === 'paused' ? 0 : 1 },
];
await execute(config, ['patch', 'deployment', name, '--type=json', '-p', JSON.stringify(patch), '-o', 'json']);
return observeWorkspaceLifecycle(config, input, { execute });
}

View File

@ -1,290 +0,0 @@
import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { runKubectl } from './kubernetes.mjs';
const safe = /^[a-zA-Z0-9_-]{1,128}$/;
/** HTTPS, or plain HTTP on a local development cluster (WF_ALLOW_INSECURE_HTTP) inside the cluster. */
const secureEnough = (config, url) =>
url.protocol === 'https:' || (url.protocol === 'http:' && config.insecureHttp === true);
/** The project's platform repository; the workspace accepts credentials for it alone. */
function workspaceRepository(config, input) {
if (input.repositoryUrl === undefined) return undefined;
let url;
try {
url = new URL(input.repositoryUrl);
} catch {
throw new Error('INVALID_WORKSPACE_REPOSITORY');
}
if (
!secureEnough(config, url) ||
url.username ||
url.password ||
url.search ||
url.hash ||
url.pathname !== `/git/${input.tenantId}/${input.projectId}.git`
)
throw new Error('INVALID_WORKSPACE_REPOSITORY');
return url.href;
}
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', 'repositoryUrl'].includes(k))
)
throw new Error('INVALID_WORKSPACE_REQUEST');
const repository = workspaceRepository(config, input);
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: {
...(config.runtimeClass ? { 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 (repository) {
// The gateway delivers a short-lived token while the IDE is open; it is kept in memory only.
workspacePod.containers[0].env.push(
{ name: 'WISHFORGE_GIT_REMOTE', value: repository },
{ name: 'WISHFORGE_GIT_CREDENTIAL_DIR', value: '/run/wishforge/git' },
);
workspacePod.volumes.push({ name: 'git-credentials', emptyDir: { medium: 'Memory', sizeLimit: '1Mi' } });
workspacePod.containers[0].volumeMounts.push({ name: 'git-credentials', mountPath: '/run/wishforge/git' });
resources
.find(r => r.kind === 'NetworkPolicy')
.spec.egress.push({
to: [
{
namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': config.controlNamespace } },
podSelector: { matchLabels: { 'wishforge.io/component': 'git-storage' } },
},
],
ports: [{ protocol: 'TCP', port: config.gitServicePort ?? 4504 }],
});
}
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 (
!secureEnough(config, gateway) ||
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_IDE_PUBLIC_URL }
: undefined);
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 {
status: ready ? 'ready' : 'pending',
workspaceId: input.workspaceId,
upstreamUrl: rendered.upstreamUrl,
collaborationUpstreamUrl: rendered.collaborationUpstreamUrl,
};
}

View File

@ -999,48 +999,6 @@ button {
padding: 14px 22px;
border-top: 1px solid #edf1f5;
}
.workspace-list {
padding: 0 22px 20px;
}
.branch-list {
list-style: none;
margin: 0;
padding: 0 22px 16px;
}
.branch-list li {
display: flex;
align-items: center;
gap: 10px;
font-size: 12px;
padding: 8px 0;
border-bottom: 1px solid #edf1f5;
}
.branch-list li > span {
color: var(--muted);
flex: 1;
}
.workspace-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
margin-bottom: 10px;
}
.workspace-row strong {
font-size: 13px;
display: block;
}
.workspace-row .status {
margin-top: 5px;
}
.workspace-row p {
font-size: 12px;
color: var(--muted);
margin-top: 5px;
}
.workspace-row > span {
font-size: 12px;
}
.form-columns {
display: grid;
grid-template-columns: minmax(0, 1.7fr) minmax(250px, 1fr);
@ -2257,13 +2215,6 @@ button {
padding: 0 17px 15px;
font-size: 11px;
}
.workspace-list {
padding: 0 17px 16px;
}
.workspace-row {
flex-wrap: wrap;
gap: 12px;
}
.panel > .notice {
margin: 0 17px 13px;
}

View File

@ -1,69 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { authorizationFor, identityHeaders, isDevelopment } from '@/lib/auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { token, localUser } = await authorizationFor(request);
if (!token)
return NextResponse.redirect(
new URL(`/login?returnTo=${encodeURIComponent(request.nextUrl.pathname)}`, request.nextUrl.origin),
);
const { id } = await params;
const api = (process.env.WF_API_URL ?? 'http://127.0.0.1:4000').replace(/\/$/, '');
try {
const response = await fetch(`${api}/v1/workspaces/${encodeURIComponent(id)}/launch`, {
method: 'POST',
headers: { ...identityHeaders(token, localUser), 'Content-Type': 'application/json' },
body: JSON.stringify({}),
cache: 'no-store',
redirect: 'error',
signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]),
});
if (!response.ok)
return NextResponse.json(
{
error: {
code: 'IDE_LAUNCH_DENIED',
message: response.status === 403 ? '你没有权限打开此工作空间。' : '工作空间尚未就绪或控制面拒绝了连接。',
},
},
{ status: response.status, headers: { 'Cache-Control': 'no-store' } },
);
const payload = (await response.json()) as {
data?: { launchUrl?: string; expiresIn?: number };
};
if (typeof payload.data?.launchUrl !== 'string' || payload.data.expiresIn !== 30)
throw new Error('Invalid workspace launch response');
// The authenticated control plane resolves the tenant's gateway and verifies
// its origin. This BFF never owns tenant routing or gateway service tokens.
const url = new URL(payload.data.launchUrl);
const localHttp =
isDevelopment() && url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
const query = [...url.searchParams.keys()];
if (
(url.protocol !== 'https:' && !localHttp) ||
url.username ||
url.password ||
url.hash ||
url.pathname !== '/session' ||
query.length !== 1 ||
query[0] !== 'code' ||
!/^[A-Za-z0-9_-]{20,256}$/.test(url.searchParams.get('code') ?? '')
)
throw new Error('Invalid workspace session redirect');
const result = NextResponse.redirect(url, 303);
result.headers.set('Cache-Control', 'no-store');
result.headers.set('Referrer-Policy', 'no-referrer');
return result;
} catch {
return NextResponse.json(
{
error: {
code: 'IDE_UNAVAILABLE',
message: '无法取得工作空间启动链接。请检查控制面与运行环境配置。',
},
},
{ status: 503, headers: { 'Cache-Control': 'no-store' } },
);
}
}

View File

@ -1,6 +1,6 @@
'use client';
import Link from 'next/link';
import { ArrowRight, CircleAlert, GitBranch, Laptop, Plus, Settings2 } from 'lucide-react';
import { ArrowRight, CircleAlert, GitBranch, Plus, Settings2 } from 'lucide-react';
import { formatNumber, useResource } from '@/lib/api';
import { resourceState } from '@/lib/readiness';
import type { Dashboard } from '@/lib/types';
@ -151,10 +151,10 @@ export function DashboardView() {
},
{
number: '03',
Icon: Laptop,
title: '打开云 IDE',
text: '在云端开发环境中构建与协作。',
href: '/projects',
Icon: Plus,
title: '提交第一个愿望',
text: '写下目标和验收标准,Agent 实现后经验证合入。',
href: '/runs/new',
},
].map(({ number, Icon, title, text, href }) => (
<Link href={href} key={number}>

View File

@ -1,10 +1,10 @@
'use client';
import { useRef, useState } from 'react';
import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowRight, ArrowUpRight, FolderGit2, GitBranch, Laptop, Plus, Search, Settings2 } from 'lucide-react';
import { ArrowRight, ArrowUpRight, FolderGit2, GitBranch, Plus, Search, Settings2 } from 'lucide-react';
import { formatTime, messageOf, mutateApi, safeUrl, useResource } from '@/lib/api';
import type { IdeBranch, Identity, Project, Run, Workspace } from '@/lib/types';
import type { Identity, Project, Run } from '@/lib/types';
import {
Button,
ButtonLink,
@ -24,7 +24,6 @@ import { RunTable } from '@/components/run-table';
import { ProjectSettings } from './project-settings';
import { LessonsPanel } from './lessons';
import { SkillsPanel } from './skills';
import { browserId } from '@/lib/browser-id';
export function ProjectsView({ create = false }: { create?: boolean }) {
const { data, error, isLoading, mutate } = useResource<Project[]>('/projects');
const [search, setSearch] = useState('');
@ -171,8 +170,6 @@ export function ProjectView({ id }: { id: string }) {
const mayWish = identity.data?.permissions?.wish !== 'none';
const projects = useResource<Project[]>('/projects');
const runs = useResource<Run[]>(`/runs?project=${id}`, 10000);
const workspaces = useResource<Workspace[]>(`/projects/${id}/workspaces`, 10000);
const branches = useResource<IdeBranch[]>(`/projects/${id}/branches`, 30000);
const projectResource = useResource<Project>(`/projects/${id}`);
const project = projectResource.data ?? projects.data?.find(item => item.id === id);
const [showSettings, setShowSettings] = useState(false);
@ -190,18 +187,6 @@ export function ProjectView({ id }: { id: string }) {
setBusy(false);
}
}
async function createWorkspace() {
setBusy(true);
setActionError('');
try {
await mutateApi(`/projects/${id}/workspaces`, {});
await workspaces.mutate();
} catch (error) {
setActionError(messageOf(error));
} finally {
setBusy(false);
}
}
if (projects.isLoading) return <Loading />;
if (projects.error) return <ErrorNotice error={projects.error} retry={() => void projects.mutate()} />;
if (!project)
@ -239,139 +224,76 @@ export function ProjectView({ id }: { id: string }) {
</div>
}
/>
<div className="detail-columns">
<Panel title="代码仓库">
<dl className="details-list">
<KeyValue label="仓库">
{safeUrl(project.repositoryUrl) ? (
<a
className="text-link break-all"
href={safeUrl(project.repositoryUrl)}
target="_blank"
rel="noreferrer"
>
{project.repositoryUrl}
<ArrowUpRight size={15} />
</a>
) : (
(project.repositoryUrl ?? '尚未关联')
)}
</KeyValue>
<KeyValue label="目标分支">
<span className="inline-icon">
<GitBranch size={15} />
{project.targetBranch}
</span>
</KeyValue>
<KeyValue label="仓库状态">
<Status
value={
project.repositoryStatus === 'ready'
? 'ready'
: project.repositoryStatus === 'unavailable'
? 'failed'
: 'unconfigured'
}
label={
{ ready: '可用', unavailable: '不可用', unconfigured: '未创建' }[project.repositoryStatus ?? 'ready']
}
/>
</KeyValue>
<KeyValue label="代码权限">
{project.codeReview?.paths.length ? (
<>
后端代码 <code>{project.codeReview.paths.join('、')}</code>
{project.codeReview.exceptPaths.length ? (
<>
(放行 <code>{project.codeReview.exceptPaths.join('、')}</code>)
</>
) : null}
算后端代码:只能改前端的人碰不到它,其他人改到它时按各自的权限直接合入或先审核(见
<Link className="text-link" href="/members">
成员与权限
</Link>
)
</>
) : (
'不区分前后端,验证通过后直接合入'
)}
</KeyValue>
<KeyValue label="创建时间">{formatTime(project.createdAt)}</KeyValue>
<KeyValue label="项目 ID">
<code>{project.id}</code>
</KeyValue>
</dl>
{project.repositoryStatus && project.repositoryStatus !== 'ready' ? (
<>
<Notice tone="warning">
{project.repositoryError ?? '平台 Git 仓库尚未创建,提交的愿望会等待仓库就绪。'}
</Notice>
<div className="panel-bottom-action">
<Button variant="secondary" busy={busy} onClick={() => void retryRepository()}>
重试创建仓库
</Button>
</div>
</>
) : null}
</Panel>
<Panel title="云 IDE" aside={<Laptop size={19} />}>
<p className="panel-intro">
在 IDE 中提交并推送到 <code>ide/</code> 开头的分支(默认 <code>ide/work</code>),再从该分支提交愿望:
验证通过后连同 Agent 的改动一起合入 {project.targetBranch}。
</p>
{branches.data?.length ? (
<ul className="branch-list">
{branches.data.map(branch => (
<li key={branch.name}>
<GitBranch size={15} />
<code>{branch.name}</code>
<span>
{branch.commit.slice(0, 7)} · {formatTime(branch.updatedAt)}
</span>
{mayWish ? (
<ButtonLink secondary href={`/runs/new?project=${id}&branch=${encodeURIComponent(branch.name)}`}>
提交愿望合入
</ButtonLink>
) : null}
</li>
))}
</ul>
) : null}
{workspaces.data?.length ? (
<div className="workspace-list">
{workspaces.data.map(workspace => (
<WorkspaceRow
key={workspace.id}
workspace={workspace}
onChanged={async updated => {
await workspaces.mutate(
current => current?.map(item => (item.id === updated.id ? { ...item, ...updated } : item)),
{ revalidate: false },
);
void workspaces.mutate();
}}
/>
))}
<Panel title="代码仓库">
<dl className="details-list">
<KeyValue label="仓库">
{safeUrl(project.repositoryUrl) ? (
<a className="text-link break-all" href={safeUrl(project.repositoryUrl)} target="_blank" rel="noreferrer">
{project.repositoryUrl}
<ArrowUpRight size={15} />
</a>
) : (
(project.repositoryUrl ?? '尚未关联')
)}
</KeyValue>
<KeyValue label="目标分支">
<span className="inline-icon">
<GitBranch size={15} />
{project.targetBranch}
</span>
</KeyValue>
<KeyValue label="仓库状态">
<Status
value={
project.repositoryStatus === 'ready'
? 'ready'
: project.repositoryStatus === 'unavailable'
? 'failed'
: 'unconfigured'
}
label={
{ ready: '可用', unavailable: '不可用', unconfigured: '未创建' }[project.repositoryStatus ?? 'ready']
}
/>
</KeyValue>
<KeyValue label="代码权限">
{project.codeReview?.paths.length ? (
<>
后端代码 <code>{project.codeReview.paths.join('、')}</code>
{project.codeReview.exceptPaths.length ? (
<>
(放行 <code>{project.codeReview.exceptPaths.join('、')}</code>)
</>
) : null}
算后端代码:只能改前端的人碰不到它,其他人改到它时按各自的权限直接合入或先审核(见
<Link className="text-link" href="/members">
成员与权限
</Link>
)
</>
) : (
'不区分前后端,验证通过后直接合入'
)}
</KeyValue>
<KeyValue label="创建时间">{formatTime(project.createdAt)}</KeyValue>
<KeyValue label="项目 ID">
<code>{project.id}</code>
</KeyValue>
</dl>
{project.repositoryStatus && project.repositoryStatus !== 'ready' ? (
<>
<Notice tone="warning">
{project.repositoryError ?? '平台 Git 仓库尚未创建,提交的愿望会等待仓库就绪。'}
</Notice>
<div className="panel-bottom-action">
<Button variant="secondary" busy={busy} onClick={() => void retryRepository()}>
重试创建仓库
</Button>
</div>
) : (
<>
<Notice>尚无可用的 IDE 会话。需要先连接支持工作空间的运行环境。</Notice>
<div className="panel-bottom-action">
<Button variant="secondary" busy={busy} onClick={createWorkspace}>
<Plus size={16} />
创建开发环境
</Button>
</div>
</>
)}
{workspaces.error ? (
<p className="field-hint">
{workspaces.error.status === 404 ? '工作空间服务尚未启用。' : workspaces.error.message}
</p>
) : null}
<FormError message={actionError} />
</Panel>
</div>
</>
) : null}
<FormError message={actionError} />
</Panel>
<Panel
title="项目运行"
aside={
@ -404,130 +326,3 @@ export function ProjectView({ id }: { id: string }) {
</>
);
}
function WorkspaceRow({
workspace,
onChanged,
}: {
workspace: Workspace;
onChanged: (workspace: Workspace) => Promise<void>;
}) {
const [confirmPause, setConfirmPause] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const operationKey = useRef<{ action: 'pause' | 'resume'; key: string } | null>(null);
const managed = workspace.managedBy === 'wishforge-provisioner';
const reconciling = ['waiting', 'pausing', 'resuming', 'unknown'].includes(workspace.status);
function closePause() {
if (busy) return;
setConfirmPause(false);
setError('');
}
async function change(action: 'pause' | 'resume') {
if (busy || !managed) return;
if (action === 'pause' && workspace.status !== 'ready') {
setError('工作区状态已变化,请等待对账完成后重试。');
return;
}
if (operationKey.current?.action !== action) {
operationKey.current = { action, key: browserId() };
}
setBusy(true);
setError('');
try {
const updated = await mutateApi<Workspace>(
`/workspaces/${workspace.id}/lifecycle`,
{ action, confirmation: 'change-workspace-lifecycle' },
'POST',
operationKey.current.key,
);
if (
updated.id !== workspace.id ||
!['ready', 'paused', 'pausing', 'resuming', 'unknown'].includes(updated.status)
) {
throw new Error('控制面返回了无法确认的工作区状态,请刷新后核对。');
}
await onChanged(updated);
operationKey.current = null;
setConfirmPause(false);
} catch (error) {
setError(messageOf(error));
} finally {
setBusy(false);
}
}
return (
<div data-workspace-id={workspace.id}>
<div className="workspace-row">
<div>
<strong>开发环境</strong>
<Status value={workspace.status} label={reconciling ? '对账中' : undefined} />
{workspace.reason ? <p>{workspace.reason}</p> : null}
{reconciling ? <p role="status">工作区对账中,确认完成后才能打开 IDE。</p> : null}
{workspace.status === 'paused' ? <p>工作区已暂停,已保存的文件保留。</p> : null}
</div>
<div className="button-group">
{workspace.status === 'ready' ? (
<a
className="button button-secondary"
href={`/ide/${workspace.id}/launch`}
target="_blank"
rel="noreferrer"
>
打开 IDE
<ArrowUpRight size={15} />
</a>
) : !reconciling && workspace.status !== 'paused' ? (
<span className="muted text-small">环境尚未就绪</span>
) : null}
{managed && workspace.status === 'ready' ? (
<Button
variant="ghost"
disabled={busy}
onClick={() => {
setError('');
setConfirmPause(true);
}}
>
暂停工作区
</Button>
) : null}
{managed && workspace.status === 'paused' ? (
<Button variant="secondary" busy={busy} onClick={() => void change('resume')}>
恢复工作区
</Button>
) : null}
</div>
</div>
{!confirmPause ? <FormError message={error} /> : null}
{confirmPause ? (
<Modal
title="暂停这个工作区?"
description="暂停后工作区不再占用计算资源,恢复后可以继续使用。"
onClose={closePause}
>
<div className="form-stack">
<KeyValue label="工作区">
<code className="break-all">{workspace.id}</code>
</KeyValue>
<Notice>暂停会结束终端和调试进程,编辑器中未保存的修改会丢失;已保存的文件保留在工作区存储中。</Notice>
<FormError message={error} />
<div className="modal-actions">
<Button variant="secondary" disabled={busy} onClick={closePause}>
取消
</Button>
<Button
variant="danger"
busy={busy}
disabled={workspace.status !== 'ready'}
onClick={() => void change('pause')}
>
暂停工作区
</Button>
</div>
</div>
</Modal>
) : null}
</div>
);
}

View File

@ -27,7 +27,6 @@ import { downloadApi, formatTime, messageOf, mutateApi, safeUrl, shortId, useRes
import type {
CommandEvidence,
Evidence,
IdeBranch,
Identity,
RunArtifacts,
RunDelivery,
@ -432,7 +431,6 @@ export function NewWishView() {
const [chosenMaxTokens, setMaxTokens] = useState<number>();
const [maxMinutes, setMaxMinutes] = useState(30);
const [maxRepairRounds, setMaxRepairRounds] = useState(3);
const [sourceBranch, setSourceBranch] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [idempotencyKey] = useState(browserId);
@ -447,8 +445,6 @@ export function NewWishView() {
const query = new URLSearchParams(window.location.search);
const selected = query.get('project');
if (selected) setProjectId(selected);
const branch = query.get('branch');
if (branch) setSourceBranch(branch);
}, []);
const effectiveProject = projectId || projects.data?.[0]?.id || '';
const project = projects.data?.find(item => item.id === effectiveProject);
@ -469,8 +465,6 @@ export function NewWishView() {
const scope = wishScopeFor(identity.data, project);
const mayWish = scope !== 'none';
const maxTokens = chosenMaxTokens ?? (localPoc && provider === 'claude-code' ? 100000000 : 300000);
const branches = useResource<IdeBranch[]>(effectiveProject ? `/projects/${effectiveProject}/branches` : null);
const targetBranch = projects.data?.find(project => project.id === effectiveProject)?.targetBranch ?? 'main';
const selectedProvider = providers.data?.find(item => item.id === provider);
const providerReady = wishProviderReady(selectedProvider, providers.error, projects.error);
// Executors this deployment cannot run stay out of the way; the chosen one always shows.
@ -525,7 +519,6 @@ export function NewWishView() {
provider,
...(model ? { model } : {}),
budget: { maxTokens, maxMinutes, maxRepairRounds },
...(sourceBranch ? { sourceBranch } : {}),
...(scopePolicy ? { frontendOnly: frontendOnly || scope === 'frontend' } : {}),
},
'POST',
@ -556,7 +549,6 @@ export function NewWishView() {
value={effectiveProject}
onChange={event => {
setProjectId(event.target.value);
setSourceBranch('');
setProvider(undefined);
}}
>
@ -596,22 +588,6 @@ export function NewWishView() {
onChange={setFrontendOnly}
/>
) : null}
<Field
label="起点"
hint={`从 IDE 推送的分支开始时,Agent 在这些改动的基础上工作,验证通过后一并合入 ${targetBranch}。`}
>
<select value={sourceBranch} onChange={event => setSourceBranch(event.target.value)}>
<option value="">{targetBranch} 的最新代码</option>
{sourceBranch && !branches.data?.some(branch => branch.name === sourceBranch) ? (
<option value={sourceBranch}>{sourceBranch}</option>
) : null}
{branches.data?.map(branch => (
<option value={branch.name} key={branch.name}>
{branch.name} · {branch.commit.slice(0, 7)} · {formatTime(branch.updatedAt)}
</option>
))}
</select>
</Field>
<Field
label="验收标准"
hint="每行一条,写成能检查的句子。标准会交给 Agent,并在审核和审批时展示;能否通过以项目的受保护检查为准。"

View File

@ -192,9 +192,6 @@ export function UsageView() {
<KeyValue label="项目">
{formatNumber(entitlement.counts.projects)} / {formatNumber(entitlement.limits.maxProjects)}
</KeyValue>
<KeyValue label="工作区">
{formatNumber(entitlement.counts.workspaces)} / {formatNumber(entitlement.limits.maxWorkspaces)}
</KeyValue>
<KeyValue label="执行名额">
{formatNumber(entitlement.counts.reservedExecutionSlots)} /{' '}
{formatNumber(entitlement.limits.maxConcurrentRuns)}

View File

@ -170,8 +170,8 @@ describe('local operator browser boundary', () => {
vi.stubEnv('WF_LOCAL_ALLOWED_ORIGINS', '');
expect(localRequestAllowed(request())).toBe(false);
});
it('protects pages, API reads, streams, IDE and callback routes while leaving login and bundles accessible', async () => {
for (const path of ['/', '/runs/new', '/ide/id/launch', '/login/callback']) {
it('protects pages, API reads, streams and callback routes while leaving login and bundles accessible', async () => {
for (const path of ['/', '/runs/new', '/login/callback']) {
const result = await proxy(request(path));
expect(result.status).toBe(307);
expect(new URL(result.headers.get('location')!).pathname).toBe('/login');

View File

@ -37,8 +37,6 @@ export type Project = {
export type { ProviderId } from '@wishforge/contracts';
import type { ProviderId } from '@wishforge/contracts';
import type { AccountType, Permissions } from '@wishforge/contracts/permissions';
/** A branch people pushed from the IDE; a wish starting from it verifies and merges it. */
export type IdeBranch = { name: string; commit: string; updatedAt: string };
export type Run = {
id: string;
projectId: string;
@ -209,19 +207,6 @@ export type ProviderConnection = {
status: string;
createdAt: string;
};
export type Workspace = {
managedBy?: 'wishforge-provisioner' | 'local-provisioner';
lifecycle?: {
revision: number;
desired: 'paused' | 'running';
state: 'queued' | 'unknown' | 'observing' | 'complete';
};
id: string;
projectId: string;
status: 'unconfigured' | 'requested' | 'ready' | 'pausing' | 'paused' | 'resuming' | 'unknown';
url?: string;
reason?: string;
};
export type Lesson = {
id: string;
projectId: string;

View File

@ -21,8 +21,7 @@ export const waitingGuides: Record<WaitingReason, WaitingGuide> = {
},
git_storage: {
title: '项目仓库未就绪',
action:
'在项目页重试仓库创建或改用可访问的 HTTPS 仓库;起点分支不存在时,先在 IDE 中推送这个分支。然后点击「继续」。',
action: '在项目页重试仓库创建或改用可访问的 HTTPS 仓库;起点分支不存在时,先推送这个分支。然后点击「继续」。',
link: project,
resumable: true,
},

View File

@ -4,7 +4,7 @@ WorkBuddy、Codex 等客户端通过 MCP(Streamable HTTP)接入,以登录
- 地址:本地为 `http://127.0.0.1:4000/mcp`,生产为 API 的 HTTPS 地址加 `/mcp`(不是 `/api/mcp`)。
- 认证:OAuth(授权码 + PKCE)。未认证请求返回 401,`WWW-Authenticate` 中给出受保护资源元数据地址 `/.well-known/oauth-protected-resource`,其中列出授权服务器。本地授权服务器是 Keycloak:`http://127.0.0.1:4100/realms/wishforge`(发现文档在 `/realms/wishforge/.well-known/openid-configuration`)。令牌的 issuer、有效期与 `wishforge-api` audience 都会校验,租户成员资格与工具权限在服务端检查。
- 工具:`list_projects`、`submit_wish`、`get_run`、`get_run_events`、`answer_question`、`control_run`、`get_delivery`、`request_release`。工具与 Web 共用同一套领域逻辑;通过工具做出的修改在审计中记为真实用户。`submit_wish` 可以带 `sourceBranch`(例如在 IDE 中推送的 `ide/work`),运行从这个分支开始,验证后合入目标分支。
- 工具:`list_projects`、`submit_wish`、`get_run`、`get_run_events`、`answer_question`、`control_run`、`get_delivery`、`request_release`。工具与 Web 共用同一套领域逻辑;通过工具做出的修改在审计中记为真实用户。`submit_wish` 可以带 `sourceBranch`(例如自己推送到项目仓库的分支),运行从这个分支开始,验证后合入目标分支。
## Codex

View File

@ -11,7 +11,6 @@ flowchart LR
subgraph Clients[入口]
Web[Web 工作台<br/>apps/web]
MCPC[WorkBuddy / Codex<br/>MCP 客户端]
IDE[云 IDE 浏览器]
end
subgraph Control[控制面]
API[控制面 API<br/>apps/api]
@ -31,14 +30,10 @@ flowchart LR
RUN[Runner<br/>apps/runner]
APP[应用]
end
GW[IDE 网关<br/>apps/ide/gateway]
THEIA[Theia 工作区]
LLM[模型服务商]
Web -->|BFF /api → /v1| API
MCPC -->|/mcp OAuth| API
IDE --> GW --> THEIA
GW -->|授权| API
API --- PG
API -->|outbox 派发| PROV
API -->|signalWithStart| TMP
@ -64,8 +59,8 @@ flowchart LR
| 组件 | 目录 | 职责 |
|---|---|---|
| Web 工作台 | `apps/web` | Next.js App Router。BFF:OIDC 会话(加密 Cookie)、`/api/*` 代理到 API 的 `/v1/*`、IDE 启动跳转。页面:概览、项目、运行、发布与审批、环境、执行器、用量。 |
| 控制面 API | `apps/api` | NestJS(Express)。`/v1`(人与连接器)、`/internal`(执行身份)、`/mcp`、`/provider-proxy`、`/health` `/readyz` `/metrics`。领域逻辑在 `src/domain`,后台循环:派发器、资源回收、工作区生命周期。 |
| Web 工作台 | `apps/web` | Next.js App Router。BFF:OIDC 会话(加密 Cookie)、`/api/*` 代理到 API 的 `/v1/*`。页面:概览、项目、运行、发布与审批、环境、执行器、用量。 |
| 控制面 API | `apps/api` | NestJS(Express)。`/v1`(人与连接器)、`/internal`(执行身份)、`/mcp`、`/provider-proxy`、`/health` `/readyz` `/metrics`。领域逻辑在 `src/domain`,后台循环:派发器、资源回收。 |
| 契约 | `packages/contracts` | 领域类型、zod 输入校验、错误类型、等待原因枚举、规范化 JSON(签名与摘要的唯一实现)。 |
| Agent 配置 | `packages/agent` | Agent 配置(Bundle)的 schema 与内容摘要、提示词组装(目标、验收标准、修复反馈、项目经验)。 |
| Worker | `apps/worker` | Temporal worker,按角色运行:`coordinator`(工作流与状态同步)、`executor`(调用执行器)、`verifier`(验证、集成、构建)、`deployer`(创建发布)。 |
@ -73,9 +68,8 @@ flowchart LR
| 平台 Git | `apps/git-service` | Smart HTTP Git 服务;仓库范围、读写分离的短期令牌。 |
| GitHub | `packages/github` | GitHub App 客户端:安装令牌、PR、合并。 |
| 产物存储 | `packages/artifacts` | S3 兼容的内容寻址存储,用于检查点 bundle。 |
| Provisioner | `apps/provisioner` | 为运行代次创建 executor/verifier,为 IDE 创建工作区。两个后端:`local`(开发,宿主机进程)与 `kubernetes`(生产,Kata Job + PVC)。 |
| Provisioner | `apps/provisioner` | 为运行代次创建 executor/verifier。两个后端:`local`(开发,宿主机进程)与 `kubernetes`(生产,Kata Job + PVC)。 |
| Runner | `apps/runner` | 部署在目标环境侧,主动拉取 Ed25519 签名的部署任务并回报结果。 |
| IDE | `apps/ide` | Theia 1.76 应用、策略扩展(扩展白名单)、鉴权网关(`gateway/`)、按工作区隔离的 OCT 协作(`collaboration/`)。 |
## 3. 运行状态机
@ -248,18 +242,9 @@ sequenceDiagram
- Runner 拉取任务时,跳过已经失效的就绪发布(运行取消、需求或代码变化、配置或审批失效),把它标记为失败并让对应运行回到等待,后面的发布照常部署;运行暂停中的就绪发布保留,继续运行后可能重新有效。
- 审批 24 小时内有效;过期后发布失败,运行可以继续并重新请求发布。
### 4.5 云 IDE
### 4.5 从已有分支开始的愿望
1. 用户在项目页请求工作区:API 写入 workspace 记录与 outbox(`workspace.provision`)。
2. 派发器调用 provisioner `POST /workspaces`,平台托管仓库的项目同时带上仓库地址:`kubernetes` 后端创建 Kata Deployment、PVC、Service 与 NetworkPolicy(入站只允许网关;出站只有 DNS,有仓库时再放行平台 Git);`local` 后端返回本机 Theia 地址。
3. 用户点击「打开 IDE」:Web 调用 API `/v1/workspaces/:id/launch`,API 向网关申请一次性启动码,浏览器跳转网关 `/session?code=`。
4. 网关为每个 HTTP 请求与 WebSocket 连接向 API 校验成员资格与角色,并定期复核已打开的连接;撤销后立即断开。
5. 会话建立后,网关以该用户的身份向 API 申请 15 分钟的仓库写令牌(`/internal/workspaces/:id/git-credential`,每次都复核成员资格与角色),交给工作区后端(Theia 策略扩展的 `/wishforge-internal/git-credential`,需要只有网关持有的 Theia 连接令牌,浏览器无法经网关访问该路径)。后端把令牌写进仓库之外的 Git 配置片段(Kubernetes 中是内存卷),由克隆通过 `include.path` 引用;首次收到时把目标分支克隆到以项目命名的文件夹。会话期间网关在令牌到期前 5 分钟续期,没有人打开 IDE 时令牌自然过期。
6. IDE 与 Agent 之间只通过 Git commit 交接,人的改动也要经过验证才进入目标分支:
- **推送范围**:IDE 的令牌只能推送 `ide/` 开头的分支。平台 Git 用 pre-receive 钩子执行这条限制,克隆默认在 `ide/work` 分支上工作。
- **合入**:愿望可以指定起点分支(`sourceBranch`),运行从该分支的最新提交开始,Agent 在这些改动上继续工作。之后的验证、修复与合入照常进行:目标分支是起点的祖先时快进,否则合并后重新验证,冲突按修复轮处理。发布风险按目标分支合入前后的全部差异计算,包括起点分支带来的提交。
- **提交身份**:取最近打开会话的用户(OIDC 的 name/email),可以用 `git config` 覆盖。
- **外部仓库**:如 GitHub 的仓库不克隆,那里的改动应走 PR。
愿望可以指定起点分支(API 与 MCP 的 `sourceBranch`,例如自己推送到项目仓库的分支),运行从该分支的最新提交开始,Agent 在这些改动上继续工作。之后的验证、修复与合入照常进行:目标分支是起点的祖先时快进,否则合并后重新验证,冲突按修复轮处理。发布风险按目标分支合入前后的全部差异计算,包括起点分支带来的提交。人的改动因此也要经过验证才进入目标分支。工作台不提供选择起点的入口。
### 4.6 经验沉淀与 Agent 配置
@ -303,7 +288,6 @@ PostgreSQL,所有租户数据表都启用强制行级安全(`app.tenant_id`
| `environment` | 类型、架构、是否生产、配置版本、密钥引用、应用地址、当前与活跃发布 |
| `release` / `approval` | 发布绑定与状态;审批绑定摘要、过期时间、决定人 |
| `runner` / `runner_task` | Runner 注册(令牌哈希)、签名任务与回执 |
| `workspace` | IDE 工作区状态、上游地址、生命周期 |
| `provider_connection` | 加密的 BYOK 凭据 |
| `provider_proxy_request` | 模型代理请求的预留、结算与结果 |
| `github_operation` | PR 与合并操作 |
@ -321,11 +305,11 @@ PostgreSQL,所有租户数据表都启用强制行级安全(`app.tenant_id`
|---|---|---|
| `/v1/*` | Web BFF、脚本 | OIDC access token(`azp` 等于 Web 客户端时为 human,否则为 connector);开发模式可用开发令牌 |
| `/mcp` | WorkBuddy、Codex 等 | OIDC access token,身份固定为 connector |
| `/internal/*` | worker、verifier、deployer、Runner、IDE 网关 | 运行级 JWT、静态服务令牌(限定租户与路由)、Runner 令牌、网关令牌 |
| `/internal/*` | worker、verifier、deployer、Runner | 运行级 JWT、静态服务令牌(限定租户与路由)、Runner 令牌 |
| `/provider-proxy/v1/*` | 执行器中的 Codex | 运行级模型代理令牌 |
| `/health`、`/readyz`、`/metrics` | 探针、Prometheus | `/metrics` 需要监控令牌 |
`/v1` 主要资源:`projects`(含 `repository`、`workspaces`、`wishes`、`wish-refinements`、`lessons`、`github`、`verification-profile`)、`runs`(含 `events`、`events/stream`、`commands`、`delivery`、`provider-requests`、`code-review`、`revert`)、`lessons`、`releases`(含 `review`、`rollback`)、`approvals`、`environments`(含 `runners`、`application-url`、`deployment-secrets`、`release-policy`、`unlock`)、`local-accounts`(本机部署)、`capabilities`、`workspaces`(`launch`、`lifecycle`)、`provider-connections`、`providers`、`agent-bundles`、`verification-profiles`、`entitlements`、`plans`、`usage`(含 `lines`、`export`)、`admin`。运行列表支持 `project`、`limit`(默认 100,最多 500)与游标 `before`(上一页最后一条的 `createdAt`);其他列表按项目权限过滤后返回。
`/v1` 主要资源:`projects`(含 `repository`、`wishes`、`wish-refinements`、`lessons`、`github`、`verification-profile`)、`runs`(含 `events`、`events/stream`、`commands`、`delivery`、`provider-requests`、`code-review`、`revert`)、`lessons`、`releases`(含 `review`、`rollback`)、`approvals`、`environments`(含 `runners`、`application-url`、`deployment-secrets`、`release-policy`、`unlock`)、`local-accounts`(本机部署)、`capabilities`、`provider-connections`、`providers`、`agent-bundles`、`verification-profiles`、`entitlements`、`plans`、`usage`(含 `lines`、`export`)、`admin`。运行列表支持 `project`、`limit`(默认 100,最多 500)与游标 `before`(上一页最后一条的 `createdAt`);其他列表按项目权限过滤后返回。
MCP 工具:`list_projects`、`submit_wish`、`get_run`、`get_run_events`、`answer_question`、`control_run`、`get_delivery`、`request_release`。工具与 `/v1` 共用同一套领域逻辑与授权;连接器不能执行人工审批、凭据与环境管理。
@ -342,7 +326,6 @@ MCP 工具:`list_projects`、`submit_wish`、`get_run`、`get_run_events`、`a
| coordinator | 静态服务令牌(限定租户与路由) | 只能查询运行状态、记录等待、请求修复;不能取得执行租约 |
| deployer | 静态服务令牌(限定租户与路由) | 只能为已构建的运行取得租约、请求发布并推进到 release |
| runner | 每个环境一个令牌(数据库只存哈希,可轮换) | 拉取本环境的签名任务、回报结果 |
| IDE 网关 | 每租户网关令牌 | 签发工作区启动码、查询授权(首次凭用户的 access token,之后按已授权的用户复核)、为有编辑会话的用户申请工作区的仓库写令牌 |
权限:每个人有四项权限(`packages/contracts/src/permissions.ts`):许愿范围 `wish`(`none`、`frontend` 只改前端、`review` 前后端但后端改动要审核、`full` 前后端直接合入)、`reviewCode` 审核代码、`releases` 请求/审批/回滚发布(含 GitHub 合并授权)、`manage` 管理(包含其余全部)。本机部署的个人账号把权限存在 `local_account` 上,创建和修改时按六种账户类型(`admin`、`fullstack`、`reviewed`、`frontend`、`releaser`、`viewer`)或自定义组合给出,角色由权限推出(`manage`→admin,能许愿→developer,能审批发布→deployer,否则 viewer),其余按角色的检查不变;认证时权限随 Actor 带上,修改立即生效。没有个人权限的人(本机管理员、OIDC 用户、早于权限的旧账号)按角色取默认权限:owner/admin 全部,developer 为 `review`(项目的 `codeReview.trustedMembers` 可在该项目把它提到 `full`),deployer 只有 `releases`,viewer 什么都没有。
@ -370,9 +353,9 @@ Claude Code 以受限模式运行(`--restricted`,权限模式 `dontAsk`)
## 9. 部署拓扑
**本地开发**(详见 [development.md](development.md)):Compose 提供 PostgreSQL、Temporal、Keycloak、MinIO、镜像仓库;`npm run dev:all` 在宿主机启动 API、Web、平台 Git、coordinator/deployer worker 与 `local` provisioner;IDE 与网关按需启动。
**本地开发**(详见 [development.md](development.md)):Compose 提供 PostgreSQL、Temporal、Keycloak、MinIO、镜像仓库;`npm run dev:all` 在宿主机启动 API、Web、平台 Git、coordinator/deployer worker 与 `local` provisioner。
**生产**(详见 [operations.md](operations.md)):控制面(API、Web、Git、coordinator/deployer worker、provisioner、IDE 网关)运行在受信命名空间;运行沙箱与 IDE 工作区运行在独立命名空间的 Kata 节点池;PostgreSQL、Temporal、对象存储与密钥系统使用托管或高可用部署;Runner 部署在各目标环境。
**生产**(详见 [operations.md](operations.md)):控制面(API、Web、Git、coordinator/deployer worker、provisioner)运行在受信命名空间;运行沙箱运行在独立命名空间的 Kata 节点池;PostgreSQL、Temporal、对象存储与密钥系统使用托管或高可用部署;Runner 部署在各目标环境。
## 10. 关键决策
@ -384,14 +367,12 @@ Claude Code 以受限模式运行(`--restricted`,权限模式 `dontAsk`)
| ADR-4 | 部署通过出站 Runner 拉取签名任务 | 客户环境不需要开放入站端口,平台不持有客户集群凭据;代价是部署延迟取决于 Runner 轮询间隔。 |
| ADR-5 | Agent 客户端通过 MCP 接入 | WorkBuddy、Codex 等原生支持 MCP 与 OAuth,权限沿用用户身份,无需为每个客户端写适配。 |
| ADR-6 | RSI 限定在任务、项目与租户范围,晋升由人决定 | 自动的平台级元进化需要基准集、评估器与大量真实运行才有统计意义,在当前阶段不可验证,且有跨租户数据风险。 |
| ADR-7 | IDE 与 Agent 只通过 Git commit 交接 | Git 已经提供精确、可审计的版本身份;IDE 快照、保存屏障等机制复杂且依赖 Theia 内部实现。 |
| ADR-8 | IDE 只推送 `ide/` 分支,由从该分支开始的愿望验证并合入;令牌由网关按会话投递 | 目标分支只经由验证器的合入改变,人工改动与 Agent 改动走同一条验证与发布风险评估路径,也能借助修复轮修好。代价是人工改动要多提交一次愿望才能进入目标分支。工作区自己不能签发凭据,令牌只在有人打开 IDE 时存在,最长 15 分钟。 |
| ADR-7 | ~~IDE 与 Agent 只通过 Git commit 交接~~(已随云 IDE 移除) | 云 IDE(Theia 工作区、IDE 网关、OCT 协作)已从 WishForge 中移除。 |
| ADR-8 | 人工改动经由从其分支开始的愿望验证并合入 | 目标分支只经由验证器的合入改变,人工改动与 Agent 改动走同一条验证与发布风险评估路径,也能借助修复轮修好。代价是人工改动要多提交一次愿望才能进入目标分支。原先 IDE 只能推送 `ide/` 分支、令牌由网关按会话投递的部分随云 IDE 移除。 |
## 11. 已知限制
- Temporal 连接使用客户端证书(生产必需),每个租户可以使用自己的命名空间(生产中多租户必需)。命名空间之间的授权依赖 Temporal 服务端按证书配置(见 operations.md 第 13 节)。同一租户的沙箱之间没有按任务队列的授权。
- OCT 协作房间保存在内存中,服务重启后需要重新创建房间;已保存的文件不受影响。
- Theia 后端与终端共用同一个 UID,同一工作区内的协作者之间没有强隔离;工作区只应授予可信成员编辑权限。
- Temporal 连接使用客户端证书(生产必需),每个租户可以使用自己的命名空间(生产中多租户必需)。命名空间之间的授权依赖 Temporal 服务端按证书配置(见 operations.md 第 12 节)。同一租户的沙箱之间没有按任务队列的授权。
- `host` 沙箱模式没有任何隔离,只能用于本机开发,并且只能运行你信任的代码与模型。macOS 上运维可以用 `WF_HOST_CHECK_SANDBOX=true` 让受保护检查与依赖安装在 Seatbelt 中运行(主目录内容不可读、只能写工作区与放行的缓存、检查没有网络、平台服务端口始终封锁),证据标记 `checkSandbox: seatbelt`;它不隔离执行器与验证器进程本身,证据仍是 `isolation: host`,生产不接受。上线前在目标机器上运行 `scripts/check-host-check-sandbox.ts` 验收。
- macOS 上,Claude Code 命令沙箱的 Seatbelt 配置固定允许访问系统安全服务(`com.apple.SecurityServer`),所以沙箱中的命令可以查询登录钥匙串:信任 `security` 工具的条目可以被读取,其他条目会弹出授权提示。需要更强的隔离时,用单独的 macOS 用户运行本机服务,或者不打开 `WF_CLAUDE_COMMAND_SANDBOX`。
@ -416,9 +397,8 @@ Claude Code 以受限模式运行(`--restricted`,权限模式 `dontAsk`)
| FR-D5 | `tests/provider-proxy.test.ts` |
| FR-J1、FR-J2 | `tests/entitlements-usage.test.ts`、`tests/control-plane.test.ts`(暂停释放预留) |
| FR-K2 | `tests/migrations.test.ts`;CI 的 PostgreSQL 任务连续执行两次迁移 |
| FR-H1 | `apps/ide/gateway/test/gateway.test.mjs`、`apps/ide/gateway/test/gateway-handler.test.mjs`、`tests/internal-auth.test.ts` |
| FR-C4 | `tests/local-loop.test.ts`(提问 → 等待澄清 → 回答 → 完成)、`packages/agent/test/prompt.test.ts` |
| FR-H2 | `apps/ide/policy/test/git-workspace.test.cjs`(克隆、令牌、`ide/work`)、`apps/ide/gateway/test/gateway-handler.test.mjs`(凭据投递)、`tests/workspace-git.test.ts`、`apps/git-service/test/hooks.test.ts`(`ide/` 推送范围)、`tests/local-loop.test.ts`(IDE 分支经愿望验证合入,发布风险覆盖分支带来的改动) |
| FR-H2(仅起点分支) | `tests/local-loop.test.ts`(从已推送分支开始的愿望验证并合入,发布风险覆盖分支带来的改动) |
| FR-K5 | `tests/service-build.test.ts`(构建全部服务并确认每个产物都能加载) |
| FR-D7 | `packages/runtime/test/runtime.test.ts`(执行器事件)、`tests/local-loop.test.ts`(事件记录) |
| FR-K1 | `apps/provisioner/test/local.test.mjs`(本地执行环境);完整的本地启动按 development.md 手动验证 |

View File

@ -251,7 +251,7 @@ kubectl --kubeconfig ~/.config/droboticflow/kubeconfigs/poc.config -n wishforge
## 已知限制
- IDE(Theia、OCT)没有迁移,集群版网页上的 IDE 入口不可用。
- 云 IDE(Theia、OCT)已从 WishForge 中移除,集群版不再有 IDE 入口。
- 检查 Pod 有网络(见上文)。
- **数据和快照都在同一个节点的同一块本地盘上**。快照能防误删、误改和软件故障,但节点或磁盘损坏时数据和快照会一起丢失;集群里没有可跨节点挂载的存储(没有 StorageClass),目前没有异地副本。
- Temporal 使用开发服务,Web UI 已关闭。

View File

@ -79,33 +79,11 @@ Temporal 控制台在 http://127.0.0.1:8233,可以看到每个运行的工作
每个运行代次的工作目录默认位于 `~/.local/share/wishforge/runs/<租户>/<运行>/<代次>/`,executor 与 verifier 各自使用独立的子目录和令牌。`WF_LOCAL_RUN_ROOT` 可以改到别处,但不能放在本仓库目录下:Node/TypeScript 会沿父目录查找依赖,项目会意外继承平台的类型定义,本地 provisioner 会拒绝这种配置。
## 5. 云 IDE(可选)
Theia 是独立安装的应用,首次构建需要几分钟并会下载扩展:
```bash
npm run ide:install
```
```bash
npm run ide:build
```
启动 Theia(端口 4300)与 IDE 网关(端口 4400):
```bash
npm run dev:ide
```
在项目页点击「创建开发环境」,本地 provisioner 会把工作区指向本机的 Theia(Theia 未启动时工作区显示为准备中);就绪后点击「打开 IDE」。本地模式下所有工作区共用同一个 Theia 实例和 `.wishforge/ide-workspace` 目录:第一次打开某个项目的工作区时,项目被克隆到其中以项目命名的文件夹,并处在 `ide/work` 分支上。在 IDE 中提交并 `git push` 后,在项目页的 IDE 分支列表点「提交愿望合入」,运行会从这个分支开始,验证通过后合入目标分支。令牌只在 IDE 打开期间有效,只能推送 `ide/` 开头的分支。
多人协作需要额外启动 OCT 服务,见 [apps/ide/collaboration/README.md](../apps/ide/collaboration/README.md)。
## 6. 通过 MCP 从 Codex / WorkBuddy 许愿
## 5. 通过 MCP 从 Codex / WorkBuddy 许愿
本地 MCP 地址为 `http://127.0.0.1:4000/mcp`,使用 Keycloak(http://127.0.0.1:4100,realm `wishforge`)做 OAuth。客户端配置见 [connectors/README.md](../connectors/README.md)。
## 7. 测试与检查
## 6. 测试与检查
| 命令 | 内容 |
|---|---|
@ -113,7 +91,6 @@ npm run dev:ide
| `npm run typecheck` | 全部 workspace 与测试代码的类型检查 |
| `npm run build:services` | 把 API、worker、Runner 与平台 Git 编译到 `dist/`(镜像运行的就是这些产物;`npm test` 会构建一次并检查每个产物都能加载) |
| `npm test` | 单元测试、进程内集成测试与 provisioner 的 Node 测试(不需要外部服务) |
| `npm run test:ide` | IDE 网关、协作服务与策略扩展的 Node 测试(需要先 `npm run ide:install`) |
| `npm run test:integration` | 需要本地 Compose 服务的集成测试,见下表 |
集成测试默认跳过,必须显式开启,跳过不算通过:
@ -130,16 +107,16 @@ npm run dev:ide
两个手动脚本:
- `node infra/scripts/smoke.mjs`:检查本地 Compose 服务(PostgreSQL、Temporal、Keycloak、MinIO、镜像仓库、OCT)是否可用。
- `node infra/scripts/smoke.mjs`:检查本地 Compose 服务(PostgreSQL、Temporal、Keycloak、MinIO、镜像仓库)是否可用。
- `WF_COMPOSE_ACCEPTANCE=true WF_CADDY_BINARY=<caddy 路径> node --import tsx infra/scripts/compose-acceptance.mjs`:用真实 Docker、本地镜像仓库与 Caddy 验收 Runner 的 Compose 蓝绿部署。它会构建并推送测试镜像,然后部署、切换并回滚,还会验证部署密钥。
两个脚本都使用当前的 Docker 上下文,可以用 `WF_DOCKER_CONTEXT` 指定其他上下文。
CI(`.github/workflows/ci.yml`)在每次推送与合并请求时运行格式检查、类型检查、`npm test`,在 PostgreSQL 服务上执行两次迁移与集成测试,并运行 IDE 相关的 Node 测试。
CI(`.github/workflows/ci.yml`)在每次推送与合并请求时运行格式检查、类型检查、`npm test`,在 PostgreSQL 服务上执行两次迁移与集成测试。
在本地 k3s 上以 Kubernetes 方式运行整个平台(每次运行独立的 Pod、网络策略、模型代理),见 [local-k3s.md](local-k3s.md)。
## 8. 常见问题
## 7. 常见问题
- **运行停在「执行环境未就绪」**:确认本地 provisioner 已启动(`dev:all` 会启动它),并检查 `.env.local` 中的 `WF_PROVISIONER_URL`。
- **运行停在「验证未配置」**:项目没有验证命令。在项目设置中添加后点击「继续」。

View File

@ -48,24 +48,16 @@
<text x="72" y="80" class="item-desc">BFF 架构 / OIDC 单点登录 / 仪表盘与运行详情</text>
<!-- Item 2: MCP -->
<rect x="354" y="40" width="310" height="56" class="box client-box" />
<rect x="354" y="40" width="640" height="56" class="box client-box" />
<circle cx="378" cy="68" r="14" fill="#ccfbf1" />
<text x="378" y="73" fill="#0d9488" font-size="12" font-weight="bold" text-anchor="middle">M</text>
<text x="402" y="62" class="item-title">MCP 客户端集成</text>
<text x="402" y="80" class="item-desc">Codex / WorkBuddy 直接许愿与进度追踪</text>
<!-- Item 3: IDE -->
<rect x="684" y="40" width="310" height="56" class="box client-box" />
<circle cx="708" cy="68" r="14" fill="#e0e7ff" />
<rect x="702" y="62" width="12" height="12" rx="2" fill="none" stroke="#6366f1" stroke-width="2" />
<text x="732" y="62" class="item-title">云端 IDE (Theia 1.76)</text>
<text x="732" y="80" class="item-desc">沙箱环境直连 / OCT 协作 / 源码调试工作区</text>
</g>
<!-- Connectors from Clients to Control Plane -->
<path d="M 195 205 L 195 245" class="arrow-accent" marker-end="url(#arrowhead-accent)" />
<path d="M 510 205 L 510 245" class="arrow" marker-end="url(#arrowhead)" />
<path d="M 840 205 L 840 245" class="arrow" marker-end="url(#arrowhead)" />
<!-- 2. 控制面 (Control Plane) -->
<g transform="translate(40, 245)">

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View File

@ -35,7 +35,7 @@ npm run local:network -- --address 192.168.1.20 --apply
地址必须是当前网卡实际持有的 RFC1918 IPv4。工具只替换相同端口的旧 HTTP 局域网地址,保留回环及其他已有入口;不添加通配符,不修改登录凭据,不创建公网入口。默认只预览;`--apply` 将原配置备份到忽略提交的 `.wishforge/local-poc/network-backups/`,权限 `0600`,然后原子更新根目录 `.env.local`。其他配置保留不变。应用后重启服务,并用新地址登录、刷新项目列表验证。`npm run local:doctor` 可检查网络与服务状态,诊断不会自动授权新地址。
所有入口包括页面、API、事件流、IDE 启动、交付文件均经过本机会话检查。登录页、框架静态资源和站点图标允许未登录访问。`/api/session` 未登录返回 `401`,因此本机模式的启动探活使用 `/login`。
所有入口包括页面、API、事件流、交付文件均经过本机会话检查。登录页、框架静态资源和站点图标允许未登录访问。`/api/session` 未登录返回 `401`,因此本机模式的启动探活使用 `/login`。
## 登录与退出
@ -60,4 +60,4 @@ npx vitest run apps/web/src/lib/auth.test.ts apps/web/src/lib/local-access.test.
npm run typecheck -w @wishforge/web
```
覆盖凭据权限、密码校验、会话过期与轮换、dev token 隔离、Host/Origin 校验、未登录 API 与 IDE 保护、静态资源访问、全局登录限流及原有 OIDC 行为。
覆盖凭据权限、密码校验、会话过期与轮换、dev token 隔离、Host/Origin 校验、未登录 API 保护、静态资源访问、全局登录限流及原有 OIDC 行为。

View File

@ -11,7 +11,6 @@
| Codex 的命令沙箱 | 起不来(runc Pod 不允许 bubblewrap 创建用户命名空间),Codex 不带它运行,时间线的「Executor started」会注明 | 必须可用,否则运行停在 `infrastructure` 等待 |
| 服务之间 | 集群内 HTTP(`WF_ALLOW_INSECURE_HTTP=true`) | HTTPS 与 mTLS |
| 登录 | 开发令牌,没有 OIDC;Web 是 Next.js 的开发构建 | OIDC,Web 是生产构建 |
| IDE | 网关在 `localhost` 上经 HTTP 访问;工作区是普通 runc Pod | 网关使用 HTTPS 公网域名;工作区在 Kata 节点池 |
| 镜像 | 本地构建,推到虚拟机里的 `localhost:5000` | 私有仓库中经审阅的镜像 |
每次运行的 NetworkPolicy 照常生效(k3s 自带网络策略控制器):沙箱只能访问 DNS、API(含模型代理)、Temporal 与平台 Git。模型调用经集群内 API 的运行级代理转发到你配置的网关。
@ -19,7 +18,7 @@
## 前置条件
- macOS 上的 Colima 与 kubectl(`brew install colima kubectl`)。
- 虚拟机默认 6 CPU、12 GiB 内存、40 GiB 磁盘,可以用 `WF_K3S_CPUS`、`WF_K3S_MEMORY_GIB`、`WF_K3S_DISK_GIB` 调整。全部镜像(含 Theia)构建一次约占 10–15 GB。
- 虚拟机默认 6 CPU、12 GiB 内存、40 GiB 磁盘,可以用 `WF_K3S_CPUS`、`WF_K3S_MEMORY_GIB`、`WF_K3S_DISK_GIB` 调整。构建会占用虚拟机磁盘,`build` 结束时清理不再使用的镜像,构建缓存保留不超过 10 GB。
- 一个 OpenAI 兼容的模型网关,以及它的 Key 和模型名。Codex 使用流式 `/responses` 与函数工具调用,不是每个模型都支持:先用 `GET <网关>/v1/models` 列出模型,再挑一个试。例如经 LiteLLM 的网关上,`deepseek-v4-pro` 可用。
所有 kubectl 与 docker 命令都显式使用 `colima-wishforge` 上下文。生成的密钥与镜像 digest 保存在 `.wishforge/k3s/`(不进 Git)。几点环境上的注意事项:
@ -37,7 +36,7 @@
node scripts/k3s-local.mjs up
```
构建 API、worker、平台 Git、provisioner、Web 与 IDE(Theia 工作区、IDE 网关、协作服务)镜像并推送。第一次需要二三十分钟,主要花在 Theia 的依赖安装与构建上:
构建 API、worker、平台 Git、provisioner 与 Web 镜像并推送。第一次要下载基础镜像并安装依赖,耗时较长:
```bash
node scripts/k3s-local.mjs build
@ -81,7 +80,7 @@ Web 工作台随 `deploy` 一起部署在集群里,由它在集群内调用 AP
node scripts/k3s-local.mjs web
```
然后打开 <http://localhost:3100>,地址要完全一致:工作台只接受来自部署时登记的地址(`WF_PUBLIC_URL`)的修改请求,换成 `127.0.0.1` 打开,提交愿望等操作会被拒绝。端口与本地开发环境(`npm run dev:all` 的 3000 与 4400)错开,两者可以同时运行。端口被占用时 `web` 会直接报错,用 `WF_K3S_WEB_PORT=<端口>` 重新执行 `deploy`,`web` 就转发到新端口。每次 `deploy` 都会换掉 Web 的 Pod,端口转发随之断开,需要再执行一次 `web`。
然后打开 <http://localhost:3100>,地址要完全一致:工作台只接受来自部署时登记的地址(`WF_PUBLIC_URL`)的修改请求,换成 `127.0.0.1` 打开,提交愿望等操作会被拒绝。端口与本地开发环境(`npm run dev:all` 的 3000)错开,两者可以同时运行。端口被占用时 `web` 会直接报错,用 `WF_K3S_WEB_PORT=<端口>` 重新执行 `deploy`,`web` 就转发到新端口。每次 `deploy` 都会换掉 Web 的 Pod,端口转发随之断开,需要再执行一次 `web`。
集群里的 Web 是 Next.js 的开发构建(镜像构建参数 `WEB_BUILD=development`)。本地没有 OIDC,每个访问者都以开发令牌的身份登录。这种登录方式只存在于开发构建中,生产镜像是生产构建,不带它。
@ -91,22 +90,10 @@ Temporal 控制台:
kubectl --context colima-wishforge --namespace wishforge-control port-forward service/temporal 8233:8233
```
## IDE
IDE 网关随 `deploy` 一起部署,`web` 同时把它转发到 <http://localhost:3101>(端口可用 `WF_K3S_IDE_PORT` 修改,改后重新 `deploy`)。
1. 在工作台的项目页创建开发环境。provisioner 在 `wishforge-tenant-demo` 中为这个项目创建 Theia 工作区:一个 Deployment、一个 PVC 和一个协作 sidecar。第一次要拉取镜像,一两分钟后就绪。
2. 点「打开 IDE」,浏览器经网关进入工作区。
3. 平台托管的项目第一次打开时被克隆到以项目命名的文件夹,处在 `ide/work` 分支。提交后 `git push`,再在项目页从这个分支提交愿望,验证通过后它会合入目标分支,详见 [apps/ide/README.md](../apps/ide/README.md)。
- 工作区只能经网关访问:它的网络策略只放行带 `workspace-gateway` 标签的网关 Pod,出站只允许 DNS 与平台 Git。
- 30 分钟没有连接时工作区自动暂停(缩容到 0,文件保留在 PVC 中),在项目页可以恢复。
- 本地集群里平台 Git 与网关走 HTTP,provisioner 只在开发部署且 `WF_ALLOW_INSECURE_HTTP=true` 时接受;生产要求 HTTPS。
## 排查
- `kubectl --context colima-wishforge --namespace wishforge-control logs deployment/api` 查看 API;provisioner、`worker-coordinator` 同理。
- 沙箱 Job 在 `wishforge-tenant-demo` 命名空间,名称形如 `wf-<哈希>-executor` / `-verifier`;IDE 工作区也在这里,名称形如 `wf-ide-<哈希>`。运行进入等待或结束后,Job 会被释放,要看它的日志得趁运行还在进行。
- 沙箱 Job 在 `wishforge-tenant-demo` 命名空间,名称形如 `wf-<哈希>-executor` / `-verifier`。运行进入等待或结束后,Job 会被释放,要看它的日志得趁运行还在进行。
- 运行时间线(`smoke` 的输出,或 `GET /v1/runs/<id>/events`)记录 Agent 执行的每条命令及其退出码,模型请求经代理记账。
- `up` 在下载 k3s 时失败(GitHub 的下载偶尔中断):直接重新执行 `up`,它会先停下装了一半的虚拟机再重新启动。
- 改了设置(例如换模型)只需重新 `deploy`:读取设置与密钥的 Pod 带着它们的摘要,摘要变了就会滚动更新。

View File

@ -26,7 +26,7 @@ node scripts/local-poc-service.mjs start
## 入口与登录
本机入口为 `http://localhost:3000`;同一可达局域网的其他设备使用 `http://本机局域网IP:3000`。是否跨网可达由现有路由和防火墙决定。当前部署另有经批准的 Cloudflare 临时 HTTPS 隧道,地址以维护者提供的链接和私有入口白名单为准;它只代理 Web,不公开内部 API 或 IDE。
本机入口为 `http://localhost:3000`;同一可达局域网的其他设备使用 `http://本机局域网IP:3000`。是否跨网可达由现有路由和防火墙决定。当前部署另有经批准的 Cloudflare 临时 HTTPS 隧道,地址以维护者提供的链接和私有入口白名单为准;它只代理 Web,不公开内部 API。
本机管理员的登录凭据保存在 `.wishforge/local-access.json`,只允许本机当前用户读取(0600)。文件含用户名、密码和会话签名材料,不应上传到 Gitea、放入网页静态目录或复制到日志。文件不存在时可运行 `node scripts/setup-local-access.mjs` 创建;重复运行保留已有凭据。`.env.local` 的 `WF_LOCAL_ACCESS_FILE` 指向该文件的绝对路径。
@ -102,7 +102,7 @@ LaunchAgent 随当前用户登录运行,退出登录后停止;电脑关机
- 读不到主目录里的文件内容,只能读工作区和下面放行的路径(文件是否存在等元数据仍然可见,路径才能正常解析);
- 只能写工作区、下面放行的缓存,以及每条命令独享并在结束后删除的临时目录,任何时候都不能写工作区的 `.git`;
- 只有依赖安装能联网;检查没有网络,打开 `WF_HOST_CHECK_LOOPBACK` 后可以使用本机回环端口;
- 平台自己的服务端口(API、Temporal 及其网页、数据库、对象存储、provisioner、Git 服务、IDE、网页控制台)在任何情况下都连不上,启动时按 `.env.local` 中的地址自动列出,也可以用 `WF_HOST_CHECK_BLOCKED_PORTS` 补充;
- 平台自己的服务端口(API、Temporal 及其网页、数据库、对象存储、provisioner、Git 服务、网页控制台)在任何情况下都连不上,启动时按 `.env.local` 中的地址自动列出,也可以用 `WF_HOST_CHECK_BLOCKED_PORTS` 补充;
- 检查时钥匙串服务不应答。
1. 确认没有执行中的愿望,运行检查。它不调用模型,也不部署:先逐项确认上面这些限制在这台机器上生效,再在沙箱里对最近一次构建的 droboticflow 源码运行 POC 的安装和全部检查:

View File

@ -2,24 +2,24 @@
本文面向部署和运维 WishForge 的平台运维人员。本地开发见 [development.md](development.md),组件与信任模型见 [architecture.md](architecture.md)。
> 现状说明:仓库提供了生产所需的组件、镜像目标与 Kubernetes 基线(`infra/k8s/base`),但它们**尚未在真实集群上完成验收**(Kata 执行、网络隔离、Runner 部署与回滚、OAuth 客户端接入)。上线前请按第 12 节逐项验收。
> 现状说明:仓库提供了生产所需的组件、镜像目标与 Kubernetes 基线(`infra/k8s/base`),但它们**尚未在真实集群上完成验收**(Kata 执行、网络隔离、Runner 部署与回滚、OAuth 客户端接入)。上线前请按第 11 节逐项验收。
## 1. 生产前提
| 依赖 | 要求 |
|---|---|
| Kubernetes | 控制面命名空间 + 每个租户独立的运行/工作区命名空间;运行沙箱与 IDE 工作区所在节点池安装 Kata(`RuntimeClass`),CNI 必须执行 NetworkPolicy |
| Kubernetes | 控制面命名空间 + 每个租户独立的运行命名空间;运行沙箱所在节点池安装 Kata(`RuntimeClass`),CNI 必须执行 NetworkPolicy |
| PostgreSQL | 16 或以上,高可用并开启 PITR。迁移使用管理员连接(超级用户或带 `BYPASSRLS`),运行时使用 `wishforge_app`(非超级用户、`NOBYPASSRLS`) |
| Temporal | 生产持久化存储;必须开启 mTLS。多个租户共用一个集群时,每个租户一个命名空间,并由服务端按客户端证书授权命名空间(见第 13 节) |
| Temporal | 生产持久化存储;必须开启 mTLS。多个租户共用一个集群时,每个租户一个命名空间,并由服务端按客户端证书授权命名空间(见第 12 节) |
| 对象存储 | S3 兼容,开启 KMS 加密(`S3_SSE=aws:kms`),禁止公开访问 |
| 镜像仓库 | 私有仓库;所有镜像按 digest 引用 |
| 身份服务 | OIDC(Keycloak 或企业 IdP),Web 客户端与 MCP 客户端分别注册;Web 客户端需要签发 refresh token 才能自动续期会话 |
| 密钥系统 | Vault:KV v2 用于部署密钥,Transit(可选)用于 BYOK 加密 |
| 入口 | Web、API、IDE 网关的 TLS 与域名;Runner 到 API 的 mTLS |
| 入口 | Web、API 的 TLS 与域名;Runner 到 API 的 mTLS |
## 2. 部署模式
API、平台 Git、worker、provisioner 与 Runner 都要求显式设置 `WF_DEPLOYMENT_MODE`,未设置时拒绝启动;Web 与 IDE 网关只在明确为 `development` 时才启用开发便利(开发令牌、本机 HTTP),其他情况一律按生产处理。
API、平台 Git、worker、provisioner 与 Runner 都要求显式设置 `WF_DEPLOYMENT_MODE`,未设置时拒绝启动;Web 只在明确为 `development` 时才启用开发便利(开发令牌、本机 HTTP),其他情况一律按生产处理。
- `production`:拒绝开发令牌与 `host` 沙箱证据;要求 HTTPS、模型代理、受保护验收配置与持久化产物存储;发布审批需要请求人以外的第二个人。
- `development`:仅用于本机或可丢弃的测试环境。
@ -42,8 +42,6 @@ docker build --file infra/images/runtime.Dockerfile --target worker --build-arg
| coordinator worker | `worker`,`WF_WORKER_ROLE=coordinator` | 可多副本 | `WF_WORKER_TOKEN`、`WF_CONTROL_PLANE_URL`、`TEMPORAL_ADDRESS`、`TEMPORAL_NAMESPACE` 或 `TEMPORAL_NAMESPACE_PREFIX` 加 `WF_DISPATCH_TENANTS`、`TEMPORAL_TLS_*` |
| deployer worker | `worker`,`WF_WORKER_ROLE=deployer` | 可多副本 | `WF_DEPLOYER_TOKEN`、`WF_CONTROL_PLANE_URL`,Temporal 配置同 coordinator |
| provisioner | `provisioner`(另需 `KUBECTL_IMAGE`) | 每个租户命名空间 1 个 | 见第 4 节 |
| IDE 网关 | `apps/ide/Dockerfile` 的 `gateway` | 每个租户 1 个 | 见第 6 节 |
| Theia 工作区 | `apps/ide/Dockerfile` 的 `theia` 目标 | 每个工作区 1 个,由 provisioner 创建 | 见 [apps/ide/README.md](../apps/ide/README.md) |
API 的其他配置:
@ -80,7 +78,7 @@ provisioner 为每个运行代次创建两个 Kata Job(executor 与 verifier
| `WF_TENANT_ID` | 该 provisioner 服务的唯一租户 |
| `WF_KUBE_CONTEXT`、`WF_KUBE_NAMESPACE` | 目标集群上下文与该租户的运行命名空间 |
| `WF_RUN_WORKER_IMAGE` | worker 镜像(必须是 `@sha256:` digest);`WF_RUN_PREVIOUS_IMAGES` 列出仍允许继续运行的旧镜像 |
| `WF_RUN_STORAGE_CLASS`、`WF_RUN_STORAGE_SIZE` | PVC 存储类;单个运行的存储上限(两个角色各一半)与 IDE 工作区卷的大小 |
| `WF_RUN_STORAGE_CLASS`、`WF_RUN_STORAGE_SIZE` | PVC 存储类;单个运行的存储上限(两个角色各一半) |
| `WF_CONTROL_PLANE_URL`、`WF_CONTROL_NAMESPACE` | 沙箱访问 API 的 HTTPS 地址与控制面命名空间 |
| `WF_GIT_SERVICE_PORT` | 平台 Git 服务端口(默认 4504) |
| `WF_RESOURCE_GRANT_SECRET` | 与 API 共享的资源授权签名密钥 |
@ -124,40 +122,13 @@ node --import tsx scripts/tenant-admin.ts member <租户ID> <成员 subject> <
最后的操作人 subject 可以省略,改用 `WF_OPERATOR_SUBJECT`;它必须列在 `WF_OPERATOR_SUBJECTS` 中。
套餐目录由 `WF_PLAN_CATALOG_FILE` 指定(格式见 `infra/plans/catalog.example.json`),限定成员数、项目数、工作区数、并发运行数、月度 token 与单次执行资源。分配套餐会把限额快照写入租户,修改目录不会自动影响已有租户;降级时如果现有用量超出新限额会被拒绝。`WF_OPERATOR_SUBJECTS` 列出可在 API 中执行运维操作(邀请成员、对账资源)的平台运维账号。
套餐目录由 `WF_PLAN_CATALOG_FILE` 指定(格式见 `infra/plans/catalog.example.json`),限定成员数、项目数、并发运行数、月度 token 与单次执行资源(旧目录中的 `maxWorkspaces` 仍被接受,但已不起作用)。分配套餐会把限额快照写入租户,修改目录不会自动影响已有租户;降级时如果现有用量超出新限额会被拒绝。`WF_OPERATOR_SUBJECTS` 列出可在 API 中执行运维操作(邀请成员、对账资源)的平台运维账号。
- 派发运行前,API 原子地占用一个执行名额并签发 5 分钟有效的资源授权(绑定租户、运行、代次、套餐版本、CPU/内存/存储与运行镜像),provisioner 校验授权后才创建资源。
- 月度 token 配额只计入排队或执行中的运行(以及有未结算模型请求的运行)的剩余预算;暂停、等待与结束的运行不占用,继续时重新计入。
- 用量:`GET /v1/usage` 返回本月 token 与执行时长,`GET /v1/usage/lines?period=YYYY-MM` 返回明细,`GET /v1/usage/export?period=YYYY-MM` 导出 CSV。模型费用由服务商直接向租户结算,平台不计价。
## 6. IDE 工作区与网关
每个租户运行一个 IDE 网关(`apps/ide/gateway`),它是浏览器访问 Theia 的唯一入口。用 `WF_WORKSPACE_GATEWAY_TARGETS_FILE` 为每个租户配置网关(单租户也可以用 `WF_WORKSPACE_GATEWAY_BASE`、`WF_WORKSPACE_GATEWAY_TOKEN`、`WF_IDE_PUBLIC_URL`,派发多个租户时用 `WF_WORKSPACE_GATEWAY_TENANT_ID` 指定租户):
```json
{"schemaVersion":1,"tenants":{"alpha":{"internalUrl":"https://alpha-ide.internal","publicUrl":"https://alpha.ide.example.com","tokenEnv":"WF_ALPHA_GATEWAY_TOKEN"}}}
```
- `internalUrl` 是 API 调用网关的地址,`publicUrl` 是浏览器访问的地址。不同租户必须使用不同的公网域名与令牌。
- 网关进程配置 `WF_DEPLOYMENT_MODE`、`WF_TENANT_ID`、`WF_WORKSPACE_GATEWAY_TOKEN`(与映射中 `tokenEnv` 的值相同)、`WF_API_URL`、`WF_IDE_PUBLIC_URL`(HTTPS)、`WF_IDE_ALLOWED_SERVICE_NAMESPACE`(工作区 Service 所在命名空间)。
- 启动流程:Web → API `POST /v1/workspaces/:id/launch` → 网关签发 30 秒一次性启动码 → 浏览器兑换为会话 Cookie。会话空闲 15 分钟失效;使用中(包括打开的 WebSocket)自动续期,最长 12 小时。
- 网关对每个请求与 WebSocket 向 API 复核权限(会话建立后按已授权的用户复核),撤销成员资格后立即断开连接。
provisioner 用 `WF_THEIA_IMAGE`(digest)创建工作区;配置 `WF_OCT_WORKSPACE_IMAGE` 与 `WF_IDE_PUBLIC_URL` 后每个工作区带一个协作 sidecar。
平台托管仓库的工作区在第一次打开时克隆项目,并切换到 `ide/work` 分支。网关在会话期间不断为它申请 15 分钟的仓库令牌,这个令牌只能推送 `ide/` 开头的分支,由平台 Git 的 pre-receive 钩子执行。人们推送后,从该分支提交愿望,由它验证并合入目标分支。为此需要:
- 工作区 Pod 能访问平台 Git:provisioner 会为每个工作区放行,控制面一侧见 [infra/k8s](../infra/k8s/README.md) 的 `workspaces-to-git`;
- 项目的 `repositoryUrl`(`WF_GIT_PUBLIC_BASE_URL`)对工作区可达;
- API 配置了 `WF_GIT_SERVICE_URL` 与 `WF_GIT_ADMIN_TOKEN`。
外部仓库不克隆。
工作区生命周期:用户可以在项目页暂停与恢复工作区;30 分钟没有活动且网关上没有打开的连接时自动暂停(`WF_WORKSPACE_AUTO_SLEEP=false` 可关闭)。暂停把工作区 Deployment 缩容到 0,文件保留在 PVC 中;未保存的编辑器内容会丢失。
多人协作需要为每个工作区部署独立的 OCT 实例,见 [apps/ide/collaboration/README.md](../apps/ide/collaboration/README.md)。
## 7. 交付:环境、Runner 与部署密钥
## 6. 交付:环境、Runner 与部署密钥
1. 租户管理员在「环境」页创建环境(Compose / Kubernetes / 平台托管 Kubernetes),然后注册 Runner,得到一次性显示的 Runner 令牌。
2. 在目标环境部署 `apps/runner`(`runner` 镜像目标),配置 `WF_DEPLOYMENT_MODE`、`WF_CONTROL_PLANE_URL`、`WF_TENANT_ID`、`WF_ENVIRONMENT_ID`、`WF_RUNNER_TOKEN`、`WF_RUNNER_PUBLIC_KEYS`(平台签名公钥)以及 mTLS 证书 `WF_RUNNER_CERT`/`WF_RUNNER_KEY`/`WF_RUNNER_CA`。Runner 默认只做演练,设置 `WF_RUNNER_EXECUTE=true` 后才真正部署。
@ -174,7 +145,7 @@ provisioner 用 `WF_THEIA_IMAGE`(digest)创建工作区;配置 `WF_OCT_WOR
4. 部署密钥通过 Vault KV v2 按固定版本注入,配置与映射文件格式见 [reference/deployment-secrets.md](reference/deployment-secrets.md)。
5. 高风险或生产发布需要审批,审批 24 小时内有效,过期后发布失败,继续运行会重新请求发布。
## 8. 监控与审计
## 7. 监控与审计
- `/health`:进程存活;`/readyz`:数据库可用。
- `/metrics`:Prometheus 格式,需要 `Authorization: Bearer $WF_METRICS_TOKEN`;未配置令牌时该路由不存在。指标按路由模板聚合,不包含资源 ID、提示词或凭据。
@ -182,11 +153,11 @@ provisioner 用 `WF_THEIA_IMAGE`(digest)创建工作区;配置 `WF_OCT_WOR
- 审计:`audit_events` 记录每次实体变更与操作者——Web 与 MCP 操作记为真实用户,模型代理的变更记为 `provider-proxy`,后台循环记为 `platform`。应用角色只能读取。
- 建议告警:API 5xx 比例、请求延迟、派发积压(未投递的 outbox 条目数与最老条目年龄)、处于 `ambiguous_execution`/`deployment` 等待超过 1 小时的运行、资源分配为 `unknown` 的运行。
## 9. 后台维护
## 8. 后台维护
API 进程内的维护循环(不依赖 Temporal)每 10 秒执行:释放已停止代次的计算资源;把代理进程已丢失、超过 15 分钟仍未结束的模型请求标记为结果未知;完成执行器两分钟内没有确认的暂停;使过期的审批与对应发布失效。每小时清理 7 天前已投递的 outbox 条目、30 天前的幂等记录,以及超过保留期的运行卷(见第 4 节)。设置 `WF_DISPATCH_ENABLED=false` 可在只读副本上关闭派发与维护循环。
## 10. 备份与恢复
## 9. 备份与恢复
`scripts/backup-restore.mjs` 基于导出快照做一致性备份,并能在独立的临时数据库中恢复并逐表比对摘要,不会覆盖源数据库:
@ -204,7 +175,7 @@ node scripts/backup-restore.mjs --restore-verify --manifest .wishforge/backups/<
脚本通过 `--container` 与 `--context` 指定运行 PostgreSQL 工具的容器与 Docker context,备份文件权限为 0600,不会自动删除。它只覆盖 PostgreSQL;平台 Git 仓库目录、对象存储、Vault 与 Temporal 需要各自的备份策略。生产应以托管数据库的 PITR 为主,本脚本用于恢复演练。
## 11. 故障处理
## 10. 故障处理
| 现象 | 处理 |
|---|---|
@ -216,13 +187,13 @@ node scripts/backup-restore.mjs --restore-verify --manifest .wishforge/backups/<
| 资源分配 `unknown` 占用并发名额 | 确认 provisioner 已清理该代次资源后,平台运维调用 `POST /v1/admin/executions/:runId/reconcile` 释放名额 |
| 派发积压 | 检查 Temporal 与 provisioner 可用性;outbox 条目的认领期限过后会被其他副本重新认领 |
## 12. 上线验收
## 11. 上线验收
- 在目标集群上证明 Kata 隔离、跨租户网络拒绝、Secret 不可读、资源耗尽保护与镜像 digest 准入(见 [infra/k8s/README.md](../infra/k8s/README.md))。
- 用真实账号完成 WorkBuddy 与 Codex 的 MCP OAuth 流程(见 [connectors/README.md](../connectors/README.md))。
- 演练一次部署失败与回滚、一次环境解锁、一次数据库恢复。
## 13. 已知风险
## 12. 已知风险
- **Temporal 授权**:平台这一侧已经做到三点:
- 所有连接使用客户端证书;
@ -230,6 +201,3 @@ node scripts/backup-restore.mjs --restore-verify --manifest .wishforge/backups/<
- 沙箱只拿到本租户的证书。
还需要运维在 Temporal 服务端配置授权:用 claim mapper 把客户端证书映射为只能访问本租户命名空间的角色,例如按证书主题区分租户。否则持有任意有效证书的客户端仍能访问所有命名空间。即使配置了授权,同一租户的沙箱仍可能轮询本租户其他运行的任务队列,影响的只是该租户自己的运行;结果是否成立仍以控制面的证据为准。
- **IDE 同 UID**:Theia 后端与用户终端以同一用户运行,同一工作区内的协作者之间没有隔离。
- **IDE 推送者不留痕**:平台不记录是谁推送了 `ide/` 分支,提交身份可以自行修改。这些改动进入目标分支前一定经过验证,但作者归属只能参考提交信息。
- **OCT 房间不持久**:协作服务重启后需要重新创建房间。

View File

@ -21,8 +21,8 @@
- 推送使用 `--force-with-lease` 并先做祖先检查;推送时目标分支又前进了,就基于新的提交重新准备候选,最多三次。
- 合并结果未通过检查、而不带本次改动的目标分支同样未通过(运行的起点能通过)时,运行进入 `target_broken` 等待,由人修好目标分支后继续,不消耗修复轮数;其余情况按一轮修复处理。
- 合并冲突时提交失败的集成证据(冲突文件与目标 commit),按一轮修复处理:修复轮先把最新目标分支合并进工作区,执行器解决冲突标记,检查点以该目标 commit 为基线。修复轮数用尽时运行进入 `integration_conflict` 等待。
- IDE 工作区(FR-H2):有编辑会话时得到 15 分钟的仓库令牌,令牌里写明只能更新 `refs/heads/ide/`。平台 Git 对每次推送运行 pre-receive 钩子,越界的引用被拒绝;平台自己的合入不受这个限制。所有推送都只接受快进,也不能删除分支。IDE 分支经由从它开始的愿望进入目标分支,过程与 Agent 的改动相同。
- 平台 Git 的管理接口 `POST /refs`(`{tenantId, projectId, prefix}`)按最近提交时间列出某个前缀下的分支,工作台据此列出 IDE 分支。
- 平台 Git 可以签发只能更新某个引用前缀(例如 `refs/heads/ide/`)的仓库令牌:pre-receive 钩子拒绝越界的引用,平台自己的合入不受这个限制。所有推送都只接受快进,也不能删除分支。管理接口 `POST /refs`(`{tenantId, projectId, prefix}`)按最近提交时间列出某个前缀下的分支。这两项原本服务于已移除的云 IDE,目前没有调用方。
- 愿望可以从一个已推送到项目仓库的分支开始(API/MCP 的 `sourceBranch`),验证后合入目标分支,过程与 Agent 的改动相同。
- GitHub 仓库走评审路径:只推送不可变的 `wishforge/<运行>/<commit>` 分支,控制面创建或对账对应的 PR 并等待合并(`github_review`);合并后在 GitHub 实际产生的合并 commit 上重新验证,再提交集成证据。未配置 GitHub App 的 GitHub 仓库不会退回直接推送(`github_unconfigured`)。安装令牌按仓库授权而不是按分支授权,目标分支仍需要分支保护。
## wishforge.yaml V1

View File

@ -17,8 +17,8 @@
|---|---|---|
| 工作概览 `/` | 进行中与待处理的运行数、最近运行、项目准备入口 | `GET /v1/dashboard` |
| 项目空间 `/projects` | 项目列表、创建项目 | `GET/POST /v1/projects` |
| 项目详情 `/projects/:id` | 仓库状态(平台仓库失败可重试)、IDE 工作区与从 IDE 推送的 `ide/` 分支(每个分支可以直接「提交愿望合入」)、项目运行、项目经验(查看、添加约定、停用、删除)、设置(目标分支、验证命令、安装命令、交付配置、验收配置) | `GET/PATCH /v1/projects/:id`、`POST /repository`、`/workspaces`、`/branches`、`/lessons`、`/v1/lessons/:id` |
| 运行记录 `/runs` | 运行列表与筛选;提交愿望(不可用的执行器不可选并显示原因;「起点」可以选一个 IDE 分支,运行从它开始,验证后合入) | `GET /v1/runs`、`POST /v1/projects/:id/wishes`、`GET /v1/projects/:id/branches` |
| 项目详情 `/projects/:id` | 仓库状态(平台仓库失败可重试)、项目运行、项目经验(查看、添加约定、停用、删除)、设置(目标分支、验证命令、安装命令、交付配置、验收配置) | `GET/PATCH /v1/projects/:id`、`POST /repository`、`/lessons`、`/v1/lessons/:id` |
| 运行记录 `/runs` | 运行列表与筛选;提交愿望(不可用的执行器不可选并显示原因) | `GET /v1/runs`、`POST /v1/projects/:id/wishes` |
| 运行详情 `/runs/:id` | 阶段进度、等待原因与对应操作、最近一次失败(修复轮的输入);标签页:概览、代码变更(检查点按文件的 diff)、阶段事件(Agent 消息、命令、文件变更、计划)、验证证据(命令、退出码、耗时、输出尾部,合入与冲突);交付结果(合入的 commit 或应用地址) | `GET /v1/runs/:id`、`/events/stream`、`/artifacts`、`/delivery`、`POST /commands` |
| 发布与审批 `/releases` | 发布列表(失败原因);审批对话框展示需求目标与验收标准、项目、环境(是否生产)、验证命令、commit、镜像、审批期限与请求人 | `GET /v1/releases`、`GET /v1/releases/:id/review`、`POST /v1/approvals/:id/decision` |
| 环境 `/environments` | 环境列表与创建、应用地址、Runner 注册、部署密钥引用、部署结果未知时「核对后解锁」 | `/v1/environments*`、`POST /v1/environments/:id/unlock` |
@ -35,7 +35,6 @@
- OIDC 使用 discovery、授权码 + PKCE(S256)、state 与 nonce,并校验 ID token 的签名、issuer 与 audience。
- 会话保存在加密的 HttpOnly Cookie 中,浏览器脚本无法读取;access token 过期前 1 分钟内由服务端代理使用 refresh token 续期,会话最长 12 小时。身份服务没有签发 refresh token 时,会话随 access token 结束。
- 写请求校验 `Origin`,代理拒绝上游重定向;界面上的权限控制只用于体验,最终以 API 的角色与成员检查为准。
- 打开 IDE 时,`/ide/:id/launch` 在服务端调用 API 获取 30 秒一次性启动地址,access token 不出现在 URL 中。
环境变量:`WF_DEPLOYMENT_MODE`、`WF_API_URL`、`WF_PUBLIC_URL`、`WF_DEV_AUTH_TOKEN`(仅开发)、`OIDC_ISSUER`、`OIDC_CLIENT_ID`、`OIDC_CLIENT_SECRET`(可选)、`WF_SESSION_SECRET`(至少 32 字符)。

View File

@ -8,13 +8,12 @@
WishForge 是一个**远程、意图驱动**的软件交付平台:
> 用户用自然语言提出「愿望」(目标 + 可验收标准),后端 Agent 在隔离环境中实现;独立验证器按受保护的验收命令判定结果,失败时把失败信息交还 Agent 自修复;通过后合入代码,按需构建并部署。全过程留有证据,高风险发布需要人工审批,任何时候都可以打开云 IDE 查看和修改代码。
> 用户用自然语言提出「愿望」(目标 + 可验收标准),后端 Agent 在隔离环境中实现;独立验证器按受保护的验收命令判定结果,失败时把失败信息交还 Agent 自修复;通过后合入代码,按需构建并部署。全过程留有证据,高风险发布需要人工审批。
用户可以从三个入口发起和跟踪愿望:
用户可以从两个入口发起和跟踪愿望:
- **Web 工作台**:完整的项目、运行、证据、审批与配置界面。
- **Agent 客户端**:WorkBuddy、Codex 等通过 MCP(OAuth 授权)调用 WishForge,在对话中远程许愿。
- **云 IDE**:基于 Theia 的浏览器 IDE,直接查看和修改项目代码。
产品价值:把「一句需求」变成「有证据的交付」,并让交付质量随使用次数提升(见第 3 节 RSI)。
@ -31,7 +30,6 @@ WishForge 是一个**远程、意图驱动**的软件交付平台:
| 发布(Release) | 把某个已验证、已构建的版本部署到某个环境的请求,绑定全部输入的摘要。 |
| 环境(Environment) | 部署目标:平台托管 Kubernetes、客户自有 Kubernetes 或 Docker Compose。 |
| Runner | 部署在目标环境侧、主动向平台拉取签名部署任务的代理进程。 |
| 工作区(Workspace) | 项目的云 IDE 实例。 |
| Agent 配置(Bundle) | 执行器使用的提示词模板与模型选择,以不可变版本保存。 |
| 项目经验(Lesson) | 从历史运行中沉淀的、对后续任务有用的知识条目。 |
@ -50,9 +48,9 @@ RSI(Recursive Self-Improvement,递归自我改进)在 WishForge 中指**
| 角色 | 权限要点 |
|---|---|
| owner / admin(租户管理员) | 管理项目、成员、执行器凭据(BYOK)、环境与 Runner、验证配置、Agent 配置与项目经验;审批发布。 |
| developer(开发者) | 提交和控制愿望、回答澄清、打开 IDE 编辑、请求发布。 |
| developer(开发者) | 提交和控制愿望、回答澄清、请求发布。 |
| deployer(发布者) | 审批与回滚发布。 |
| viewer(观察者) | 只读查看项目、运行、证据和发布;不能进入 IDE 编辑会话。 |
| viewer(观察者) | 只读查看项目、运行、证据和发布。 |
| 平台运维 | 部署和运维 WishForge 本身,配置执行环境、验收配置、套餐与配额。 |
| Agent 客户端 | WorkBuddy、Codex 等,以用户身份经 OAuth 调用 MCP,权限不超过该用户,且不能代替人完成审批。 |
@ -73,10 +71,9 @@ RSI(Recursive Self-Improvement,递归自我改进)在 WishForge 中指**
4. 查看可读的代码 diff 与验证证据(每条命令的结果与输出)。
5. 未配置交付的项目,代码合入目标分支后运行即成功;配置了交付的项目继续构建,按风险自动发布或等待审批,部署完成后访问应用。
**J3 在云 IDE 中协作**
1. 从项目页打开工作区,在浏览器中编辑、使用终端和调试器。
2. 改动提交并推送到 `ide/` 开头的分支;从该分支提交一个愿望,验证通过后合入目标分支。
3. 可以邀请有编辑权限的成员实时协作。
**J3 在云 IDE 中协作**(已移除)
云 IDE 已从 WishForge 中移除。自己写的改动可以推送到项目仓库的一个分支,再通过 API/MCP 提交一个从该分支开始的愿望(`sourceBranch`),验证通过后合入目标分支。
**J4 失败与修复**
1. 验证失败时,Agent 带着失败信息自动修复,最多尝试预算规定的轮数。
@ -163,16 +160,18 @@ RSI(Recursive Self-Improvement,递归自我改进)在 WishForge 中指**
| FR-G5 | P1 | 部署密钥通过密钥 broker 按固定版本注入;证据和日志中不含明文。 | 回执中只出现密钥引用与版本号。 |
| FR-G6 | P0 | 部署完成后在工作台与 MCP 展示应用地址。访问控制由目标环境负责,平台不提供应用访问网关。 | `get_delivery` 返回应用地址。 |
### H. 云 IDE
### H. 云 IDE(已移除)
云 IDE(Theia 工作区、IDE 网关、OCT 协作、按工作区的创建与生命周期)已从 WishForge 中移除,下列需求不再实现,只保留编号与原文供追溯。FR-H2 中「愿望可以指定起点分支」的部分保留:API 与 MCP 的 `sourceBranch` 仍然有效,工作台不再提供入口。
| ID | 优先级 | 需求 | 验收标准 |
|---|---|---|---|
| FR-H1 | P0 | 从工作台打开项目的 Theia 工作区;网关对每个 HTTP/WebSocket 请求校验租户、项目与角色;viewer 不能进入编辑会话。 | 撤销成员资格后,现有连接会被关闭。 |
| FR-H2 | P1 | 工作区首次打开时克隆项目仓库(平台托管仓库),有人使用期间持续注入仓库范围的短期凭据;IDE 只能推送 `ide/` 开头的分支,愿望可以指定从这样的分支开始,验证通过后连同 Agent 的改动一起合入目标分支。外部仓库的改动走 PR,不克隆。 | 新工作区打开后即有项目代码;IDE 直接推送目标分支被拒绝;从 IDE 分支开始的愿望验证并合入这些改动。 |
| FR-H3 | P1 | 多人实时协作(OCT),房间按工作区隔离,仅有编辑权限的成员可以加入。 | 其他工作区的邀请无法加入。 |
| FR-H4 | P1 | 工作区手动暂停/恢复与空闲自动暂停。 | 暂停后不占用计算资源,恢复后数据仍在。 |
| FR-H5 | P1 | 扩展白名单:只能使用平台预置并校验过摘要的扩展。 | 安装未经审核扩展的请求被拒绝。 |
| FR-H6 | P1 | 活跃使用中的 IDE 会话自动续期,不会被定时强制断开。 | 连续使用 2 小时不需要重新打开。 |
| ~~FR-H1~~ | 已移除 | 从工作台打开项目的 Theia 工作区;网关对每个 HTTP/WebSocket 请求校验租户、项目与角色;viewer 不能进入编辑会话。 | 撤销成员资格后,现有连接会被关闭。 |
| ~~FR-H2~~ | 已移除(起点分支保留) | 工作区首次打开时克隆项目仓库(平台托管仓库),有人使用期间持续注入仓库范围的短期凭据;IDE 只能推送 `ide/` 开头的分支,愿望可以指定从这样的分支开始,验证通过后连同 Agent 的改动一起合入目标分支。外部仓库的改动走 PR,不克隆。 | 新工作区打开后即有项目代码;IDE 直接推送目标分支被拒绝;从 IDE 分支开始的愿望验证并合入这些改动。 |
| ~~FR-H3~~ | 已移除 | 多人实时协作(OCT),房间按工作区隔离,仅有编辑权限的成员可以加入。 | 其他工作区的邀请无法加入。 |
| ~~FR-H4~~ | 已移除 | 工作区手动暂停/恢复与空闲自动暂停。 | 暂停后不占用计算资源,恢复后数据仍在。 |
| ~~FR-H5~~ | 已移除 | 扩展白名单:只能使用平台预置并校验过摘要的扩展。 | 安装未经审核扩展的请求被拒绝。 |
| ~~FR-H6~~ | 已移除 | 活跃使用中的 IDE 会话自动续期,不会被定时强制断开。 | 连续使用 2 小时不需要重新打开。 |
### I. 经验沉淀与 Agent 配置(RSI)
@ -189,7 +188,7 @@ RSI(Recursive Self-Improvement,递归自我改进)在 WishForge 中指**
|---|---|---|---|
| FR-J1 | P0 | 记录每个运行的 token 用量(优先使用代理计量)与执行时长。 | 用量页显示本月 token 与按运行的明细。 |
| FR-J2 | P0 | 租户配额:并发运行数、月度 token 上限;超额时拒绝提交并说明原因;暂停、等待中或已结束的运行不长期占用预留额度。 | 暂停一个运行后,可以提交新的愿望。 |
| FR-J3 | P1 | 套餐限额(成员数、项目数、工作区数、执行资源规格)由运营配置;用量明细可导出 CSV。 | 超出套餐限额时返回明确错误。 |
| FR-J3 | P1 | 套餐限额(成员数、项目数、执行资源规格)由运营配置;用量明细可导出 CSV。 | 超出套餐限额时返回明确错误。 |
### K. 运维与工程
@ -220,7 +219,7 @@ RSI(Recursive Self-Improvement,递归自我改进)在 WishForge 中指**
- 发票、计价、结算与作废流程(只保留用量计量、配额与 CSV 导出)。
- 无人监督的平台级自动元进化(统计门禁、自动灰度、签名评估与外部发布回执)。
- 平台提供的私有应用访问网关及签名探测证明链。
- IDE 保存屏障、草稿恢复、调试控制租约,以及以 IDE 快照作为集成输入的机制。IDE 与 Agent 之间只通过 Git commit 交接。
- 云 IDE(Theia 工作区、IDE 网关、OCT 协作),以及 IDE 保存屏障、草稿恢复、调试控制租约、以 IDE 快照作为集成输入的机制。
- WorkBuddy Cloud 作为执行器(WorkBuddy 仍可作为 MCP 客户端发起愿望)。
- SSH/SCP 仓库地址、Git LFS、子模块。
- 多区域部署;使用客户数据训练模型或跨租户共享经验。
@ -230,7 +229,7 @@ RSI(Recursive Self-Improvement,递归自我改进)在 WishForge 中指**
| 里程碑 | 范围 | 完成标志 |
|---|---|---|
| M1 本地主线 | 全部 P0 | 本地一键启动后,一个愿望可以完成「实现 → 验证(含自修复)→ 合入」;经验会被沉淀并在下一次运行中使用;文档与代码一致;CI 通过。 |
| M2 生产就绪 | 全部 P1 | 在测试集群上完成 Kata 执行、构建、Runner 部署与回滚、IDE 工作区克隆与协作,并通过真实账号的 MCP OAuth 验收。 |
| M2 生产就绪 | 全部 P1 | 在测试集群上完成 Kata 执行、构建、Runner 部署与回滚,并通过真实账号的 MCP OAuth 验收。 |
| M3 持续改进 | P2 | 离线评测、项目归档等。 |
## 10. 验证方式

View File

@ -30,13 +30,12 @@
- **能撤回**:线上版本可以一键回滚;已经合入的改动可以一键撤销,撤销同样走验证和发布。
- **越用越好**:运行中积累的「项目经验」会自动带进同一项目后续的任务里。
### 1.1 三个入口
### 1.1 两个入口
| 入口 | 适合做什么 |
|---|---|
| **网页工作台** | 全部功能:提愿望、看进度和代码改动、处理等待、审批发布、管理项目与配置 |
| **Agent 客户端(MCP)** | 在 Codex、WorkBuddy 的对话里直接许愿和跟进(见[第 10 章](#10-在-codex--workbuddy-里许愿mcp)) |
| **云 IDE** | 在浏览器里看和改项目代码,再通过愿望合入(见[第 11 章](#11-云-ide)) |
### 1.2 本机 POC 是什么
@ -153,7 +152,7 @@
- 「+ 提交愿望」按钮。
- 三个数字:**进行中的运行**(运行中加排队中)、**待确认**(等待处理的运行加待审批的发布,也就是「需要你判断」的事)、**配置可用的执行器**。
- 「最近运行」列出最近 5 个运行,「全部运行 →」进入运行记录。
- 右侧是连接状态(POC 上显示「local · local-development」)和三个准备入口:连接代码仓库、配置执行器、打开云 IDE。
- 右侧是连接状态(POC 上显示「local · local-development」)和三个准备入口:连接代码仓库、配置执行器、提交第一个愿望。
### 4.3 项目空间与项目详情
@ -167,10 +166,9 @@
| 代码仓库地址 | 可留空:留空时由平台自建仓库;填写时只支持 HTTPS,不支持 SSH |
| 目标分支 | 默认 `main` |
**项目详情**页右上角有「⚙ 项目设置」和「+ 提交愿望」,页面包含四块:
**项目详情**页右上角有「⚙ 项目设置」和「+ 提交愿望」,页面包含三块:
- **代码仓库**:仓库地址、目标分支、仓库状态(可用 / 不可用 / 未创建)、代码权限(哪些算后端代码,谁能改它见「成员与权限」)。项目设置按钮只有管理员看得到。平台仓库没建好时有「重试创建仓库」。
- **云 IDE**:开发环境与从 IDE 推上来的分支,见[第 11 章](#11-云-ide)。
- **项目运行**:这个项目的运行,「查看全部 →」跳到筛选好的运行记录。
- **项目经验**:自动沉淀和手动添加的经验。新运行的提示词会带上最近 5 条启用中的经验。
- 「+ 添加约定」:写一条以后的执行器都要遵守的约定(最多 1000 字),例如「运行测试前先执行 npm run build」。
@ -205,7 +203,6 @@
| 项目空间 | 选择项目 |
| 你的愿望 | 必填,8~20000 字。第一行写目标,可以再写「范围:」「不改:」各一行;细节写进验收标准,不需要预先拆分技术步骤 |
| 代码范围 | 项目划出了后端代码时才显示,默认「只改前端」。**只改前端**:只能改项目放行的路径(POC 是 `src/`、`tests/frontend/`、`**/*.md`),Agent 一开始就被告知,做不到时会停下来提问(之后可以在运行详情放开,见 4.5);改到后端代码时不运行检查,平台在下一轮开始前把这些文件恢复原样(新建的删掉),让 Agent 只改前端重做,算一轮修复。**前端和后端**:可以改后端;你的账户能直接合入时验证通过就合入,否则先等代码审核,选项下面会写明。账户类型是「前端开发」时只有「只改前端」,没得选 |
| 起点 | 默认是目标分支的最新代码;平台托管仓库的项目可以选从 IDE 推送的分支,验证通过后一并合入。POC 只能从 `poc` 开始 |
| 验收标准 | 必填,每行一条,最多 30 条 |
| 执行器 | 只列出这台部署能用的执行器;POC 只有 Claude Code |
| Token 上限 | 1000~2,000,000。默认 30 万;POC 用 Claude Code 时默认 100 万(Claude CLI 的计量包含缓存读取) |
@ -305,15 +302,15 @@
### 4.10 用量
- **套餐权益与当前占用**:成员、项目、工作区、执行名额的「占用 / 上限」,以及月 Token 配额。
- **套餐权益与当前占用**:成员、项目、执行名额的「占用 / 上限」,以及月 Token 配额。
- **执行资源上限与当前预算**:单次运行的 CPU、内存、存储上限,已记 Token、已预留 Token、当前活跃运行。
- **按月查看**:选择月份(按 UTC 自然月)后「查看月份」,看模型 Token、执行时长、新增产物和逐条明细;「导出 CSV」下载当月明细。
- 平台只记录用量、不计价,模型费用由模型服务商直接结算。
### 4.11 界面上值得注意的几点
- **没有二次确认的操作**:暂停、继续、审批对话框里的「拒绝」、激活和回滚 Agent 配置、停用和删除项目经验、创建开发环境、重试创建仓库、修改成员的账户类型和权限(编辑后点「保存」)、停用或启用成员、退出登录。点之前想清楚。
- **有确认的操作**:取消运行、回滚发布、撤销这次改动、批准代码审核(须先勾选)、批准发布(须先勾选)、重置成员密码、暂停工作区、撤销凭据、解锁环境、注册 Runner。
- **没有二次确认的操作**:暂停、继续、审批对话框里的「拒绝」、激活和回滚 Agent 配置、停用和删除项目经验、重试创建仓库、修改成员的账户类型和权限(编辑后点「保存」)、停用或启用成员、退出登录。点之前想清楚。
- **有确认的操作**:取消运行、回滚发布、撤销这次改动、批准代码审核(须先勾选)、批准发布(须先勾选)、重置成员密码、撤销凭据、解锁环境、注册 Runner。
- **英文内容**:等待说明的具体内容、时间线说明、发布失败原因、表单里的错误信息来自后端,多为英文。
- 等待说明里的「打开项目设置」只会打开项目页,还要再点「⚙ 项目设置」。
@ -611,16 +608,15 @@ WishForge 提供 MCP 服务,Agent 客户端可以用你的身份远程许愿
---
## 11. 云 IDE
## 11. 从自己推送的分支许愿
云 IDE(基于 Theia)适用于**平台托管仓库**的项目(创建项目时仓库地址留空,由平台建仓)。POC 项目使用外部 Gitea 仓库,不走这个流程。
云 IDE 已经移除。想让自己写的改动经过验证再合入目标分支,可以:
1. 在项目详情的「云 IDE」面板点「+ 创建开发环境」。环境就绪后点「打开 IDE ↗」,会在新标签页打开 IDE(启动链接约 30 秒内有效)。
2. 第一次打开时,项目被克隆到工作区,处在 `ide/work` 分支上。
3. 在 IDE 里修改、提交,然后 `git push`。IDE 的凭据**只能推送 `ide/` 开头的分支**,直接推目标分支会被拒绝。
4. 回到项目详情,「云 IDE」面板列出推上来的分支,点「提交愿望合入」:提交愿望表单的「起点」已经选好这个分支。运行从这个分支开始,Agent 可以在你的改动上继续,验证通过后连同你的改动一起合入目标分支。
1. 把改动推送到项目仓库的一个分支(不能是目标分支,也不能以 `wishforge/` 开头)。
2. 通过 API 或 MCP 提交愿望时带上 `sourceBranch`(见[第 10 章](#10-在-codex--workbuddy-里许愿mcp))。网页的提交表单不提供这个选项。
3. 运行从这个分支的最新提交开始,Agent 可以在你的改动上继续,验证通过后连同你的改动一起合入目标分支;运行详情的「起点分支」显示它。
多人协作建议:**每人用自己的分支**(如 `ide/zhangsan`)。两个人推同一个分支时,后推的会被拒,需要先拉取合并。本地模式下所有工作区共用一个 Theia 实例和同一个目录,多人同时使用等于在改同一份文件;需要隔离时要用 Kubernetes 后端。由平台 provisioner 管理的工作区还可以「暂停工作区」/「恢复工作区」(暂停会结束终端和调试进程,未保存的修改会丢失)。
POC 项目固定从 `poc` 开始,不接受 `sourceBranch`。
---
@ -853,7 +849,7 @@ POC 一次只执行一个运行,前面的运行还在执行时新愿望会排
**怎么把整个本地环境重置?**
见 [development.md 第 8 节](development.md#8-常见问题)。不要整个删除 `.wishforge/` 目录。
见 [development.md 第 7 节](development.md#7-常见问题)。不要整个删除 `.wishforge/` 目录。
---
@ -866,7 +862,7 @@ POC 一次只执行一个运行,前面的运行还在执行时新愿望会排
| 权限 | 包含的操作 |
|---|---|
| 查看(所有人) | 查看自己能进入的项目、运行、代码变更、证据和发布 |
| 许愿 | 提交愿望、AI 优化、继续/暂停/取消运行、补充需求、撤销改动、创建项目、使用云 IDE;能不能改后端见 4.12 |
| 许愿 | 提交愿望、AI 优化、继续/暂停/取消运行、补充需求、撤销改动、创建项目;能不能改后端见 4.12 |
| 审核代码 | 批准或驳回代码审核 |
| 审批发布 | 批准、拒绝、回滚发布(含 GitHub 合并授权) |
| 管理 | 成员与权限、项目设置(含代码权限)、调整预算、项目经验、执行器凭据、环境与 Runner(含「每次发布都需人工确认」)、Agent 配置、用量明细与导出;包含以上全部 |

View File

@ -112,16 +112,6 @@ services:
retries: 20
restart: unless-stopped
oct:
profiles: ['ide']
build: { context: ./oct }
image: wishforge/oct:0.3.1-wf1
environment:
OCT_ACTIVATE_SIMPLE_LOGIN: 'true'
ports: ['127.0.0.1:48100:8100']
restart: unless-stopped
# OCT 0.3.1 holds rooms in memory: restart requires a new room/rejoin.
volumes:
postgres-data:
temporal-data:

View File

@ -17,7 +17,7 @@
docker build --file infra/images/runtime.Dockerfile --target worker --build-arg NODE_IMAGE="$NODE_IMAGE" --build-arg DOCKER_CLI_IMAGE="$DOCKER_CLI_IMAGE" --tag "$WORKER_IMAGE" .
```
把镜像推送到私有仓库,并把 worker 镜像的 digest 配置给 provisioner(`WF_RUN_WORKER_IMAGE`)。根目录的 `.dockerignore` 排除了 `.git`、本地环境文件、密钥与证书、依赖与构建目录、本地数据目录与 IDE(`apps/ide` 有自己的 `Dockerfile`,见 [apps/ide/README.md](../../apps/ide/README.md))。
把镜像推送到私有仓库,并把 worker 镜像的 digest 配置给 provisioner(`WF_RUN_WORKER_IMAGE`)。根目录的 `.dockerignore` 排除了 `.git`、本地环境文件、密钥与证书、依赖与构建目录和本地数据目录。
- worker 镜像中的 Docker 客户端必须连接单独配置的构建器(本地用 `WF_DOCKER_CONTEXT`,Kubernetes 中由 provisioner 传入 `WF_DOCKER_HOST` 与 TLS 证书),不要把宿主机 Docker socket 挂进任何 worker。镜像构建由 verifier 完成,只有它挂载构建器的客户端配置(provisioner 的 `WF_VERIFIER_DOCKER_CONFIG_SECRET`),executor 拿不到。
- 受保护验收脚本以 root 所有的镜像内容安装在 `/usr/local/lib/wishforge-verification/` 下,并在 API 中登记它们的摘要(见 [verification-profiles.md](../../docs/reference/verification-profiles.md))。不要把 API、Vault 或部署凭据挂进 executor 或 verifier。
@ -25,4 +25,4 @@ docker build --file infra/images/runtime.Dockerfile --target worker --build-arg
- 依赖先只按各工作区的 `package.json` 安装,只改源码时这一层直接复用缓存。新增工作区时要在 `runtime.Dockerfile` 中补一行 `COPY`,`tests/images.test.ts` 会检查。
- 构建时由 `scripts/build-services.mjs` 把各服务编译为 `dist/<服务>/main.mjs`:工作区包编入其中,其他依赖从 `node_modules` 加载,Temporal 工作流预先打包为 `dist/worker/workflow-bundle.js`,迁移脚本是 `dist/api/migrate.mjs`。运行时不再转译 TypeScript(FR-K5)。
这些镜像已在本地 k3s 集群(arm64、`node:22-bookworm`,见 [docs/local-k3s.md](../../docs/local-k3s.md))上构建,并完整跑通了愿望与 IDE 的流程。运维选定的基础镜像、x64、嵌套的 bubblewrap、远程 BuildKit 与 Kata/CNI 仍需在目标集群上验收。
这些镜像已在本地 k3s 集群(arm64、`node:22-bookworm`,见 [docs/local-k3s.md](../../docs/local-k3s.md))上构建,并完整跑通了愿望的流程。运维选定的基础镜像、x64、嵌套的 bubblewrap、远程 BuildKit 与 Kata/CNI 仍需在目标集群上验收。

View File

@ -7,7 +7,7 @@
| `namespaces.yaml` | 控制面命名空间 `wishforge-control` 与示例租户命名空间 `wishforge-tenant-example`,都强制 `restricted` Pod Security |
| `runtime-class.yaml` | `wishforge-kata`(`kata-qemu`,调度到 `wishforge.io/kata-ready=true` 的节点),即 provisioner `WF_KATA_RUNTIME_CLASS` 的默认值。只创建 RuntimeClass 不会安装 Kata |
| `provisioner-rbac.yaml` | provisioner 的 ServiceAccount 与它在租户命名空间中的 Role,正好覆盖它创建、读取、调整与清理的对象 |
| `network-policy.yaml` | 两个命名空间默认拒绝全部出入流量;控制面 Pod 允许 DNS;沙箱 Pod 可以访问 API、Temporal 与平台 Git;IDE 工作区可以访问平台 Git;IDE 网关可以访问工作区 Pod |
| `network-policy.yaml` | 两个命名空间默认拒绝全部出入流量;控制面 Pod 允许 DNS;沙箱 Pod 可以访问 API、Temporal 与平台 Git |
| `quota.yaml` | 示例租户的 ResourceQuota 与 LimitRange |
## provisioner 在租户命名空间中创建的对象
@ -15,7 +15,6 @@
Kubernetes 后端的说明见 [apps/provisioner/README.md](../../apps/provisioner/README.md)。
- **每个运行代次**:executor 与 verifier 各一个 Kata Job、PVC、保存运行令牌的 Secret 和 ServiceAccount(不挂载令牌、没有任何绑定),外加一条 NetworkPolicy。这条策略只允许 DNS,以及控制面命名空间中 `wishforge.io/component` 为 `api`、`temporal`、`git-storage` 的 Pod。模型调用经 API 的模型代理完成。
- **每个 IDE 工作区**:一个 PVC、一个 Kata Deployment(Theia,可选 OCT sidecar)、一个 Service 与一条 NetworkPolicy。这条策略只允许 `wishforge.io/component: workspace-gateway` 的 Pod 访问 3000/8100 端口;出站只有 DNS,平台托管仓库的项目再放行平台 Git,用于克隆与推送。
- **释放运行**:删除 Job,Pod 全部结束后删除 Secret、ServiceAccount 与 NetworkPolicy。PVC 保留用于排查,保留期过后由控制面请求 provisioner 按 `wishforge.io/run` 标签删除(默认一周,见 operations.md)。在此之前它们占用配额,配额要留出余量。
每次运行的出站端口取自 `WF_CONTROL_PLANE_URL`(未写端口时为 443)、`TEMPORAL_ADDRESS` 与 `WF_GIT_SERVICE_PORT`。NetworkPolicy 按 Pod 端口匹配,所以这三个 Service 的端口必须与容器端口一致。
@ -24,14 +23,14 @@ Kubernetes 后端的说明见 [apps/provisioner/README.md](../../apps/provisione
- 显式选择集群。准备带 `kata-qemu` 的 Kata 节点池并打上 `wishforge.io/kata-ready=true`,按实测调整 RuntimeClass 的 overhead。CNI 必须执行 NetworkPolicy。
- 每个租户一个命名空间:复制示例的 `wishforge.io/tenant` 标签、配额、默认拒绝策略与 provisioner 绑定,并配置为该租户 provisioner 的 `WF_KUBE_NAMESPACE`。把 Pod Security 版本从 `latest` 固定为集群支持的次版本。
- 给控制面 Pod 打上 `wishforge.io/component` 标签:`api`、`temporal`、`git-storage`、`workspace-gateway`。
- 给控制面 Pod 打上 `wishforge.io/component` 标签:`api`、`temporal`、`git-storage`。
- 为其余流量编写环境相关的策略:
- 入口;Web 与网关到 API;
- 入口;Web 到 API;
- API 到 PostgreSQL、OIDC、对象存储、Vault、provisioner 与模型供应商;
- worker 到 API 与 Temporal;
- provisioner 到 Kubernetes API。
- 把 provisioner 的 `WF_KUBE_CONTEXT` 绑定到 `provisioner` ServiceAccount 的短期投射令牌。
- 准入策略需要限制以下几项,RBAC 无法限制受信任控制器所创建 Job 与 Deployment 的字段:
- 准入策略需要限制以下几项,RBAC 无法限制受信任控制器所创建 Job 的字段:
- 只允许经批准的镜像 digest 与 `wishforge-kata`;
- 只允许非 root、只读根文件系统的容器,禁止特权容器、宿主机卷与宿主机命名空间;
- 只允许挂载本运行的 Secret。
@ -47,7 +46,7 @@ Kubernetes 后端的说明见 [apps/provisioner/README.md](../../apps/provisione
- 私有对象存储;
- 签名镜像;
- 外部密钥管理。
- 不要把 Compose 的开发密码或 OCT 的显示名登录带进生产。
- 不要把 Compose 的开发密码带进生产。
## 部署目标
@ -68,6 +67,6 @@ Runner 在客户的目标环境中运行,使用自己的 `WF_KUBE_CONTEXT` 与
- 验证跨租户访问与网络被拒绝、Secret 访问被拒绝。
- 做资源耗尽测试。
- 确认准入策略会拒绝未批准的 digest。
- 演练运行、IDE 工作区的暂停与恢复、Runner 的部署与回滚。
- 演练运行、Runner 的部署与回滚。
这些都尚未完成。

View File

@ -1,7 +1,5 @@
# Tenant namespaces deny everything. The provisioner adds one policy per run
# generation (DNS plus the API, Temporal and Git service) and one per IDE
# workspace (DNS and, for a platform repository, the Git service out; in only
# from the workspace gateway).
# generation (DNS plus the API, Temporal and Git service).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
@ -62,53 +60,7 @@ spec:
matchLabels:
app.kubernetes.io/managed-by: wishforge-provisioner
wishforge.io/component: runner
---
# The receiving side of the IDE workspaces' egress to the Git service, where people's
# clones fetch and push the project's repository.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: workspaces-to-git
namespace: wishforge-control
spec:
podSelector:
matchLabels:
wishforge.io/component: git-storage
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector:
matchExpressions:
- { key: wishforge.io/tenant, operator: Exists }
podSelector:
matchLabels:
app.kubernetes.io/managed-by: wishforge-provisioner
wishforge.io/component: ide
---
# The sending side of the per-workspace ingress policy: Theia on 3000, OCT on 8100.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: gateway-to-workspaces
namespace: wishforge-control
spec:
podSelector:
matchLabels:
wishforge.io/component: workspace-gateway
policyTypes: [Egress]
egress:
- to:
- namespaceSelector:
matchExpressions:
- { key: wishforge.io/tenant, operator: Exists }
podSelector:
matchLabels:
app.kubernetes.io/managed-by: wishforge-provisioner
wishforge.io/component: ide
ports:
- { protocol: TCP, port: 3000 }
- { protocol: TCP, port: 8100 }
# Every other flow (ingress, Web and gateway to the API, the API to PostgreSQL,
# Every other flow (ingress, Web to the API, the API to PostgreSQL,
# OIDC, object storage, Vault, the provisioner and model providers, workers to
# the API and Temporal, the provisioner to the Kubernetes API) needs an explicit
# environment-specific policy.

View File

@ -8,11 +8,10 @@ metadata:
namespace: wishforge-control
automountServiceAccountToken: false
---
# Exactly what apps/provisioner applies (server-side) for run generations and IDE
# workspaces, reads back, patches (workspace pause/resume) and deletes on release.
# Exactly what apps/provisioner applies (server-side) for run generations, reads
# back and deletes on release.
# Run PVCs are deleted by label once the control plane's retention period passed.
# RBAC cannot constrain the fields of the Jobs and Deployments it creates:
# admission policy must.
# RBAC cannot constrain the fields of the Jobs it creates: admission policy must.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
@ -22,18 +21,12 @@ rules:
- apiGroups: [batch]
resources: [jobs]
verbs: [get, list, create, patch, delete]
- apiGroups: [apps]
resources: [deployments]
verbs: [get, create, patch]
- apiGroups: ['']
resources: [pods]
verbs: [get, list]
- apiGroups: ['']
resources: [persistentvolumeclaims]
verbs: [get, list, create, patch, delete]
- apiGroups: ['']
resources: [services]
verbs: [get, create, patch]
- apiGroups: ['']
resources: [secrets, serviceaccounts]
verbs: [get, create, patch, delete]

View File

@ -37,7 +37,6 @@ stringData:
WF_GIT_ADMIN_TOKEN: '{{WF_GIT_ADMIN_TOKEN}}'
WF_GIT_TOKEN_SECRET: '{{WF_GIT_TOKEN_SECRET}}'
WF_PROVIDER_PROXY_SIGNING_KEY: '{{WF_PROVIDER_PROXY_SIGNING_KEY}}'
WF_WORKSPACE_GATEWAY_TOKEN: '{{WF_WORKSPACE_GATEWAY_TOKEN}}'
---
apiVersion: v1
kind: ConfigMap
@ -66,12 +65,6 @@ data:
WF_PROVIDER_PROXY_ALLOWED_MODELS: '{{MODEL}}'
WF_CODEX_DEFAULT_MODEL: '{{MODEL}}'
WF_OPENAI_BASE_URL: '{{OPENAI_BASE_URL}}'
# The IDE: the provisioner creates a Theia workspace with a collaboration sidecar per project,
# reached only through the gateway, which the browser opens at WF_IDE_PUBLIC_URL.
WF_WORKSPACE_GATEWAY_BASE: http://ide-gateway.wishforge-control.svc.cluster.local:4400
WF_IDE_PUBLIC_URL: '{{IDE_PUBLIC_URL}}'
WF_THEIA_IMAGE: '{{IDE_IMAGE}}'
WF_OCT_WORKSPACE_IMAGE: '{{OCT_IMAGE}}'
---
apiVersion: v1
kind: PersistentVolumeClaim
@ -314,47 +307,6 @@ spec:
selector: { app: web }
ports: [{ port: 3000, targetPort: 3000 }]
---
# The IDE gateway, the browser's only way into the workspaces: their network policy admits this
# component alone. It checks every request and WebSocket with the API.
apiVersion: apps/v1
kind: Deployment
metadata:
name: ide-gateway
namespace: wishforge-control
spec:
replicas: 1
selector: { matchLabels: { app: ide-gateway } }
template:
metadata:
labels: { app: ide-gateway, wishforge.io/component: workspace-gateway }
annotations: { wishforge.io/settings: '{{SETTINGS_DIGEST}}' }
spec:
containers:
- name: gateway
image: '{{IDE_GATEWAY_IMAGE}}'
env:
- { name: WF_DEPLOYMENT_MODE, value: development }
- { name: WF_API_URL, value: http://api.wishforge-control.svc.cluster.local:4000 }
- { name: WF_TENANT_ID, value: demo }
# The address the browser opens; the gateway refuses other origins.
- { name: WF_IDE_PUBLIC_URL, value: '{{IDE_PUBLIC_URL}}' }
- { name: WF_IDE_ALLOWED_SERVICE_NAMESPACE, value: wishforge-tenant-demo }
- name: WF_WORKSPACE_GATEWAY_TOKEN
valueFrom: { secretKeyRef: { name: wishforge-local, key: WF_WORKSPACE_GATEWAY_TOKEN } }
ports: [{ containerPort: 4400 }]
readinessProbe:
httpGet: { path: /healthz, port: 4400 }
periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: ide-gateway
namespace: wishforge-control
spec:
selector: { app: ide-gateway }
ports: [{ port: 4400, targetPort: 4400 }]
---
apiVersion: apps/v1
kind: Deployment
metadata:
@ -414,18 +366,12 @@ rules:
- apiGroups: [batch]
resources: [jobs]
verbs: [get, list, create, patch, delete]
- apiGroups: [apps]
resources: [deployments]
verbs: [get, create, patch]
- apiGroups: ['']
resources: [pods]
verbs: [get, list]
- apiGroups: ['']
resources: [persistentvolumeclaims]
verbs: [get, list, create, patch, delete]
- apiGroups: ['']
resources: [services]
verbs: [get, create, patch]
- apiGroups: ['']
resources: [secrets, serviceaccounts]
verbs: [get, create, patch, delete]

View File

@ -1,9 +0,0 @@
FROM node:22.14.0-bookworm-slim
WORKDIR /opt/oct
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --ignore-scripts && npm cache clean --force
USER node
EXPOSE 8100
# 0.3.1's Commander parser passes its previous default as parseInt's radix.
# Omit --port and use the upstream default 8100 to avoid NaN.
CMD ["node", "node_modules/open-collaboration-server/lib/app.js", "--hostname", "0.0.0.0"]

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More