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
workflow-artifacts.ts13.1 KB · 390 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/**
 * REST API for workflow run artifacts (Block C1 / Sprint 1 — Agent 6).
 *
 * Mount point: `/api/v1/...` — the main thread wires this in via
 * `app.route('/', artifactsRoutes)` in `app.tsx` (out of scope for this agent).
 *
 * Endpoints
 * ---------
 *   POST   /api/v1/runs/:runId/artifacts       → create artifact (multipart or JSON+base64)
 *   GET    /api/v1/runs/:runId/artifacts       → list artifact metadata
 *   GET    /api/v1/artifacts/:artifactId/download → download binary
 *   DELETE /api/v1/artifacts/:artifactId       → delete
 *
 * Auth
 * ----
 * `Authorization: Bearer <glc_...>` PAT. The token row in `api_tokens`
 * carries comma-separated scopes (see `src/routes/tokens.tsx`). For write
 * operations we require the token to have `repo` / `write` / `admin`; for
 * deletes we require `admin`. List/download allow public-repo anonymous
 * access (falls back to session cookie or unauthenticated for public repos).
 *
 * NOTE: we intentionally DO NOT use the existing `requireAuth` middleware
 * here — it redirects cookie-less requests to `/login` which is wrong for
 * an API client. Instead we resolve the bearer ourselves at the top of each
 * handler.
 */

