wishforge-ide/apps/api/src/domain/gateway-target.ts
eust-w 8b77085a5f fix: let Kubernetes sandboxes start, and run on a local development cluster
Sandbox Jobs never received WF_DEPLOYMENT_MODE, which every worker requires
before anything else, so each Kubernetes sandbox exited at start. The
provisioner now passes its own mode.

A local development cluster (k3s) has no Kata, no bubblewrap inside runc and no
TLS between services. For it, and only with WF_DEPLOYMENT_MODE=development:

- WF_ALLOW_INSECURE_HTTP=true lets services reach each other over plain HTTP
  (Git, the model proxy, the provisioner and IDE gateway targets, the worker's
  control-plane client); production refuses the setting outright.
- The provisioner accepts WF_RUN_SANDBOX_MODE=host and WF_KATA_RUNTIME_CLASS=none
  and passes the HTTP settings to its sandboxes.
- The development seed is built into the image (dist/api/seed.mjs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:56:07 +08:00

138 lines
5.1 KiB
TypeScript

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 };
}