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
system-config.ts8.4 KB · 269 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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/**
 * DB-backed runtime config for `/admin/integrations`.
 *
 * Operators used to SSH into the box, edit `/etc/gluecron.env`, and
 * `systemctl restart gluecron` to rotate keys like `ANTHROPIC_API_KEY`,
 * `RESEND_API_KEY`, `GITHUB_TOKEN`. This module replaces that workflow:
 *
 *   - `getConfigValue(key, fallbackEnv)` — DB first, env fallback,
 *     empty string if neither is set.
 *   - `setConfigValue(key, value, userId)` — upsert + write `process.env`
 *     so existing synchronous callers (e.g. `config.anthropicApiKey`)
 *     pick up the new value immediately, with no restart.
 *   - `loadConfigIntoEnv()` — boot hook (called from `src/index.ts`)
 *     that copies every saved row into `process.env` before other
 *     modules read it.
 *   - `maskSecret(s)` — `re_••••••...XYZ`-style display helper.
 *
 * A small in-memory LRU (60s TTL) avoids hitting the DB on every read.
 * Cache is invalidated on any `setConfigValue` so admins see their
 * changes immediately in subsequent renders.
 */

import { eq } from "drizzle-orm";
import { db } from "../db";
import { systemConfig } from "../db/schema";

const CACHE_TTL_MS = 60_000;

type CacheEntry = { value: string; expiresAt: number };
const cache = new Map<string, CacheEntry>();

/** Mask "re_abc123xyz789" → "re_••••••89". Used for safe display in the UI. */
export function maskSecret(s: string | null | undefined): string {
  const v = (s ?? "").trim();
  if (!v) return "";
  // Keep the prefix (up to first underscore, max 4 chars) and last 2 chars.
  const underscore = v.indexOf("_");
  const prefixLen =
    underscore > 0 && underscore <= 4 ? underscore + 1 : Math.min(2, v.length);
  const prefix = v.slice(0, prefixLen);
  const tail = v.length > prefixLen + 4 ? v.slice(-2) : "";
  return `${prefix}••••••${tail}`;
}

/**
 * Heuristic: is this value the mask string we showed on the form, rather
 * than a freshly-typed secret? Used by the POST handler so a re-submit of
 * the rendered form doesn't overwrite the real secret with the mask.
 */
export function isMaskedValue(s: string | null | undefined): boolean {
  if (!s) return false;
  return s.includes("••••••");
}

/**
 * Read a config value. DB wins; falls back to `process.env[fallbackEnv]`;
 * empty string if neither is set. Cached for 60s.
 */
export async function getConfigValue(
  key: string,
  fallbackEnv: string
): Promise<string> {
  const cached = cache.get(key);
  if (cached && cached.expiresAt > Date.now()) {
    return cached.value || process.env[fallbackEnv] || "";
  }

  let dbValue = "";
  try {
    const [row] = await db
      .select({ value: systemConfig.value })
      .from(systemConfig)
      .where(eq(systemConfig.key, key))
      .limit(1);
    dbValue = (row?.value ?? "").trim();
  } catch (err) {
    console.warn(
      "[system-config] getConfigValue read failed:",
      err instanceof Error ? err.message : err
    );
  }

  cache.set(key, { value: dbValue, expiresAt: Date.now() + CACHE_TTL_MS });
  return dbValue || process.env[fallbackEnv] || "";
}

/**
 * Upsert a config value. Also writes `process.env[key]` so existing
 * synchronous `config.X` getters pick it up immediately — no restart.
 * Throws on DB failure so the route handler can surface an error banner.
 */
export async function setConfigValue(
  key: string,
  value: string,
  userId: string | null
): Promise<void> {
  const trimmed = (value ?? "").trim();
  await db
    .insert(systemConfig)
    .values({ key, value: trimmed, updatedByUserId: userId || null })
    .onConflictDoUpdate({
      target: systemConfig.key,
      set: {
        value: trimmed,
        updatedByUserId: userId || null,
        updatedAt: new Date(),
      },
    });
  cache.set(key, { value: trimmed, expiresAt: Date.now() + CACHE_TTL_MS });
  // Make the new value visible to sync getters across the process.
  if (trimmed) process.env[key] = trimmed;
  else delete process.env[key];
}

/**
 * Boot hook: copy every saved row into `process.env` before other modules
 * read it. Called once from `src/index.ts` near startup. Fire-and-forget —
 * if the DB is unreachable at boot, existing env vars stay as the fallback.
 */
