feat: make the deployment mode explicit and fail closed

Security-relevant behaviour (development tokens, loopback HTTP, inline
checkpoints, raw provider keys, optional verification profiles) was
keyed off NODE_ENV === 'production', so any deployment that forgot
NODE_ENV silently ran with development rules.

- @wishforge/contracts exports deploymentMode/isProduction/
  requireDeploymentMode. WF_DEPLOYMENT_MODE wins; misspelled values and
  development combined with NODE_ENV=production are rejected; NODE_ENV
  remains a fallback only for libraries and tests.
- All API, runtime, artifact, Git service and operator-script checks use
  isProduction.
- The API, worker, Git service and Runner refuse to start without an
  explicit WF_DEPLOYMENT_MODE; the IDE gateway treats anything other
  than an explicit development mode as production.
- The development seed loads .env.local before checking the mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
eust-w 2026-10-19 14:07:02 +08:00
parent 82d35a3708
commit 78ed117763
34 changed files with 129 additions and 70 deletions

View File

@ -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<Actor> {
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)

View File

@ -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 {}

View File

@ -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 {

View File

@ -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<Release, 'applicationUrl' | 'deliveryRequired'>,
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',

View File

@ -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<string, unknown>,
): Promise<Record<string, unknown>> {
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',

View File

@ -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<string> {
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<string> {
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',

View File

@ -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: {

View File

@ -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(

View File

@ -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), {

View File

@ -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 ||

View File

@ -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<Run>(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',

View File

@ -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 ||

View File

@ -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!,

View File

@ -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) {

View File

@ -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',

View File

@ -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',
},

View File

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

View File

@ -8,6 +8,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@wishforge/contracts": "*",
"@wishforge/runtime": "*"
}
}

View File

@ -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({

View File

@ -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)

View File

@ -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({

View File

@ -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',

View File

@ -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');

4
package-lock.json generated
View File

@ -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": {

View File

@ -11,6 +11,7 @@
"build": "tsc --noEmit"
},
"dependencies": {
"@aws-sdk/client-s3": "3.1152.0"
"@aws-sdk/client-s3": "3.1152.0",
"@wishforge/contracts": "*"
}
}

View File

@ -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(

View File

@ -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<string, string | undefined>;
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);
}

View File

@ -430,3 +430,4 @@ export interface UsageLine {
export * from './application-access.js';
export * from './canonical.js';
export * from './deployment-mode.js';

View File

@ -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 {

View File

@ -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 (

View File

@ -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)

View File

@ -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 {}

View File

@ -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 {}

View File

@ -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');
});
});