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-target-store.ts8.4 KB · 338 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/**
 * DB-side helpers for server targets — exists to keep route + hook code
 * thin and to centralise the audit-log call so every mutation logs.
 */

import { and, desc, eq } from "drizzle-orm";
import { db } from "../db";
import {
  serverTargetAudit,
  serverTargetDeployments,
  serverTargetEnv,
  serverTargets,
  type ServerTarget,
  type NewServerTarget,
  type ServerTargetEnv,
} from "../db/schema";
import { decryptValue, encryptValue, isValidEnvName } from "./server-targets-crypto";

export async function listTargets(): Promise<ServerTarget[]> {
  return db
    .select()
    .from(serverTargets)
    .orderBy(desc(serverTargets.createdAt));
}

export async function getTarget(
  id: string
): Promise<ServerTarget | null> {
  const [row] = await db
    .select()
    .from(serverTargets)
    .where(eq(serverTargets.id, id))
    .limit(1);
  return row ?? null;
}

export async function getTargetByName(
  name: string
): Promise<ServerTarget | null> {
  const [row] = await db
    .select()
    .from(serverTargets)
    .where(eq(serverTargets.name, name))
    .limit(1);
  return row ?? null;
}

export interface CreateTargetInput {
  name: string;
  host: string;
  port?: number;
  sshUser: string;
  privateKey: string;
  deployPath?: string;
  deployScript?: string;
  watchedRepositoryId?: string | null;
  watchedBranch?: string | null;
  createdBy: string;
}

export async function createTarget(
  input: CreateTargetInput
): Promise<{ ok: true; target: ServerTarget } | { ok: false; error: string }> {
  const enc = encryptValue(input.privateKey);
  if (!enc.ok) return { ok: false, error: enc.error };
  const insert: NewServerTarget = {
    name: input.name,
    host: input.host,
    port: input.port ?? 22,
    sshUser: input.sshUser,
    encryptedPrivateKey: enc.ciphertext,
    deployPath: input.deployPath ?? "/var/www/app",
    deployScript: input.deployScript ?? "bash deploy.sh",
    watchedRepositoryId: input.watchedRepositoryId ?? null,
    watchedBranch: input.watchedBranch ?? null,
    createdBy: input.createdBy,
  };
  try {
    const [row] = await db.insert(serverTargets).values(insert).returning();
    if (!row) return { ok: false, error: "insert returned no row" };
    await logAudit({
      targetId: row.id,
      actorId: input.createdBy,
      action: "target.created",
      detail: `${row.sshUser}@${row.host}:${row.port}`,
    });
    return { ok: true, target: row };
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err.message : String(err),
    };
  }
}

export async function deleteTarget(
  id: string,
  actorId: string
): Promise<void> {
  await db.delete(serverTargets).where(eq(serverTargets.id, id));
  await logAudit({
    targetId: id,
    actorId,
    action: "target.deleted",
  });
}

export async function recordPin(
  targetId: string,
  fingerprint: string,
  actorId: string
): Promise<void> {
  await db
    .update(serverTargets)
    .set({
      hostFingerprint: fingerprint,
      status: "verified",
      lastSeenAt: new Date(),
      updatedAt: new Date(),
    })
    .where(eq(serverTargets.id, targetId));
  await logAudit({
    targetId,
    actorId,
    action: "target.fingerprint_pinned",
    detail: fingerprint,
  });
}

// --- env vars ---------------------------------------------------------------

export async function listEnv(targetId: string): Promise<ServerTargetEnv[]> {
  return db
    .select()
    .from(serverTargetEnv)
    .where(eq(serverTargetEnv.targetId, targetId))
    .orderBy(serverTargetEnv.name);
}

/**
 * Decrypt the env vars for a target into a KEY→value map. Skips rows whose
 * ciphertext fails to decrypt (logged) — a corrupt row should not abort a
 * deploy, but the missing var becomes obvious in the run log.
 */
export async function resolveEnv(
  targetId: string
): Promise<Record<string, string>> {
  const rows = await listEnv(targetId);
  const out: Record<string, string> = {};
  for (const row of rows) {
    const dec = decryptValue(row.encryptedValue);
    if (dec.ok) out[row.name] = dec.plaintext;
    else console.warn(`[server-targets] decrypt env ${row.name}: ${dec.error}`);
  }
  return out;
}

