Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
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-sweepfix/audit-sweep-2026-07-26gatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
cross-product.tsx10.4 KB · 339 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
/**
 * Block K11 — Cross-product identity routes.
 *
 *   POST /api/v1/cross-product/token    — exchange any gluecron credential
 *                                         (session / PAT / OAuth) for a
 *                                         short-lived JWT bound to a sibling
 *                                         product audience.
 *   GET  /api/v1/cross-product/verify   — no-auth verifier used by siblings.
 *   POST /api/v1/cross-product/revoke   — owner revocation.
 *   GET  /settings/cross-product        — web UI listing active tokens.
 *
 * Every mint writes an `audit_log` row with action `cross_product.token_mint`.
 */

import { Hono } from "hono";
import { sql } from "drizzle-orm";
import { db } from "../db";
import { auditLog } from "../db/schema";
import { Layout } from "../views/layout";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import {
  ALLOWED_AUDIENCES,
  ALLOWED_SCOPES,
  isAllowedAudience,
  validateScopes,
  signCrossProductToken,
  verifyCrossProductToken,
  revokeCrossProductToken,
  listActiveCrossProductTokens,
  type Audience,
} from "../lib/cross-product-auth";

const cp = new Hono<AuthEnv>();

// softAuth is enough for the exchange endpoint — it runs session/PAT/OAuth
// resolution. We then gate on `c.get("user")` so we can return JSON 401
// rather than the redirect requireAuth emits for HTML paths.
cp.use("/api/v1/cross-product/token", softAuth);
cp.use("/api/v1/cross-product/revoke", softAuth);
cp.use("/settings/cross-product", softAuth, requireAuth);
cp.use("/settings/cross-product/*", softAuth, requireAuth);

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function parseBearer(c: {
  req: { header: (k: string) => string | undefined };
}): string | null {
  const h = c.req.header("authorization") || "";
  if (!h.toLowerCase().startsWith("bearer ")) return null;
  const tok = h.slice(7).trim();
  return tok || null;
}

async function recordMintAudit(
  userId: string,
  audience: Audience,
  scopes: string[],
  jti: string,
  ip: string | undefined,
  userAgent: string | undefined
): Promise<void> {
  try {
    await db.insert(auditLog).values({
      userId,
      repositoryId: null,
      action: "cross_product.token_mint",
      targetType: "cross_product_token",
      targetId: jti,
      ip: ip ?? null,
      userAgent: userAgent ?? null,
      metadata: JSON.stringify({ audience, scopes }),
    });
  } catch (err) {
    console.error("[cross-product] audit write failed:", err);
  }
}

// ---------------------------------------------------------------------------
// POST /api/v1/cross-product/token
// ---------------------------------------------------------------------------

cp.post("/api/v1/cross-product/token", async (c) => {
  const user = c.get("user");
  if (!user) {
    return c.json({ error: "unauthenticated" }, 401);
  }

  let body: Record<string, unknown>;
  try {
    body = (await c.req.json()) as Record<string, unknown>;
  } catch {
    return c.json({ error: "invalid_json" }, 400);
  }

  const audience = body.audience;
  if (!isAllowedAudience(audience)) {
    return c.json(
      {
        error: "unknown_audience",
        allowed: ALLOWED_AUDIENCES,
      },
      400
    );
  }

  let requestedScopes: string[] = [];
  if (Array.isArray(body.scope)) {
    requestedScopes = body.scope.filter(
      (s): s is string => typeof s === "string"
    );
  } else if (Array.isArray(body.scopes)) {
    requestedScopes = body.scopes.filter(
      (s): s is string => typeof s === "string"
    );
  }
  const scopes = validateScopes(requestedScopes);

  const ip =
    c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ||
    c.req.header("x-real-ip") ||
    undefined;
  const userAgent = c.req.header("user-agent") || undefined;

  try {
    const result = await signCrossProductToken({
      userId: user.id,
      email: user.email,
      audience,
      scopes,
    });
    await recordMintAudit(user.id, audience, scopes, result.jti, ip, userAgent);
    return c.json({
      token: result.token,
      expires_at: result.expiresAt.toISOString(),
      audience,
      scopes: result.scopes,
      jti: result.jti,
      issuer: "gluecron",
    });
  } catch (err) {
    console.error("[cross-product] mint failed:", err);
    return c.json({ error: "mint_failed" }, 500);
  }
});

// ---------------------------------------------------------------------------
// GET /api/v1/cross-product/verify   (no auth; sibling products call this)
// ---------------------------------------------------------------------------

async function handleVerify(c: {
  req: {
    header: (k: string) => string | undefined;
    json: () => Promise<unknown>;
  };
  json: (body: unknown, status?: number) => Response;
}): Promise<Response> {
  let token = parseBearer(c);
  if (!token) {
    // Fall back to body token for clients that prefer POST.
    try {
      const body = (await c.req.json()) as Record<string, unknown>;
      if (body && typeof body.token === "string") token = body.token;
    } catch {
      // no body — that's fine
    }
  }
  if (!token) {
    return c.json({ valid: false, error: "missing_token" }, 401);
  }

  const result = await verifyCrossProductToken(token);
  if (!result.valid) {
    return c.json({ valid: false, error: result.reason }, 401);
  }
  return c.json({
    valid: true,
    sub: result.sub,
    email: result.email,
    audience: result.audience,
    scopes: result.scopes,
    jti: result.jti,
    expires_at: result.expiresAt.toISOString(),
    issuer: "gluecron",
  });
}