export async function loadConfigIntoEnv(): Promise<number> {
  try {
    const rows = await db
      .select({ key: systemConfig.key, value: systemConfig.value })
      .from(systemConfig);
    let n = 0;
    for (const r of rows) {
      const v = (r.value ?? "").trim();
      if (!v) continue;
      // DB wins over env at boot. Existing process.env values are
      // overridden — that's the whole point: the admin saved a newer
      // value in the UI, and they want it to take effect.
      process.env[r.key] = v;
      cache.set(r.key, { value: v, expiresAt: Date.now() + CACHE_TTL_MS });
      n++;
    }
    return n;
  } catch (err) {
    console.warn(
      "[system-config] loadConfigIntoEnv skipped:",
      err instanceof Error ? err.message : err
    );
    return 0;
  }
}

/** Test-only — flush the in-memory cache. */
export function __resetCache(): void {
  cache.clear();
}

/**
 * Canonical integration list rendered by /admin/integrations. Keeping it
 * here (not in the route) so other modules (e.g. /admin/health) can read
 * which keys are user-managed without importing JSX.
 */
export interface IntegrationField {
  key: string;
  envFallback: string;
  label: string;
  helper: string;
  helperLink?: { href: string; text: string };
  isSecret: boolean;
  group:
    | "platform"
    | "ai"
    | "email"
    | "scm"
    | "security"
    | "observability"
    | "webhook";
}

export const INTEGRATION_FIELDS: IntegrationField[] = [
  {
    key: "APP_BASE_URL",
    envFallback: "APP_BASE_URL",
    label: "Public base URL",
    helper:
      "The HTTPS URL users hit (e.g. https://gluecron.com). Used to build OAuth redirect URIs — wrong/missing → Google/GitHub sign-in fails with redirect_uri_mismatch.",
    isSecret: false,
    group: "platform",
  },
  {
    key: "SELF_HOST_REPO",
    envFallback: "SELF_HOST_REPO",
    label: "Self-host repo (owner/name)",
    helper:
      "Which repo the /admin/ops + /admin/self-host tools operate on. Defaults to ccantynz-alt/Gluecron.com.",
    isSecret: false,
    group: "platform",
  },
  {
    key: "ANTHROPIC_API_KEY",
    envFallback: "ANTHROPIC_API_KEY",
    label: "Anthropic API key",
    helper:
      "Powers AI PR review, incident responder, commit messages, and auto-merge approval.",
    helperLink: { href: "https://console.anthropic.com/", text: "console.anthropic.com" },
    isSecret: true,
    group: "ai",
  },
  {
    key: "RESEND_API_KEY",
    envFallback: "RESEND_API_KEY",
    label: "Resend API key",
    helper: "Verification emails, password reset, magic link sign-in.",
    helperLink: { href: "https://resend.com/api-keys", text: "resend.com/api-keys" },
    isSecret: true,
    group: "email",
  },
  {
    key: "EMAIL_FROM",
    envFallback: "EMAIL_FROM",
    label: "Email sender address",
    helper: 'Format: `Gluecron <no-reply@your-domain>`.',
    isSecret: false,
    group: "email",
  },
  {
    key: "GITHUB_TOKEN",
    envFallback: "GITHUB_TOKEN",
    label: "GitHub personal access token",
    helper: "Used by the auto-merge sweep and GitHub-side API calls.",
    helperLink: { href: "https://github.com/settings/tokens", text: "github.com/settings/tokens" },
    isSecret: true,
    group: "scm",
  },
  {
    key: "GATETEST_URL",
    envFallback: "GATETEST_URL",
    label: "GateTest endpoint URL",
    helper: "Push-time security scanner — leave blank to disable scans.",
    isSecret: false,
    group: "security",
  },
  {
    key: "GATETEST_API_KEY",
    envFallback: "GATETEST_API_KEY",
    label: "GateTest API key",
    helper: "Auth token sent with each scan request.",
    isSecret: true,
    group: "security",
  },
  {
    key: "DEPLOY_EVENT_TOKEN",
    envFallback: "DEPLOY_EVENT_TOKEN",
    label: "Deploy events token",
    helper:
      "Shared secret for the live deploy timeline and AI incident responder.",
    isSecret: true,
    group: "observability",
  },
  {
    key: "CRONTECH_DEPLOY_URL",
    envFallback: "CRONTECH_DEPLOY_URL",
    label: "Crontech webhook URL",
    helper: "Optional: notify Crontech on every push to the canonical repo.",
    isSecret: false,
    group: "webhook",
  },
  {
    key: "CRONTECH_HMAC_SECRET",
    envFallback: "CRONTECH_HMAC_SECRET",
    label: "Crontech HMAC secret",
    helper: "Used to sign outbound Crontech webhook payloads.",
    isSecret: true,
    group: "webhook",
  },
];