diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index aa4fc3b..3eb75c3 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -1,6 +1,6 @@ import { resolveGatewayTarget } from './domain/gateway-target.js'; import { createRemoteJWKSet, jwtVerify } from 'jose'; -import { DomainError, type Actor } from '@wishforge/contracts'; +import { DomainError, type Actor, isProduction } from '@wishforge/contracts'; import { sameSecret } from './domain/policy.js'; import type { Store } from './db/store.js'; import { ServiceTokens } from './service-tokens.js'; @@ -24,22 +24,18 @@ export class Authenticator { issuer.search || issuer.hash || !['https:', 'http:'].includes(issuer.protocol) || - (env.NODE_ENV === 'production' && issuer.protocol !== 'https:') + (isProduction(env) && issuer.protocol !== 'https:') ) throw new Error('OIDC issuer must be HTTPS in production and contain no credentials, query or fragment'); this.jwks = createRemoteJWKSet(new URL(`${env.OIDC_ISSUER.replace(/\/$/, '')}/protocol/openid-connect/certs`)); } - if (env.NODE_ENV === 'production' && env.WF_DEV_AUTH_TOKEN) + if (isProduction(env) && env.WF_DEV_AUTH_TOKEN) throw new Error('Development authentication cannot be configured in production'); } async authenticate(authorization?: string): Promise { if (!authorization?.startsWith('Bearer ')) throw new DomainError('UNAUTHENTICATED', 'Sign in to continue', 401); const token = authorization.slice(7); - if ( - this.env.NODE_ENV !== 'production' && - this.env.WF_DEV_AUTH_TOKEN && - sameSecret(token, this.env.WF_DEV_AUTH_TOKEN) - ) { + if (!isProduction(this.env) && this.env.WF_DEV_AUTH_TOKEN && sameSecret(token, this.env.WF_DEV_AUTH_TOKEN)) { return this.member('demo', '11111111-1111-4111-8111-111111111111', 'human', 'wishforge-web'); } if (!this.jwks || !this.env.OIDC_ISSUER || !this.env.OIDC_AUDIENCE) diff --git a/apps/api/src/db/migrate.ts b/apps/api/src/db/migrate.ts index 41b1f52..84eb569 100644 --- a/apps/api/src/db/migrate.ts +++ b/apps/api/src/db/migrate.ts @@ -1,3 +1,4 @@ +import { isProduction } from '@wishforge/contracts'; import pg from 'pg'; import { readFile } from 'node:fs/promises'; import { pathToFileURL } from 'node:url'; @@ -33,7 +34,7 @@ export async function migrate(url: string, appPassword: string) { } } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - if (process.env.NODE_ENV !== 'production') { + if (!isProduction(process.env)) { try { process.loadEnvFile('.env.local'); } catch {} diff --git a/apps/api/src/db/seed.ts b/apps/api/src/db/seed.ts index 98cf932..0848495 100644 --- a/apps/api/src/db/seed.ts +++ b/apps/api/src/db/seed.ts @@ -1,8 +1,10 @@ import pg from 'pg'; -if (process.env.NODE_ENV === 'production') throw new Error('Development seed is disabled in production'); +import { isProduction } from '@wishforge/contracts'; + try { process.loadEnvFile('.env.local'); } catch {} +if (isProduction(process.env)) throw new Error('The development seed never runs in production mode'); const c = new pg.Client({ connectionString: process.env.DATABASE_ADMIN_URL }); await c.connect(); try { diff --git a/apps/api/src/domain/application-access.ts b/apps/api/src/domain/application-access.ts index 0bb17f9..485c7cb 100644 --- a/apps/api/src/domain/application-access.ts +++ b/apps/api/src/domain/application-access.ts @@ -4,6 +4,7 @@ import { matchesApplicationAccess, type Environment, type Release, + isProduction, } from '@wishforge/contracts'; /** @@ -18,10 +19,7 @@ export function applicationUrlFor( if (!environment.applicationUrl) return undefined; let applicationUrl: string; try { - applicationUrl = normalizeApplicationUrl( - environment.applicationUrl, - env.NODE_ENV !== 'production' && !environment.production, - ); + applicationUrl = normalizeApplicationUrl(environment.applicationUrl, !isProduction(env) && !environment.production); } catch { throw new DomainError( 'APPLICATION_URL_INVALID', @@ -62,7 +60,7 @@ export function assertApplicationConfigured( release: Pick, env: NodeJS.ProcessEnv, ) { - if (!release.applicationUrl && (env.NODE_ENV === 'production' || release.deliveryRequired)) + if (!release.applicationUrl && (isProduction(env) || release.deliveryRequired)) throw new DomainError( 'APPLICATION_URL_REQUIRED', 'Production delivery requires an explicit application URL and an access check', diff --git a/apps/api/src/domain/artifacts.ts b/apps/api/src/domain/artifacts.ts index d1ee1f7..d7eed28 100644 --- a/apps/api/src/domain/artifacts.ts +++ b/apps/api/src/domain/artifacts.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto'; -import { DomainError, type Actor, type Entity, type Run } from '@wishforge/contracts'; +import { DomainError, type Actor, type Entity, type Run, isProduction } from '@wishforge/contracts'; import { ArtifactError, MAX_ARTIFACT_BYTES, @@ -122,7 +122,7 @@ export class Artifacts { ); return { ...input }; } - if (this.env.NODE_ENV === 'production') + if (isProduction(this.env)) throw new DomainError('CHECKPOINT_ARTIFACT_REQUIRED', 'Production checkpoints require a durable source bundle'); return { ...input }; } @@ -151,7 +151,7 @@ export class Artifacts { 400, ); if (!this.objects.configured()) { - if (this.env.NODE_ENV === 'production') + if (isProduction(this.env)) throw new DomainError( 'ARTIFACT_STORAGE_UNCONFIGURED', 'Production checkpoint storage requires configured S3 and SSE-KMS', @@ -220,7 +220,7 @@ export class Artifacts { checkpoint: Record, ): Promise> { if (!checkpoint.gitBundleArtifactId) { - if (this.env.NODE_ENV === 'production' && checkpoint.gitBundleBase64) + if (isProduction(this.env) && checkpoint.gitBundleBase64) throw new DomainError( 'CHECKPOINT_ARTIFACT_REQUIRED', 'Inline development bundles cannot be used in production', diff --git a/apps/api/src/domain/connections.ts b/apps/api/src/domain/connections.ts index c9db164..735e76a 100644 --- a/apps/api/src/domain/connections.ts +++ b/apps/api/src/domain/connections.ts @@ -1,6 +1,6 @@ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; import { z } from 'zod'; -import { DomainError, providers, type Actor, type Run } from '@wishforge/contracts'; +import { DomainError, providers, type Actor, type Run, isProduction } from '@wishforge/contracts'; import type { Store } from '../db/store.js'; import { record, touch, must, executionLease } from './control-plane.js'; import { requireRole } from './policy.js'; @@ -11,7 +11,7 @@ export class CredentialVault { constructor(private env = process.env) {} async seal(tenantId: string, value: string): Promise { if (this.env.VAULT_ADDR) return this.transit('encrypt', tenantId, value); - if (this.env.NODE_ENV === 'production') + if (isProduction(this.env)) throw new DomainError('VAULT_UNCONFIGURED', 'Production requires an external Vault transit service', 503); const key = this.key(), iv = randomBytes(12), @@ -22,7 +22,7 @@ export class CredentialVault { } async open(tenantId: string, encrypted: string): Promise { if (encrypted.startsWith('vault:')) return this.transit('decrypt', tenantId, encrypted); - if (this.env.NODE_ENV === 'production') + if (isProduction(this.env)) throw new DomainError('VAULT_UNCONFIGURED', 'Local credential envelopes are not accepted in production', 503); const [, iv, tag, payload] = encrypted.split(':'); const decipher = createDecipheriv('aes-256-gcm', this.key(), Buffer.from(iv, 'base64url')); @@ -122,7 +122,7 @@ export class Connections { return (await tx.list('provider_connection')).find(c => c.provider === current.provider && c.status === 'active'); }); if (!connection?.ciphertext) return undefined; - if (this.env.NODE_ENV === 'production' || this.env.WF_PROVIDER_PROXY_ENABLED === 'true') { + if (isProduction(this.env) || this.env.WF_PROVIDER_PROXY_ENABLED === 'true') { if (run.provider !== 'codex') throw new DomainError( 'PROVIDER_PROXY_UNSUPPORTED', diff --git a/apps/api/src/domain/control-plane.ts b/apps/api/src/domain/control-plane.ts index ebaab64..1764556 100644 --- a/apps/api/src/domain/control-plane.ts +++ b/apps/api/src/domain/control-plane.ts @@ -18,6 +18,7 @@ import { type Environment, type ProviderInfo, type UsageSummary, + isProduction, } from '@wishforge/contracts'; import type { Store, Transaction } from '../db/store.js'; import { checkLease, digest, redact, requireRole } from './policy.js'; @@ -120,7 +121,7 @@ export class ControlPlane { try { validateRepositoryUrl(data.repositoryUrl, { allowLocalHttp: this.env.WF_GIT_ALLOW_LOCAL_HTTP === 'true', - production: this.env.NODE_ENV === 'production', + production: isProduction(this.env), }); } catch (error) { throw new DomainError( @@ -191,8 +192,7 @@ export class ControlPlane { ] as const ).map(([id, name]) => { const configured = connected(id); - const productionAllowed = - this.env.NODE_ENV !== 'production' || (id === 'codex' && providerProxyConfigured(this.env)); + const productionAllowed = !isProduction(this.env) || (id === 'codex' && providerProxyConfigured(this.env)); const enabled = configured && productionAllowed && (id !== 'codebuddy' || !!this.env.WF_CODEBUDDY_BIN); const reason = !productionAllowed ? 'Production execution requires a verified credential-isolation proxy and approved model configuration; raw BYOK is never sent to a production job.' @@ -643,7 +643,7 @@ export class ControlPlane { verificationCommands: project.verificationCommands, verificationProfile: project.verificationProfile, verificationProfileDigest: project.verificationProfile ? digest(project.verificationProfile) : undefined, - verificationProfileRequired: this.env.NODE_ENV === 'production', + verificationProfileRequired: isProduction(this.env), connectionId: connection?.id ?? null, bundleConfig: await resolveBundle(tx, run.bundleVersion), delivery: { diff --git a/apps/api/src/domain/gateway-target.ts b/apps/api/src/domain/gateway-target.ts index 957fc76..b84bcb3 100644 --- a/apps/api/src/domain/gateway-target.ts +++ b/apps/api/src/domain/gateway-target.ts @@ -1,6 +1,6 @@ import { readFile } from 'node:fs/promises'; import { z } from 'zod'; -import { DomainError } from '@wishforge/contracts'; +import { DomainError, isProduction } from '@wishforge/contracts'; const entry = z .object({ internalUrl: z.string().max(2048), @@ -31,9 +31,7 @@ function origin(raw: string, env: NodeJS.ProcessEnv) { value.hash || !( value.protocol === 'https:' || - (env.NODE_ENV !== 'production' && - value.protocol === 'http:' && - ['127.0.0.1', 'localhost', '[::1]'].includes(value.hostname)) + (!isProduction(env) && value.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(value.hostname)) ) ) throw new DomainError( diff --git a/apps/api/src/domain/git-storage.ts b/apps/api/src/domain/git-storage.ts index 21746d9..3518a30 100644 --- a/apps/api/src/domain/git-storage.ts +++ b/apps/api/src/domain/git-storage.ts @@ -1,4 +1,4 @@ -import { DomainError, type Actor, type Project, type Run } from '@wishforge/contracts'; +import { DomainError, type Actor, type Project, type Run, isProduction } from '@wishforge/contracts'; /** Only the trusted control plane can provision repositories or mint repository-scoped access. */ export class GitStorage { @@ -19,7 +19,7 @@ export class GitStorage { const base = new URL(this.env.WF_GIT_SERVICE_URL!); if ( base.protocol !== 'https:' && - !(this.env.NODE_ENV !== 'production' && ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname)) + !(!isProduction(this.env) && ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname)) ) throw new DomainError('INSECURE_GIT_STORAGE', 'Git control transport requires HTTPS', 503); const response = await this.fetcher(new URL(route, base), { diff --git a/apps/api/src/domain/integration-lease.ts b/apps/api/src/domain/integration-lease.ts index 881f6d9..72db1ba 100644 --- a/apps/api/src/domain/integration-lease.ts +++ b/apps/api/src/domain/integration-lease.ts @@ -1,4 +1,4 @@ -import { DomainError, type Actor, type Project, type Run } from '@wishforge/contracts'; +import { DomainError, type Actor, type Project, type Run, isProduction } from '@wishforge/contracts'; import type { Store } from '../db/store.js'; import { executionLease, executionScope, must, projectAccess, touch } from './control-plane.js'; @@ -117,7 +117,7 @@ export class IntegrationLeases { } private assertHeld(actor: Actor, run: Run, project: Project) { - if (this.env.NODE_ENV !== 'production' && !run.executionGeneration) return; + if (!isProduction(this.env) && !run.executionGeneration) return; const lock = project.integrationLease as IntegrationLease | undefined; if ( !lock || diff --git a/apps/api/src/domain/provider-proxy.ts b/apps/api/src/domain/provider-proxy.ts index dcc6777..febc3da 100644 --- a/apps/api/src/domain/provider-proxy.ts +++ b/apps/api/src/domain/provider-proxy.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto'; import { SignJWT, jwtVerify } from 'jose'; -import { DomainError, type Actor, type Entity, type Run } from '@wishforge/contracts'; +import { DomainError, type Actor, type Entity, type Run, isProduction } from '@wishforge/contracts'; import type { Store, Transaction } from '../db/store.js'; import { CredentialVault } from './connections.js'; import { executionLease, must, record, touch, now } from './control-plane.js'; @@ -54,7 +54,7 @@ interface Options { pollMs?: number; } export function providerProxyConfigured(env = process.env) { - if (env.NODE_ENV !== 'production' && env.WF_PROVIDER_PROXY_ENABLED !== 'true') return false; + if (!isProduction(env) && env.WF_PROVIDER_PROXY_ENABLED !== 'true') return false; if ( !env.WF_PROVIDER_PROXY_PUBLIC_URL || !env.WF_PROVIDER_PROXY_SIGNING_KEY || @@ -71,9 +71,7 @@ export function providerProxyConfigured(env = process.env) { !url.hash && url.pathname.replace(/\/$/, '').endsWith('/provider-proxy/v1') && (url.protocol === 'https:' || - (env.NODE_ENV !== 'production' && - url.protocol === 'http:' && - ['127.0.0.1', 'localhost'].includes(url.hostname))) + (!isProduction(env) && url.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(url.hostname))) ); } catch { return false; @@ -157,10 +155,7 @@ export class ProviderProxy { const current = await must(tx, 'run', run.id); executionLease(actor, current, run.lease!.token); if (current.status !== 'running') throw new DomainError('RUN_STOPPED', 'Run is not executing'); - if ( - this.env.NODE_ENV === 'production' && - (!actor.credentialId || actor.credentialId !== current.executionGeneration) - ) + if (isProduction(this.env) && (!actor.credentialId || actor.credentialId !== current.executionGeneration)) throw new DomainError( 'PROVIDER_GENERATION_REQUIRED', 'Production requires a run-scoped execution generation', diff --git a/apps/api/src/domain/provisioner-target.ts b/apps/api/src/domain/provisioner-target.ts index e1cafc0..a0a48af 100644 --- a/apps/api/src/domain/provisioner-target.ts +++ b/apps/api/src/domain/provisioner-target.ts @@ -1,6 +1,6 @@ import { readFile } from 'node:fs/promises'; import { z } from 'zod'; -import { DomainError } from '@wishforge/contracts'; +import { DomainError, isProduction } from '@wishforge/contracts'; const tenantIdSchema = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/); const targetSchema = z @@ -20,7 +20,7 @@ function checkedTarget(url: string, token: string | undefined, env: NodeJS.Proce } const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname); if ( - !(parsed.protocol === 'https:' || (env.NODE_ENV !== 'production' && parsed.protocol === 'http:' && loopback)) || + !(parsed.protocol === 'https:' || (!isProduction(env) && parsed.protocol === 'http:' && loopback)) || parsed.username || parsed.password || parsed.search || diff --git a/apps/api/src/domain/releases.ts b/apps/api/src/domain/releases.ts index 5f9b5c5..7c6ce25 100644 --- a/apps/api/src/domain/releases.ts +++ b/apps/api/src/domain/releases.ts @@ -11,6 +11,7 @@ import { type Run, type Evidence, type Project, + isProduction, } from '@wishforge/contracts'; import type { Store, Transaction } from '../db/store.js'; import { record, touch, must, projectAccess, idempotent, now, executionScope } from './control-plane.js'; @@ -193,7 +194,7 @@ export class Releases { requireDeploymentSecretPolicy(env); applicationUrlFor(env, this.env, await gatewayIdentityOrigins(this.env)); assertApplicationConfigured( - { applicationUrl: env.applicationUrl, deliveryRequired: this.env.NODE_ENV === 'production' }, + { applicationUrl: env.applicationUrl, deliveryRequired: isProduction(this.env) }, this.env, ); assertVerificationProfile(project, this.env); @@ -224,8 +225,8 @@ export class Releases { const binding = { deploymentSecretPolicyDigest: env.deploymentSecretPolicyDigest, applicationUrl: env.applicationUrl, - deliveryRequired: this.env.NODE_ENV === 'production' || !!env.applicationUrl, - developmentLoopback: this.env.NODE_ENV !== 'production' && !env.production, + deliveryRequired: isProduction(this.env) || !!env.applicationUrl, + developmentLoopback: !isProduction(this.env) && !env.production, runId: run.id, revision: run.revision, sourceCommit: run.verifiedCommit!, diff --git a/apps/api/src/domain/runner-broker.ts b/apps/api/src/domain/runner-broker.ts index 71ff575..9742d88 100644 --- a/apps/api/src/domain/runner-broker.ts +++ b/apps/api/src/domain/runner-broker.ts @@ -1,4 +1,4 @@ -import { canonicalJson, matchesApplicationAccess } from '@wishforge/contracts'; +import { canonicalJson, matchesApplicationAccess, isProduction } from '@wishforge/contracts'; import { createHash, createPrivateKey, createPublicKey, randomBytes, randomUUID, sign } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { z } from 'zod'; @@ -285,7 +285,7 @@ export class RunnerBroker { const verified = basicVerified && matchesApplicationAccess(release, result.evidence.accessEvidence) && - (this.env.NODE_ENV !== 'production' || !!release.applicationUrl); + (!isProduction(this.env) || !!release.applicationUrl); let rolledBack = false; if (task.rollbackOperationId) { diff --git a/apps/api/src/domain/verification-policy.ts b/apps/api/src/domain/verification-policy.ts index e4107bb..a4b8a86 100644 --- a/apps/api/src/domain/verification-policy.ts +++ b/apps/api/src/domain/verification-policy.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { DomainError, type Project, type VerificationProfile } from '@wishforge/contracts'; +import { DomainError, type Project, type VerificationProfile, isProduction } from '@wishforge/contracts'; import { digest } from './policy.js'; const profilePath = z @@ -66,7 +66,7 @@ export function verificationPolicyDigest(project: Project): string { } export function assertVerificationProfile(project: Project, env: NodeJS.ProcessEnv) { if (!project.verificationProfile) { - if (env.NODE_ENV === 'production') + if (isProduction(env)) throw new DomainError( 'VERIFICATION_PROFILE_REQUIRED', 'Production verification requires an operator-installed independent acceptance profile', diff --git a/apps/api/src/http.ts b/apps/api/src/http.ts index 71e638e..983a552 100644 --- a/apps/api/src/http.ts +++ b/apps/api/src/http.ts @@ -17,7 +17,7 @@ import { } from '@nestjs/common'; import type { Request, Response } from 'express'; import { z, ZodError } from 'zod'; -import { DomainError, type Actor, type Run } from '@wishforge/contracts'; +import { DomainError, type Actor, type Run, isProduction } from '@wishforge/contracts'; import { Authenticator } from './auth.js'; import { ControlPlane, must, projectAccess, record, touch } from './domain/control-plane.js'; import { Releases } from './domain/releases.js'; @@ -92,7 +92,7 @@ export class ApiController { providers, usage, system: { - mode: this.s.control.env.NODE_ENV === 'production' ? 'production' : 'development', + mode: isProduction(this.s.control.env) ? 'production' : 'development', region: this.s.control.env.WF_REGION ?? 'unconfigured', authMode: this.s.control.env.WF_DEV_AUTH_TOKEN ? 'local-development' : 'oidc', }, diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index f48825f..cb2c400 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -3,7 +3,7 @@ import 'reflect-metadata'; import { Module } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import express from 'express'; -import { DomainError } from '@wishforge/contracts'; +import { DomainError, requireDeploymentMode } from '@wishforge/contracts'; import { PgStore } from './db/store.js'; import { ControlPlane } from './domain/control-plane.js'; import { ApiController, InternalController, Services, Errors } from './http.js'; @@ -18,6 +18,7 @@ import { WorkspaceLifecycleWorker } from './workspace-lifecycle-worker.js'; import { ResourceReconciliationWorker } from './resource-reconciliation-worker.js'; export async function bootstrap() { + requireDeploymentMode(process.env); // Migration credentials belong to operator tools, never the running application. delete process.env.DATABASE_ADMIN_URL; delete process.env.WF_DATABASE_APP_PASSWORD; diff --git a/apps/git-service/package.json b/apps/git-service/package.json index 394228c..a2af28d 100644 --- a/apps/git-service/package.json +++ b/apps/git-service/package.json @@ -8,6 +8,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { + "@wishforge/contracts": "*", "@wishforge/runtime": "*" } } diff --git a/apps/git-service/src/main.ts b/apps/git-service/src/main.ts index 3fb206f..04ded87 100644 --- a/apps/git-service/src/main.ts +++ b/apps/git-service/src/main.ts @@ -1,5 +1,7 @@ +import { requireDeploymentMode } from '@wishforge/contracts'; import { createGitService } from './service.js'; async function main() { + requireDeploymentMode(process.env); for (const key of ['WF_GIT_ROOT', 'WF_GIT_PUBLIC_BASE_URL', 'WF_GIT_ADMIN_TOKEN', 'WF_GIT_TOKEN_SECRET']) if (!process.env[key]) throw new Error(`unconfigured: ${key} is required`); const server = await createGitService({ diff --git a/apps/git-service/src/service.ts b/apps/git-service/src/service.ts index 84bd1b4..b7e474b 100644 --- a/apps/git-service/src/service.ts +++ b/apps/git-service/src/service.ts @@ -1,3 +1,4 @@ +import { isProduction } from '@wishforge/contracts'; import { createHmac, timingSafeEqual } from 'node:crypto'; import { spawn } from 'node:child_process'; import { mkdir, open, realpath, stat, unlink } from 'node:fs/promises'; @@ -90,7 +91,7 @@ export async function createGitService(config: GitServiceConfig) { if ( publicBase.protocol !== 'https:' && !( - process.env.NODE_ENV !== 'production' && + !isProduction(process.env) && config.allowLocalHttp && publicBase.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(publicBase.hostname) diff --git a/apps/ide/gateway/main.mjs b/apps/ide/gateway/main.mjs index e2a9d13..9350dfb 100644 --- a/apps/ide/gateway/main.mjs +++ b/apps/ide/gateway/main.mjs @@ -1,6 +1,7 @@ import { createGateway } from './server.mjs'; -const production = process.env.NODE_ENV === 'production'; +// 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({ diff --git a/apps/runner/src/main.ts b/apps/runner/src/main.ts index f79025c..f397a25 100644 --- a/apps/runner/src/main.ts +++ b/apps/runner/src/main.ts @@ -6,9 +6,11 @@ import { DeploymentSecretBroker, type SignedRunnerTask, } from '@wishforge/runtime'; +import { requireDeploymentMode } from '@wishforge/contracts'; import { OutboundRunner } from './runner.js'; async function main() { + requireDeploymentMode(process.env); const required = [ 'WF_CONTROL_PLANE_URL', 'WF_RUNNER_TOKEN', diff --git a/apps/worker/src/main.ts b/apps/worker/src/main.ts index 62ae3e4..69689b4 100644 --- a/apps/worker/src/main.ts +++ b/apps/worker/src/main.ts @@ -1,8 +1,10 @@ import { fileURLToPath } from 'node:url'; import { NativeConnection, Worker } from '@temporalio/worker'; +import { requireDeploymentMode } from '@wishforge/contracts'; import { createActivities } from './activities.js'; async function main() { + requireDeploymentMode(process.env); const role = process.env.WF_WORKER_ROLE ?? 'coordinator'; if (!['coordinator', 'executor', 'verifier', 'deployer'].includes(role)) throw new Error('WF_WORKER_ROLE must be coordinator, executor, verifier or deployer'); diff --git a/package-lock.json b/package-lock.json index 42cee12..9760bcc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -56,6 +56,7 @@ "name": "@wishforge/git-service", "version": "0.1.0", "dependencies": { + "@wishforge/contracts": "*", "@wishforge/runtime": "*" } }, @@ -7905,7 +7906,8 @@ "name": "@wishforge/artifacts", "version": "0.1.0", "dependencies": { - "@aws-sdk/client-s3": "3.1152.0" + "@aws-sdk/client-s3": "3.1152.0", + "@wishforge/contracts": "*" } }, "packages/contracts": { diff --git a/packages/artifacts/package.json b/packages/artifacts/package.json index d08aff6..1c19e23 100644 --- a/packages/artifacts/package.json +++ b/packages/artifacts/package.json @@ -11,6 +11,7 @@ "build": "tsc --noEmit" }, "dependencies": { - "@aws-sdk/client-s3": "3.1152.0" + "@aws-sdk/client-s3": "3.1152.0", + "@wishforge/contracts": "*" } } diff --git a/packages/artifacts/src/index.ts b/packages/artifacts/src/index.ts index 3ce5d0c..21bc853 100644 --- a/packages/artifacts/src/index.ts +++ b/packages/artifacts/src/index.ts @@ -1,3 +1,4 @@ +import { isProduction } from '@wishforge/contracts'; import { createHash } from 'node:crypto'; import { S3Client, @@ -82,7 +83,7 @@ export class S3Artifacts { 'Set S3_BUCKET and S3_REGION to enable durable artifact storage', ); if ( - this.env.NODE_ENV === 'production' && + isProduction(this.env) && (this.encryption !== 'aws:kms' || !this.env.S3_KMS_KEY_ID || (this.env.S3_ENDPOINT && !this.env.S3_ENDPOINT.startsWith('https://'))) @@ -209,7 +210,7 @@ export class S3Artifacts { response.Metadata?.project !== record.projectId || response.Metadata?.run !== record.runId || response.Metadata?.sha256 !== record.sha256 || - (this.env.NODE_ENV === 'production' && response.ServerSideEncryption !== 'aws:kms') + (isProduction(this.env) && response.ServerSideEncryption !== 'aws:kms') ) { (response.Body as { destroy?: () => void } | undefined)?.destroy?.(); throw new ArtifactError( diff --git a/packages/contracts/src/deployment-mode.ts b/packages/contracts/src/deployment-mode.ts new file mode 100644 index 0000000..ae1e9b5 --- /dev/null +++ b/packages/contracts/src/deployment-mode.ts @@ -0,0 +1,31 @@ +/** + * Every security-relevant switch (development tokens, host execution, inline + * artifacts, HTTPS requirements, raw provider keys) depends on the deployment + * mode, never on NODE_ENV alone. + * + * Service entry points call `requireDeploymentMode` so that a process refuses + * to start until an operator chooses explicitly. Libraries call `isProduction`; + * when the variable is absent (tests, tooling) it falls back to NODE_ENV. + */ +export type DeploymentMode = 'production' | 'development'; + +type Env = Record; + +export function deploymentMode(env: Env): DeploymentMode { + const mode = env.WF_DEPLOYMENT_MODE; + if (mode === 'production') return mode; + if (mode === 'development') { + if (env.NODE_ENV === 'production') + throw new Error('WF_DEPLOYMENT_MODE=development conflicts with NODE_ENV=production'); + return mode; + } + if (mode) throw new Error(`WF_DEPLOYMENT_MODE must be "production" or "development", not "${mode}"`); + return env.NODE_ENV === 'production' ? 'production' : 'development'; +} + +export const isProduction = (env: Env) => deploymentMode(env) === 'production'; + +export function requireDeploymentMode(env: Env): DeploymentMode { + if (!env.WF_DEPLOYMENT_MODE) throw new Error('Set WF_DEPLOYMENT_MODE to "production" or "development"'); + return deploymentMode(env); +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index a8dbb59..ab88f66 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -430,3 +430,4 @@ export interface UsageLine { export * from './application-access.js'; export * from './canonical.js'; +export * from './deployment-mode.js'; diff --git a/packages/runtime/src/deploy.ts b/packages/runtime/src/deploy.ts index 7d51550..1469d3c 100644 --- a/packages/runtime/src/deploy.ts +++ b/packages/runtime/src/deploy.ts @@ -1,4 +1,4 @@ -import { normalizeApplicationUrl, type ApplicationAccessEvidence } from '@wishforge/contracts'; +import { normalizeApplicationUrl, type ApplicationAccessEvidence, isProduction } from '@wishforge/contracts'; import { requireCommit, safeIdentifier } from './git.js'; import { RuntimeError, type ReleaseManifest } from './types.js'; @@ -8,7 +8,7 @@ export function validateRelease(release: ReleaseManifest): void { if ( normalizeApplicationUrl( release.applicationUrl, - release.developmentLoopback === true && process.env.NODE_ENV !== 'production', + release.developmentLoopback === true && !isProduction(process.env), ) !== release.applicationUrl ) throw Error(); @@ -78,7 +78,7 @@ export function validateRelease(release: ReleaseManifest): void { } export function deliveryConfiguration(release: ReleaseManifest, stable: string | undefined): string | undefined { if (!release.applicationUrl) - return release.deliveryRequired || process.env.NODE_ENV === 'production' + return release.deliveryRequired || isProduction(process.env) ? 'Production delivery requires an explicit external application URL' : undefined; try { diff --git a/packages/runtime/src/deployment-secrets.ts b/packages/runtime/src/deployment-secrets.ts index 07e9f4d..b7495b7 100644 --- a/packages/runtime/src/deployment-secrets.ts +++ b/packages/runtime/src/deployment-secrets.ts @@ -1,3 +1,4 @@ +import { isProduction } from '@wishforge/contracts'; import { createHash } from 'node:crypto'; import { readFile, stat } from 'node:fs/promises'; import { inspect } from 'node:util'; @@ -110,7 +111,7 @@ function vaultOrigin(env: NodeJS.ProcessEnv) { return fail('DEPLOYMENT_SECRETS_UNCONFIGURED', 'An independent deployment Vault origin is required'); } const development = - env.NODE_ENV !== 'production' && + !isProduction(env) && env.WF_DEPLOYMENT_VAULT_ALLOW_LOOPBACK_HTTP === 'true' && ['127.0.0.1', 'localhost', '[::1]'].includes(target.hostname); if ( diff --git a/packages/runtime/src/git.ts b/packages/runtime/src/git.ts index 7e0d125..a6d3990 100644 --- a/packages/runtime/src/git.ts +++ b/packages/runtime/src/git.ts @@ -1,3 +1,4 @@ +import { isProduction } from '@wishforge/contracts'; import { createHash } from 'node:crypto'; import { mkdir, mkdtemp, readFile, writeFile, rm, stat } from 'node:fs/promises'; import path from 'node:path'; @@ -50,7 +51,7 @@ export function validateRepositoryUrl( } const localHttp = options.allowLocalHttp && - !(options.production ?? process.env.NODE_ENV === 'production') && + !(options.production ?? isProduction(process.env)) && url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname); if ((url.protocol !== 'https:' && !localHttp) || url.username || url.password || url.search || url.hash) diff --git a/scripts/provision-tenant.ts b/scripts/provision-tenant.ts index 3528b13..ccc1697 100644 --- a/scripts/provision-tenant.ts +++ b/scripts/provision-tenant.ts @@ -1,5 +1,6 @@ +import { isProduction } from '@wishforge/contracts'; import { runTenantAdmin } from './tenant-admin.js'; -if (process.env.NODE_ENV !== 'production') { +if (!isProduction(process.env)) { try { process.loadEnvFile('.env.local'); } catch {} diff --git a/scripts/tenant-admin.ts b/scripts/tenant-admin.ts index 7129134..48ba808 100644 --- a/scripts/tenant-admin.ts +++ b/scripts/tenant-admin.ts @@ -2,7 +2,7 @@ import pg from 'pg'; import { randomUUID } from 'node:crypto'; import { pathToFileURL } from 'node:url'; import { z } from 'zod'; -import { roles, type CommercialPlan, type TenantEntitlementSnapshot } from '@wishforge/contracts'; +import { roles, type CommercialPlan, type TenantEntitlementSnapshot, isProduction } from '@wishforge/contracts'; import { configuredPlans } from '../apps/api/src/domain/entitlements.js'; const tenantIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{2,62}$/); @@ -203,7 +203,7 @@ export async function runTenantAdmin(command: string, args: string[], env = proc } } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - if (process.env.NODE_ENV !== 'production') { + if (!isProduction(process.env)) { try { process.loadEnvFile('.env.local'); } catch {} diff --git a/tests/deployment-mode.test.ts b/tests/deployment-mode.test.ts new file mode 100644 index 0000000..eae2a57 --- /dev/null +++ b/tests/deployment-mode.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest'; +import { deploymentMode, isProduction, requireDeploymentMode } from '@wishforge/contracts'; + +describe('explicit deployment mode', () => { + it('prefers WF_DEPLOYMENT_MODE and rejects misspelled or conflicting values', () => { + expect(deploymentMode({ WF_DEPLOYMENT_MODE: 'production', NODE_ENV: 'development' })).toBe('production'); + expect(deploymentMode({ WF_DEPLOYMENT_MODE: 'development' })).toBe('development'); + expect(() => deploymentMode({ WF_DEPLOYMENT_MODE: 'prod' })).toThrow('must be'); + expect(() => deploymentMode({ WF_DEPLOYMENT_MODE: 'development', NODE_ENV: 'production' })).toThrow('conflicts'); + }); + it('falls back to NODE_ENV only for libraries and tests', () => { + expect(isProduction({ NODE_ENV: 'production' })).toBe(true); + expect(isProduction({})).toBe(false); + }); + it('makes service entry points refuse to start without an explicit choice', () => { + expect(() => requireDeploymentMode({ NODE_ENV: 'production' })).toThrow('Set WF_DEPLOYMENT_MODE'); + expect(requireDeploymentMode({ WF_DEPLOYMENT_MODE: 'production' })).toBe('production'); + }); +});