Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
server-targets-crypto.ts4.3 KB · 140 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/**
 * Server-target crypto primitives (no I/O, no DB).
 *
 * Mirrors `workflow-secrets-crypto.ts` — AES-256-GCM under a 32-byte master
 * key sourced from `SERVER_TARGETS_KEY` (hex). Used for two ciphertext
 * columns:
 *   - `server_targets.encrypted_private_key` (the SSH private key)
 *   - `server_target_env.encrypted_value`    (per-target env var values)
 *
 * Both are addressed through the same primitives because they share the
 * same threat model: an attacker who reads the DB without the master key
 * cannot connect to or impersonate the target.
 *
 * Every fn returns `{ok:true,...}` / `{ok:false,error}` — never throws.
 */

import { createCipheriv, createDecipheriv, randomBytes } from "crypto";

const ALGO = "aes-256-gcm";
const IV_LEN = 12;
const TAG_LEN = 16;
const KEY_LEN = 32;

export function getMasterKey(): Buffer | null {
  const hex = process.env.SERVER_TARGETS_KEY;
  if (!hex) return null;
  const trimmed = hex.trim();
  if (!/^[0-9a-fA-F]+$/.test(trimmed)) return null;
  let buf: Buffer;
  try {
    buf = Buffer.from(trimmed, "hex");
  } catch {
    return null;
  }
  if (buf.length !== KEY_LEN) return null;
  return buf;
}

export function encryptValue(
  plaintext: string
): { ok: true; ciphertext: string } | { ok: false; error: string } {
  const key = getMasterKey();
  if (!key) {
    return {
      ok: false,
      error:
        "SERVER_TARGETS_KEY missing or not a 32-byte hex value (64 hex chars)",
    };
  }
  if (typeof plaintext !== "string") {
    return { ok: false, error: "plaintext must be a string" };
  }
  try {
    const iv = randomBytes(IV_LEN);
    const cipher = createCipheriv(ALGO, key, iv);
    const enc = Buffer.concat([
      cipher.update(plaintext, "utf8"),
      cipher.final(),
    ]);
    const tag = cipher.getAuthTag();
    if (tag.length !== TAG_LEN) {
      return { ok: false, error: "unexpected auth tag length" };
    }
    const blob = Buffer.concat([iv, tag, enc]);
    return { ok: true, ciphertext: blob.toString("base64") };
  } catch (err) {
    return {
      ok: false,
      error: `encrypt failed: ${err instanceof Error ? err.message : String(err)}`,
    };
  }
}

export function decryptValue(
  ciphertext: string
): { ok: true; plaintext: string } | { ok: false; error: string } {
  const key = getMasterKey();
  if (!key) {
    return {
      ok: false,
      error:
        "SERVER_TARGETS_KEY missing or not a 32-byte hex value (64 hex chars)",
    };
  }
  if (typeof ciphertext !== "string" || ciphertext.length === 0) {
    return { ok: false, error: "ciphertext must be a non-empty string" };
  }
  let blob: Buffer;
  try {
    blob = Buffer.from(ciphertext, "base64");
  } catch {
    return { ok: false, error: "ciphertext is not valid base64" };
  }
  if (blob.length < IV_LEN + TAG_LEN) {
    return { ok: false, error: "ciphertext blob too short" };
  }
  const iv = blob.subarray(0, IV_LEN);
  const tag = blob.subarray(IV_LEN, IV_LEN + TAG_LEN);
  const enc = blob.subarray(IV_LEN + TAG_LEN);
  try {
    const decipher = createDecipheriv(ALGO, key, iv);
    decipher.setAuthTag(tag);
    const dec = Buffer.concat([decipher.update(enc), decipher.final()]);
    return { ok: true, plaintext: dec.toString("utf8") };
  } catch (err) {
    return {
      ok: false,
      error: `decrypt failed: ${err instanceof Error ? err.message : String(err)}`,
    };
  }
}

/**
 * Validate an env var name. Same rule as POSIX-ish env: leading
 * letter/underscore, then letters/digits/underscores. We're a little
 * stricter than POSIX in that we require uppercase + digits + underscore
 * so KEY=value lines in the materialised .env file are predictable.
 */
export function isValidEnvName(name: unknown): name is string {
  return typeof name === "string" && /^[A-Z_][A-Z0-9_]*$/.test(name);
}

/**
 * Render an env-vars map as a `.env` file body — `KEY=value\n` lines with
 * values single-quoted and embedded single quotes escaped. This matches the
 * common `set -a; source /path/to/file; set +a` deploy-script pattern and
 * is what `materializeEnv` produces before scp'ing it to the box.
 */
export function renderDotenv(env: Record<string, string>): string {
  const keys = Object.keys(env).sort();
  return (
    keys
      .map((k) => {
        const v = env[k] ?? "";
        const quoted = "'" + v.replace(/'/g, "'\\''") + "'";
        return `${k}=${quoted}`;
      })
      .join("\n") + (keys.length ? "\n" : "")
  );
}