cp.get("/api/v1/cross-product/verify", (c) => handleVerify(c));
cp.post("/api/v1/cross-product/verify", (c) => handleVerify(c));

// ---------------------------------------------------------------------------
// POST /api/v1/cross-product/revoke
// ---------------------------------------------------------------------------

cp.post("/api/v1/cross-product/revoke", async (c) => {
  const user = c.get("user");
  if (!user) return c.json({ error: "unauthenticated" }, 401);

  let body: Record<string, unknown>;
  try {
    body = (await c.req.json()) as Record<string, unknown>;
  } catch {
    return c.json({ error: "invalid_json" }, 400);
  }

  const jti = typeof body.jti === "string" ? body.jti : "";
  if (!jti) return c.json({ error: "jti_required" }, 400);

  const ok = await revokeCrossProductToken(jti, user.id);
  if (!ok) return c.json({ error: "not_found_or_not_owner" }, 404);

  // Audit the revoke (separate action from mint).
  try {
    await db.insert(auditLog).values({
      userId: user.id,
      repositoryId: null,
      action: "cross_product.token_revoke",
      targetType: "cross_product_token",
      targetId: jti,
      metadata: null,
    });
  } catch (err) {
    console.error("[cross-product] revoke audit failed:", err);
  }
  return c.json({ ok: true });
});

// ---------------------------------------------------------------------------
// GET /settings/cross-product   (web UI)
// ---------------------------------------------------------------------------

cp.get("/settings/cross-product", async (c) => {
  const user = c.get("user")!;
  let active: Awaited<ReturnType<typeof listActiveCrossProductTokens>> = [];
  try {
    active = await listActiveCrossProductTokens(user.id);
  } catch {
    active = [];
  }

  return c.html(
    <Layout title="Cross-product identity" user={user}>
      <div class="settings-container">
        <h2>Cross-product identity</h2>
        <p style="color: var(--text-muted); max-width: 640px">
          One gluecron account signs into Crontech and Gatetest. Active
          short-lived tokens issued for those sibling products are listed
          below. Tokens expire in {String(15)} minutes; revoke anything
          suspicious.
        </p>

        <h3 style="margin-top: 24px">Active tokens</h3>
        {active.length === 0 ? (
          <p style="color: var(--text-muted)">
            No active cross-product tokens. They are minted on-demand by the
            sibling products when you sign in.
          </p>
        ) : (
          <div>
            {active.map((tok) => (
              <div class="ssh-key-item">
                <div>
                  <strong>{tok.audience}</strong>
                  <div class="ssh-key-meta">
                    <code>{tok.jti.slice(0, 8)}...</code>
                    <span style="margin-left: 8px">
                      Scopes:{" "}
                      {tok.scopes.length > 0 ? tok.scopes.join(", ") : "none"}
                    </span>
                    <span style="margin-left: 8px">
                      Expires{" "}
                      {new Date(tok.expiresAt).toLocaleTimeString()}
                    </span>
                  </div>
                </div>
                <form
                  method="POST"
                  action={`/settings/cross-product/${tok.jti}/revoke`}
                >
                  <button type="submit" class="btn btn-danger btn-sm">
                    Revoke
                  </button>
                </form>
              </div>
            ))}
          </div>
        )}

        <h3 style="margin-top: 24px">Audiences</h3>
        <ul style="color: var(--text-muted)">
          {ALLOWED_AUDIENCES.map((a) => (
            <li>
              <code>{a}</code>
            </li>
          ))}
        </ul>

        <h3 style="margin-top: 24px">Supported scopes</h3>
        <ul style="color: var(--text-muted)">
          {ALLOWED_SCOPES.map((s) => (
            <li>
              <code>{s}</code>
            </li>
          ))}
        </ul>
      </div>
    </Layout>
  );
});

// Form POST for the web UI revoke button (keeps it cookie-based).
cp.post("/settings/cross-product/:jti/revoke", async (c) => {
  const user = c.get("user")!;
  const jti = c.req.param("jti");
  const ok = await revokeCrossProductToken(jti, user.id);
  if (ok) {
    try {
      await db.insert(auditLog).values({
        userId: user.id,
        repositoryId: null,
        action: "cross_product.token_revoke",
        targetType: "cross_product_token",
        targetId: jti,
        metadata: null,
      });
    } catch (err) {
      console.error("[cross-product] revoke audit failed:", err);
    }
  }
  return c.redirect("/settings/cross-product");
});

// Stub so TS narrows `sql` as imported (keeps the compiler happy if this
// file grows helpers later — stripped by the bundler).
void sql;

export default cp;