wishforge-ide/scripts/setup-local.mjs
eust-w 5aea9b73a9 fix: harden the control plane's storage, identities and recovery paths
- Storage: read-only queries use a read-only transaction without the tenant
  lock, so event streams and dashboards no longer queue behind writers; lists
  filter on indexed project, run and status fields and the run list pages with
  limit/before. Dispatchers claim outbox items with SKIP LOCKED and a claim
  deadline; delivered items and old idempotency records are pruned hourly.
- Migrations are versioned files recorded with checksums in schema_migrations;
  002 adds the claim column and run index and migrates preview-stage runs and
  free-text waiting reasons. Run events and usage are append-only for the app.
- Identities: static service tokens reach only their routes (coordinator: state,
  wait, repair; deployer: lease, transition, releases); the static verifier
  identity is gone; Git credentials go only to the lease holder; internal bodies
  are validated; framework and body-parser errors use the API error envelope.
- Quotas: only queued or running runs (or ones with an unsettled model request)
  hold token reservations; continuing a run reserves its remaining budget again.
- Recovery: owners can list and reconcile model requests with an unknown outcome,
  and requests whose proxy died are marked unknown; definite deployment failures
  free the environment, admins can unlock an environment after checking the
  target, approvals expire with their release, and production approvals need a
  second person. The builder's Docker context is operator configuration.
- MCP: list_projects, absolute console links, request_release resolves the run's
  evidence and default environment, and tool changes are audited as the user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:16:47 +08:00

136 lines
4.9 KiB
JavaScript