export async function upsertEnv(input: {
  targetId: string;
  name: string;
  value: string;
  isSecret?: boolean;
  actorId: string;
}): Promise<{ ok: true } | { ok: false; error: string }> {
  if (!isValidEnvName(input.name)) {
    return {
      ok: false,
      error: "name must match /^[A-Z_][A-Z0-9_]*$/ (uppercase, digits, _)",
    };
  }
  const enc = encryptValue(input.value);
  if (!enc.ok) return { ok: false, error: enc.error };
  const now = new Date();
  try {
    const [existing] = await db
      .select()
      .from(serverTargetEnv)
      .where(
        and(
          eq(serverTargetEnv.targetId, input.targetId),
          eq(serverTargetEnv.name, input.name)
        )
      )
      .limit(1);
    if (existing) {
      await db
        .update(serverTargetEnv)
        .set({
          encryptedValue: enc.ciphertext,
          isSecret: input.isSecret ?? existing.isSecret,
          updatedBy: input.actorId,
          updatedAt: now,
        })
        .where(eq(serverTargetEnv.id, existing.id));
    } else {
      await db.insert(serverTargetEnv).values({
        targetId: input.targetId,
        name: input.name,
        encryptedValue: enc.ciphertext,
        isSecret: input.isSecret ?? true,
        updatedBy: input.actorId,
      });
    }
    await logAudit({
      targetId: input.targetId,
      actorId: input.actorId,
      action: "env.upserted",
      detail: input.name,
    });
    return { ok: true };
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err.message : String(err),
    };
  }
}

export async function deleteEnv(input: {
  targetId: string;
  name: string;
  actorId: string;
}): Promise<void> {
  await db
    .delete(serverTargetEnv)
    .where(
      and(
        eq(serverTargetEnv.targetId, input.targetId),
        eq(serverTargetEnv.name, input.name)
      )
    );
  await logAudit({
    targetId: input.targetId,
    actorId: input.actorId,
    action: "env.deleted",
    detail: input.name,
  });
}

// --- deployments + audit ----------------------------------------------------

export interface RecordDeployInput {
  targetId: string;
  commitSha?: string | null;
  ref?: string | null;
  triggeredBy?: string | null;
  triggerSource: "push" | "manual";
}

export async function startDeployRow(
  input: RecordDeployInput
): Promise<string | null> {
  try {
    const [row] = await db
      .insert(serverTargetDeployments)
      .values({
        targetId: input.targetId,
        commitSha: input.commitSha ?? null,
        ref: input.ref ?? null,
        triggeredBy: input.triggeredBy ?? null,
        triggerSource: input.triggerSource,
        status: "running",
      })
      .returning();
    return row?.id ?? null;
  } catch {
    return null;
  }
}

export async function finishDeployRow(input: {
  id: string;
  exitCode: number;
  stdout: string;
  stderr: string;
}): Promise<void> {
  try {
    await db
      .update(serverTargetDeployments)
      .set({
        status: input.exitCode === 0 ? "success" : "failed",
        exitCode: input.exitCode,
        stdout: input.stdout.slice(0, 1_000_000),
        stderr: input.stderr.slice(0, 1_000_000),
        finishedAt: new Date(),
      })
      .where(eq(serverTargetDeployments.id, input.id));
  } catch {
    /* ignore */
  }
}

export async function recentDeploys(
  targetId: string,
  limit = 20
): Promise<Array<typeof serverTargetDeployments.$inferSelect>> {
  return db
    .select()
    .from(serverTargetDeployments)
    .where(eq(serverTargetDeployments.targetId, targetId))
    .orderBy(desc(serverTargetDeployments.startedAt))
    .limit(limit);
}

export async function logAudit(input: {
  targetId?: string | null;
  actorId?: string | null;
  action: string;
  detail?: string | null;
  ip?: string | null;
}): Promise<void> {
  try {
    await db.insert(serverTargetAudit).values({
      targetId: input.targetId ?? null,
      actorId: input.actorId ?? null,
      action: input.action,
      detail: input.detail ?? null,
      ip: input.ip ?? null,
    });
  } catch {
    /* never fail the caller because of audit */
  }
}

export async function findTargetsForPush(input: {
  repositoryId: string;
  branch: string;
}): Promise<ServerTarget[]> {
  return db
    .select()
    .from(serverTargets)
    .where(
      and(
        eq(serverTargets.watchedRepositoryId, input.repositoryId),
        eq(serverTargets.watchedBranch, input.branch)
      )
    );
}