#!/usr/bin/env node // Builds a product's .env files from its env template (crosscode.env-template/1, // docs/AGENT-1.0-PLAN.md §5). Used by `crosscode install` (files don't exist yet: written whole) // and `crosscode deploy` (files exist: only variables they don't have are appended, with a // comment; existing lines are never changed or removed). // // node envtpl.cjs --template --dir [--config ] // [--product events] [--var domain=… --var apiPort=…] [--fallback NAME=value] // [--release events@x.y.z] [--check] // // Values by layer: generated → environment variables CROSSCODE_GEN_ (so secrets never // appear in arguments or files other than the .env); server / defaults → the config's layers; // install → the config's install[product], else the variable's `from` filled with --var values. // Then --fallback, then the template's `default`. A required variable with no value stops // everything before any file is written (exit 3, the names on stderr). So does a value the app // can't start with (VALUE_RULES, exit 4), e.g. TRUST_PROXY=TRUE, which crashes the Events backend // only after the long build. // --check: only says what would be added. Prints names only, never values. 'use strict'; const fs = require('fs'); const path = require('path'); function parseArgs(argv) { const out = { vars: {}, fallback: {}, check: false }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; const next = () => { if (i + 1 >= argv.length) throw new Error(`${a} needs a value`); return argv[++i]; }; if (a === '--template') out.template = next(); else if (a === '--dir') out.dir = next(); else if (a === '--config') out.config = next(); else if (a === '--product') out.product = next(); else if (a === '--release') out.release = next(); else if (a === '--check') out.check = true; else if (a === '--var' || a === '--fallback') { const v = next(); const eq = v.indexOf('='); if (eq < 1) throw new Error(`${a} ${v}: expected NAME=value`); out[a === '--var' ? 'vars' : 'fallback'][v.slice(0, eq)] = v.slice(eq + 1); } else throw new Error(`Unknown option ${a}`); } if (!out.template || !out.dir) throw new Error('--template and --dir are required'); return out; } /** KEY names a .env file already sets (comments and blank lines ignored, `export KEY=` allowed). */ function keysIn(text) { const keys = new Set(); for (const line of text.split(/\r?\n/)) { const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line); if (m) keys.add(m[1]); } return keys; } // Values the apps check at startup. The rules live here rather than in the templates so they also // apply to releases whose templates predate them. Keep in step with checkEnvValue in // packages/contracts/src/agent.ts. Only for values that aren't secret: the message shows the value. const PROXY_NAME = /^(loopback|linklocal|uniquelocal)$/; const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/; const isIp = s => IPV4.test(s) || (s.includes(':') && /^[0-9A-Fa-f:.]+$/.test(s)); function proxyEntry(s) { if (PROXY_NAME.test(s)) return true; const [ip, bits, extra] = s.split('/'); if (extra !== undefined || !isIp(ip)) return false; return bits === undefined || /^\d{1,3}$/.test(bits) || IPV4.test(bits); } const VALUE_RULES = { // Events hands this to Express's "trust proxy" (apps/events/backend/src/app.js). TRUST_PROXY: { ok: v => v === 'true' || v === 'false' || /^\d+$/.test(v) || v.split(',').every(s => proxyEntry(s.trim())), hint: 'use loopback behind frp, a hop count such as 1, true or false (lowercase), or proxy IP addresses/CIDRs separated by commas', }, }; /** Why the app can't use this value, or undefined when it can (or there's no rule for it). */ function checkValue(name, value) { const rule = VALUE_RULES[name]; if (!rule || rule.ok(String(value).trim())) return undefined; return `${name}=${JSON.stringify(String(value))} won't work: ${rule.hint}`; } function fill(from, vars) { let missing = false; const value = from.replace(/\{([A-Za-z]+)\}/g, (_, k) => { if (vars[k] === undefined || vars[k] === '') missing = true; return vars[k] ?? ''; }); return missing ? undefined : value; } /** A value as a .env line: bare when safe, otherwise double-quoted (dotenv's rules). */ function line(name, value) { if (/[\r\n]/.test(value)) throw new Error(`${name}: values can't contain newlines`); return /^[A-Za-z0-9_./:@,+=%-]*$/.test(value) ? `${name}=${value}` : `${name}="${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`; } function resolve(variable, ctx) { let value; const nonEmpty = v => (v === undefined || v === null || String(v) === '' ? undefined : String(v)); switch (variable.layer) { case 'generated': value = nonEmpty(process.env[`CROSSCODE_GEN_${variable.name}`]); break; case 'server': value = nonEmpty(ctx.config.server?.[variable.name]); break; case 'defaults': value = nonEmpty(ctx.config.defaults?.[variable.name]); break; case 'install': value = nonEmpty(ctx.config.install?.[ctx.product]?.[variable.name]); if (value === undefined && variable.from) value = nonEmpty(fill(variable.from, ctx.vars)); break; default: throw new Error(`${variable.name}: unknown layer ${variable.layer}`); } if (value === undefined) value = nonEmpty(ctx.fallback[variable.name]); if (value === undefined) value = nonEmpty(variable.default); return value; } function plan(opts) { const template = JSON.parse(fs.readFileSync(opts.template, 'utf8')); if (template.schema !== 'crosscode.env-template/1') throw new Error(`${opts.template} isn't a crosscode.env-template/1`); const config = opts.config ? JSON.parse(fs.readFileSync(opts.config, 'utf8')) : {}; const ctx = { config, vars: opts.vars, fallback: opts.fallback, product: opts.product || template.product }; const files = []; const missing = []; const invalid = []; for (const [rel, variables] of Object.entries(template.files)) { if (rel.includes('..') || path.isAbsolute(rel)) throw new Error(`Bad file name in the template: ${rel}`); const file = path.join(opts.dir, rel); const exists = fs.existsSync(file); const have = exists ? keysIn(fs.readFileSync(file, 'utf8')) : new Set(); const add = []; for (const v of variables) { if (have.has(v.name)) continue; const value = resolve(v, ctx); if (value === undefined) { if (v.required) missing.push(`${v.name} (${v.layer}, ${rel})`); continue; } const problem = checkValue(v.name, value); if (problem) { const where = v.layer === 'server' ? "server, from the server's configuration on the Hub" : v.layer; invalid.push(`${problem} (${where}, ${rel})`); continue; } add.push({ name: v.name, value }); } files.push({ rel, file, exists, add }); } return { files, missing, invalid: [...new Set(invalid)] }; } function write({ files }, release) { const date = new Date().toISOString().slice(0, 10); for (const f of files) { if (!f.add.length) continue; const lines = f.add.map(a => line(a.name, a.value)); let text; if (!f.exists) { text = `# Written by crosscode from env.template.json${release ? ` (${release})` : ''}, ${date}.\n${lines.join('\n')}\n`; } else { const current = fs.readFileSync(f.file, 'utf8'); text = `${current}${current === '' || current.endsWith('\n') ? '' : '\n'}\n# Added by crosscode ${date}${release ? ` (${release})` : ''}\n${lines.join('\n')}\n`; } fs.mkdirSync(path.dirname(f.file), { recursive: true }); const tmp = `${f.file}.crosscode-${process.pid}`; fs.writeFileSync(tmp, text, { mode: 0o600 }); if (f.exists) { const st = fs.statSync(f.file); try { fs.chownSync(tmp, st.uid, st.gid); } catch { /* not root: same owner anyway */ } fs.chmodSync(tmp, st.mode & 0o777); } fs.renameSync(tmp, f.file); } } function main() { let opts; try { opts = parseArgs(process.argv.slice(2)); } catch (e) { console.error(`envtpl: ${e.message}`); process.exit(2); } const result = plan(opts); if (result.missing.length) { console.error(`Required settings with no value: ${result.missing.join(', ')}`); process.exit(3); } if (result.invalid.length) { console.error(`Settings the app can't start with:\n ${result.invalid.join('\n ')}`); process.exit(4); } for (const f of result.files) { if (!f.add.length) continue; const names = f.add.map(a => a.name).join(', '); console.log(`${f.rel}: ${opts.check ? 'would add' : f.exists ? 'added' : 'wrote'} ${names}`); } if (!opts.check) write(result, opts.release); } if (require.main === module) main(); module.exports = { parseArgs, keysIn, fill, line, plan, write, checkValue };