// Creates or completes the local-only configuration. Existing values are never
// changed, so it is safe to run again after pulling new versions.
import { generateKeyPairSync, randomBytes } from 'node:crypto';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
const root = process.cwd();
const secret = () => randomBytes(32).toString('hex');
let text = await readFile('.env.local', 'utf8').catch(
() => '# Local only. Generated secrets; never commit this file.\n',
);
const values = Object.fromEntries(
text
.split('\n')
.filter(line => line.includes('=') && !line.startsWith('#'))
.map(line => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]),
);
const added = [];
const add = (key, value) => {
if (values[key] !== undefined) return;
values[key] = value;
if (!text.endsWith('\n')) text += '\n';
text += `${key}=${value}\n`;
added.push(key);
};
// Development mode and the single local tenant.
add('WF_DEPLOYMENT_MODE', 'development');
add('WF_REGION', 'local');
add('WF_DISPATCH_TENANTS', 'demo');
add('WF_TENANT_ID', 'demo');
// PostgreSQL from infra/compose.yaml; the application connects with a non-superuser role.
add('DATABASE_ADMIN_URL', 'postgresql://wishforge:wishforge-dev-only@127.0.0.1:55432/wishforge');
add('WF_DATABASE_APP_PASSWORD', secret());
add('DATABASE_URL', `postgresql://wishforge_app:${values.WF_DATABASE_APP_PASSWORD}@127.0.0.1:55432/wishforge`);
// Control plane, console and identity (Keycloak realm from infra/keycloak).
add('PORT', '4000');
add('WF_API_URL', 'http://127.0.0.1:4000');
add('WF_CONTROL_PLANE_URL', 'http://127.0.0.1:4000');
add('WF_PUBLIC_URL', 'http://localhost:3000');
add('WF_DEV_AUTH_TOKEN', secret());
add('WF_SESSION_SECRET', secret());
add('OIDC_ISSUER', 'http://127.0.0.1:4100/realms/wishforge');
add('OIDC_AUDIENCE', 'wishforge-api');
add('OIDC_CLIENT_ID', 'wishforge-web');
add('WF_WEB_CLIENT_ID', 'wishforge-web');
add('TEMPORAL_ADDRESS', '127.0.0.1:7233');
add('TEMPORAL_NAMESPACE', 'default');
// Service identities and signing keys.
for (const key of [
'WF_WORKER_TOKEN',
'WF_DEPLOYER_TOKEN',
'WF_VAULT_KEY',
'WF_INTERNAL_TOKEN_KEY',
'WF_RESOURCE_GRANT_SECRET',
'WF_PROVISIONER_TOKEN',
'WF_WORKSPACE_GATEWAY_TOKEN',
'WF_GIT_ADMIN_TOKEN',
'WF_GIT_TOKEN_SECRET',
'WF_METRICS_TOKEN',
'WF_PROVIDER_PROXY_SIGNING_KEY',
])
add(key, secret());
// Platform Git service.
add('WF_GIT_SERVICE_URL', 'http://127.0.0.1:4504');
add('WF_GIT_PUBLIC_BASE_URL', 'http://127.0.0.1:4504');
add('WF_GIT_PORT', '4504');
add('WF_GIT_ALLOW_LOCAL_HTTP', 'true');
add('WF_GIT_ROOT', resolve(root, '.wishforge/git'));
// Checkpoint storage (MinIO from infra/compose.yaml).
add('S3_BUCKET', 'wishforge-artifacts');
add('S3_REGION', 'us-east-1');
add('S3_ENDPOINT', 'http://127.0.0.1:49000');
add('S3_ACCESS_KEY_ID', 'wishforge-dev');
add('S3_SECRET_ACCESS_KEY', 'wishforge-minio-dev-only');
// Local execution: the local provisioner runs each generation's executor and verifier on this host.
add('WF_PROVISIONER_BACKEND', 'local');
add('WF_PROVISIONER_URL', 'http://127.0.0.1:4450');
add('WF_LOCAL_RUN_ROOT', resolve(root, '.wishforge/runs'));
add('WF_LOCAL_IDE_URL', 'http://127.0.0.1:4300/');
// Cloud IDE gateway (npm run dev:ide).
add('WF_WORKSPACE_GATEWAY_TENANT_ID', 'demo');
add('WF_WORKSPACE_GATEWAY_BASE', 'http://127.0.0.1:4400');
add('WF_IDE_GATEWAY_URL', 'http://127.0.0.1:4400');
add('WF_IDE_PUBLIC_URL', 'http://127.0.0.1:4400');
add('WF_IDE_ALLOWED_UPSTREAM_ORIGINS', 'http://127.0.0.1:4300');
// Runner task signing key.
await mkdir('.wishforge/keys', { recursive: true, mode: 0o700 });
const keyFile = resolve(root, '.wishforge/keys/runner-ed25519.pem');
if (!(await readFile(keyFile).catch(() => undefined))) {
const { privateKey, publicKey } = generateKeyPairSync('ed25519');
await writeFile(keyFile, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600, flag: 'wx' });
await writeFile(
resolve(root, '.wishforge/keys/runner-public.json'),
JSON.stringify({ v1: publicKey.export({ type: 'spki', format: 'pem' }).toString() }, null, 2),
{ mode: 0o600 },
);
}
add('WF_RUNNER_SIGNING_KEY_FILE', keyFile);
await writeFile('.env.local', text, { mode: 0o600 });
// The web process receives only what the console needs: no database, worker or signing credentials.
const webKeys = [
'WF_DEPLOYMENT_MODE',
'WF_DEV_AUTH_TOKEN',
'WF_SESSION_SECRET',
'WF_PUBLIC_URL',
'WF_API_URL',
'OIDC_ISSUER',
'OIDC_CLIENT_ID',
'OIDC_CLIENT_SECRET',
];
await mkdir('apps/web', { recursive: true });
await writeFile(
'apps/web/.env.local',
`# Private local web configuration, generated by npm run setup:local\n${webKeys
.filter(key => values[key])
.map(key => `${key}=${values[key]}`)
.join('\n')}\n`,
{ mode: 0o600 },
);
console.log(
added.length
? `.env.local: added ${added.length} setting(s): ${added.join(', ')}`
: '.env.local already has every setting; nothing was changed.',
);