import { Hono } from "hono";
import { and, eq } from "drizzle-orm";
import { db } from "../db";
import {
  apiTokens,
  repositories,
  users,
  workflowRuns,
} from "../db/schema";
import type { User } from "../db/schema";
import { sha256Hex } from "../lib/oauth";
import { softAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import {
  uploadArtifact,
  listArtifacts,
  downloadArtifact,
  deleteArtifact,
  getRunRepositoryId,
  getArtifactRunId,
  MAX_ARTIFACT_BYTES,
} from "../lib/workflow-artifacts";

const app = new Hono<AuthEnv>();

// Soft-auth so that public-repo GET requests with no creds still resolve
// `c.get("user") === null` cleanly (rather than touching the DB inside each
// handler). Write/delete handlers re-resolve the bearer themselves below
// because they also need the PAT scope list.
app.use("/api/v1/runs/*", softAuth);
app.use("/api/v1/artifacts/*", softAuth);

// ---------------------------------------------------------------------------
// Bearer-PAT helper (~30 lines per sprint notes).
// Returns the user + scopes if the header carries a valid `glc_` PAT, else
// null. We don't handle `glct_` OAuth tokens here — the API surface for
// workflow artifacts is PAT-oriented.
// ---------------------------------------------------------------------------

async function resolveBearer(
  authHeader: string | undefined
): Promise<{ user: User; scopes: string[] } | null> {
  if (!authHeader) return null;
  const lower = authHeader.toLowerCase();
  if (!lower.startsWith("bearer ")) return null;
  const token = authHeader.slice(7).trim();
  if (!token.startsWith("glc_")) return null;
  try {
    const hash = await sha256Hex(token);
    const [row] = await db
      .select()
      .from(apiTokens)
      .where(eq(apiTokens.tokenHash, hash))
      .limit(1);
    if (!row) return null;
    if (row.expiresAt && new Date(row.expiresAt) < new Date()) return null;
    const [user] = await db
      .select()
      .from(users)
      .where(eq(users.id, row.userId))
      .limit(1);
    if (!user) return null;
    const scopes = row.scopes
      ? row.scopes.split(/[,\s]+/).filter(Boolean)
      : [];
    return { user, scopes };
  } catch (err) {
    console.error("[workflow-artifacts] resolveBearer:", err);
    return null;
  }
}

/** Scope checks. Our PATs use names like `repo` / `user` / `admin`. We also
 * accept the literal names from the spec (`read` / `write` / `admin`) so the
 * action runner and CI clients can pick whichever feels natural. */
function hasReadScope(scopes: string[]): boolean {
  return (
    scopes.includes("repo") ||
    scopes.includes("read") ||
    scopes.includes("write") ||
    scopes.includes("admin")
  );
}
function hasWriteScope(scopes: string[]): boolean {
  return (
    scopes.includes("repo") ||
    scopes.includes("write") ||
    scopes.includes("admin")
  );
}
function hasAdminScope(scopes: string[]): boolean {
  return scopes.includes("admin");
}

async function loadRepoOwner(repositoryId: string): Promise<
  | { id: string; ownerId: string; isPrivate: boolean }
  | null
> {
  try {
    const [row] = await db
      .select({
        id: repositories.id,
        ownerId: repositories.ownerId,
        isPrivate: repositories.isPrivate,
      })
      .from(repositories)
      .where(eq(repositories.id, repositoryId))
      .limit(1);
    return row || null;
  } catch (err) {
    console.error("[workflow-artifacts] loadRepoOwner:", err);
    return null;
  }
}

// ---------------------------------------------------------------------------
// POST /api/v1/runs/:runId/artifacts — upload
// ---------------------------------------------------------------------------

app.post("/api/v1/runs/:runId/artifacts", async (c) => {
  const runId = c.req.param("runId");

  const bearer = await resolveBearer(c.req.header("authorization"));
  if (!bearer) {
    return c.json({ error: "authentication required" }, 401);
  }
  if (!hasWriteScope(bearer.scopes)) {
    return c.json({ error: "token missing write scope" }, 403);
  }

  const repositoryId = await getRunRepositoryId(runId);
  if (!repositoryId) {
    return c.json({ error: "run not found" }, 404);
  }
  const repo = await loadRepoOwner(repositoryId);
  if (!repo) {
    return c.json({ error: "repository not found" }, 404);
  }
  if (repo.ownerId !== bearer.user.id) {
    return c.json({ error: "forbidden" }, 403);
  }

  // Parse body — either multipart/form-data or JSON with base64 `content`.
  const ctype = (c.req.header("content-type") || "").toLowerCase();
  let name: string | undefined;
  let jobId: string | undefined;
  let contentType: string | undefined;
  let content: Buffer | undefined;

  try {
    if (ctype.startsWith("application/json")) {
      const body = await c.req.json<{
        name?: string;
        jobId?: string;
        contentType?: string;
        content?: string; // base64
      }>();
      name = body.name;
      jobId = body.jobId;
      contentType = body.contentType;
      if (typeof body.content === "string") {
        content = Buffer.from(body.content, "base64");
      }
    } else {
      // Treat everything else (multipart, x-www-form-urlencoded) as form data.
      const form = await c.req.parseBody({ all: false });
      const n = form["name"];
      const j = form["jobId"];
      const ct = form["contentType"];
      const f = form["content"];
      if (typeof n === "string") name = n;
      if (typeof j === "string") jobId = j;
      if (typeof ct === "string") contentType = ct;
      if (f instanceof File) {
        const ab = await f.arrayBuffer();
        content = Buffer.from(ab);
        if (!contentType) contentType = f.type || undefined;
        if (!name) name = f.name;
      } else if (typeof f === "string") {
        // Fallback: raw text content in a form field.
        content = Buffer.from(f, "utf8");
      }
    }
  } catch (err) {
    console.error("[workflow-artifacts] parse body:", err);
    return c.json({ error: "invalid request body" }, 400);
  }

  if (!name) return c.json({ error: "name is required" }, 400);
  if (!jobId) return c.json({ error: "jobId is required" }, 400);
  if (!content) return c.json({ error: "content is required" }, 400);

  if (content.byteLength > MAX_ARTIFACT_BYTES) {
    return c.json({ error: "payload exceeds 100MB limit" }, 413);
  }

  const result = await uploadArtifact({
    runId,
    jobId,
    name,
    content,
    contentType,
  });
  if (!result.ok) {
    // Treat validation errors as 400; other helper errors as 500.
    const msg = result.error;
    const status =
      msg.startsWith("name ") ||
      msg.includes("exceeds") ||
      msg.includes("required")
        ? 400
        : 500;
    return c.json({ error: msg }, status);
  }

  return c.json(
    {
      id: result.artifactId,
      name,
      size: content.byteLength,
      contentType: contentType || "application/octet-stream",
      downloadUrl: `/api/v1/artifacts/${result.artifactId}/download`,
    },
    201
  );
});

// ---------------------------------------------------------------------------
// GET /api/v1/runs/:runId/artifacts — list
// ---------------------------------------------------------------------------

app.get("/api/v1/runs/:runId/artifacts", async (c) => {
  const runId = c.req.param("runId");
  const repositoryId = await getRunRepositoryId(runId);
  if (!repositoryId) return c.json({ error: "run not found" }, 404);
  const repo = await loadRepoOwner(repositoryId);
  if (!repo) return c.json({ error: "repository not found" }, 404);

  const bearer = await resolveBearer(c.req.header("authorization"));
  const cookieUser = c.get("user");

  // Auth logic:
  //   - public repo → anyone with a valid bearer OR cookie session reads.
  //     Also allow totally-anonymous reads (matches packages + web UI style
  //     for public resources).
  //   - private repo → require bearer with read scope OR cookie session,
  //     AND caller must be the repo owner.
  if (repo.isPrivate) {
    let userId: string | null = null;
    if (bearer) {
      if (!hasReadScope(bearer.scopes)) {
        return c.json({ error: "token missing read scope" }, 403);
      }
      userId = bearer.user.id;
    } else if (cookieUser) {
      userId = cookieUser.id;
    } else {
      return c.json({ error: "authentication required" }, 401);
    }
    if (userId !== repo.ownerId) {
      return c.json({ error: "forbidden" }, 403);
    }
  } else if (bearer && !hasReadScope(bearer.scopes)) {
    // Public repo but caller presented a weird-scoped token. Don't silently
    // upgrade — reject.
    return c.json({ error: "token missing read scope" }, 403);
  }

  const result = await listArtifacts(runId);
  if (!result.ok) return c.json({ error: result.error }, 500);
  return c.json({ artifacts: result.artifacts });
});

// ---------------------------------------------------------------------------
// GET /api/v1/artifacts/:artifactId/download — binary download
// ---------------------------------------------------------------------------

app.get("/api/v1/artifacts/:artifactId/download", async (c) => {
  const artifactId = c.req.param("artifactId");

  const runId = await getArtifactRunId(artifactId);
  if (!runId) return c.json({ error: "not found" }, 404);
  const repositoryId = await getRunRepositoryId(runId);
  if (!repositoryId) return c.json({ error: "not found" }, 404);
  const repo = await loadRepoOwner(repositoryId);
  if (!repo) return c.json({ error: "not found" }, 404);

  const bearer = await resolveBearer(c.req.header("authorization"));
  const cookieUser = c.get("user");

  if (repo.isPrivate) {
    let userId: string | null = null;
    if (bearer) {
      if (!hasReadScope(bearer.scopes)) {
        return c.json({ error: "token missing read scope" }, 403);
      }
      userId = bearer.user.id;
    } else if (cookieUser) {
      userId = cookieUser.id;
    } else {
      return c.json({ error: "authentication required" }, 401);
    }
    if (userId !== repo.ownerId) {
      return c.json({ error: "forbidden" }, 403);
    }
  } else if (bearer && !hasReadScope(bearer.scopes)) {
    return c.json({ error: "token missing read scope" }, 403);
  }

  const result = await downloadArtifact(artifactId);
  if (!result.ok) {
    const status = result.error === "not found" ? 404 : 500;
    return c.json({ error: result.error }, status);
  }

  // Sanitize filename for Content-Disposition. Artifact name regex is
  // already `[A-Za-z0-9._-]+` so nothing dangerous can slip in, but we still
  // strip any stray quotes/newlines defensively.
  const safeName = result.name.replace(/["\r\n]/g, "");

  return new Response(result.content as BodyInit, {
    status: 200,
    headers: {
      "Content-Type": result.contentType,
      "Content-Disposition": `attachment; filename="${safeName}"`,
      "Content-Length": String(result.content.byteLength),
      "Cache-Control": "private, max-age=0, no-store",
    },
  });
});

// ---------------------------------------------------------------------------
// DELETE /api/v1/artifacts/:artifactId
// ---------------------------------------------------------------------------

app.delete("/api/v1/artifacts/:artifactId", async (c) => {
  const artifactId = c.req.param("artifactId");

  const bearer = await resolveBearer(c.req.header("authorization"));
  if (!bearer) return c.json({ error: "authentication required" }, 401);
  if (!hasAdminScope(bearer.scopes)) {
    return c.json({ error: "admin scope required" }, 403);
  }

  const runId = await getArtifactRunId(artifactId);
  if (!runId) return c.body(null, 404);
  const repositoryId = await getRunRepositoryId(runId);
  if (!repositoryId) return c.body(null, 404);
  const repo = await loadRepoOwner(repositoryId);
  if (!repo) return c.body(null, 404);
  if (repo.ownerId !== bearer.user.id) {
    return c.json({ error: "forbidden" }, 403);
  }

  const result = await deleteArtifact(artifactId);
  if (!result.ok) {
    const status = result.error === "not found" ? 404 : 500;
    return c.json({ error: result.error }, status);
  }
  return c.body(null, 204);
});

export default app;