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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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import crypto from "node:crypto";
import {
  createLinearWebhook,
  db,
  deleteLinearWebhook,
  exchangeLinearCode,
  fetchLinearViewer,
  revokeLinearToken,
  schema,
} from "@superlog/db";
import { and, eq, isNull } from "drizzle-orm";
import type { Hono } from "hono";
import type { Context } from "hono";
import { logger } from "./logger.js";
import { resolveActiveOrgContext } from "./org-context.js";

const log = logger.child({ scope: "linear" });

const SCOPES = "read,write,issues:create,comments:create";

type Vars = { userId: string; orgId: string | null };

export function buildLinearAuthorizeUrl(args: {
  clientId: string;
  redirectUrl: string;
  state: string;
}): string {
  const url = new URL("https://linear.app/oauth/authorize");
  url.searchParams.set("response_type", "code");
  url.searchParams.set("client_id", args.clientId);
  url.searchParams.set("redirect_uri", args.redirectUrl);
  url.searchParams.set("scope", SCOPES);
  url.searchParams.set("state", args.state);
  url.searchParams.set("prompt", "consent");
  url.searchParams.set("actor", "app");
  return url.toString();
}

// biome-ignore lint/suspicious/noExplicitAny: Hono Variables invariance.
export function mountLinearPublic(app: Hono<any>): void {
  const clientId = process.env.LINEAR_CLIENT_ID;
  const clientSecret = process.env.LINEAR_CLIENT_SECRET;
  const redirectUrl =
    process.env.LINEAR_OAUTH_REDIRECT_URL ?? "http://localhost:4100/linear/oauth/callback";
  const stateSecret = process.env.STATE_SIGNING_SECRET;
  const webOrigin = process.env.WEB_ORIGIN ?? "http://localhost:5173";

  if (!clientId || !clientSecret) {
    log.warn("LINEAR_CLIENT_ID/SECRET not set — /linear/oauth/callback disabled");
  }

  app.get("/linear/oauth/callback", async (c) => {
    if (!clientId || !clientSecret || !stateSecret) {
      return c.json({ error: "linear not configured" }, 503);
    }
    const err = c.req.query("error");
    if (err) return c.redirect(`${webOrigin}/settings?linear=denied`, 302);

    const code = c.req.query("code");
    const state = c.req.query("state") ?? "";
    if (!code) return c.redirect(`${webOrigin}/settings?linear=error`, 302);

    const decoded = verifyState(state, stateSecret);
    if (!decoded) return c.json({ error: "invalid state" }, 400);

    let token: Awaited<ReturnType<typeof exchangeLinearCode>>;
    try {
      token = await exchangeLinearCode({
        clientId,
        clientSecret,
        code,
        redirectUri: redirectUrl,
      });
    } catch (e) {
      log.error({ err: e }, "linear oauth exchange failed");
      return c.redirect(`${webOrigin}/settings?linear=error`, 302);
    }

    let viewer: Awaited<ReturnType<typeof fetchLinearViewer>>;
    try {
      viewer = await fetchLinearViewer(token.access_token);
    } catch (e) {
      log.error({ err: e }, "linear viewer fetch failed");
      return c.redirect(`${webOrigin}/settings?linear=error`, 302);
    }

    const expiresAt =
      typeof token.expires_in === "number" ? new Date(Date.now() + token.expires_in * 1000) : null;

    const webhook = await registerLinearWebhookSafely(token.access_token);
    await upsertInstallation({
      projectId: decoded.projectId,
      actorUserId: decoded.userId,
      workspaceId: viewer.organization.id,
      workspaceName: viewer.organization.name,
      workspaceUrlKey: viewer.organization.urlKey,
      actorEmail: viewer.email,
      accessToken: token.access_token,
      refreshToken: token.refresh_token ?? null,
      accessExpiresAt: expiresAt,
      scope: token.scope ?? null,
      webhookId: webhook?.id ?? null,
      webhookSecret: webhook?.secret ?? null,
    });
    log.info(
      {
        org_id: decoded.orgId,
        project_id: decoded.projectId,
        workspace_id: viewer.organization.id,
        workspace_name: viewer.organization.name,
        actor_user_id: decoded.userId,
      },
      "linear installed",
    );

    return c.redirect(`${webOrigin}/settings?linear=installed`, 302);
  });

  app.post("/linear/webhook", async (c) => {
    const rawBody = await c.req.text();
    const sigHeader = c.req.header("linear-signature") ?? "";
    const delivery = c.req.header("linear-delivery") ?? null;

    let parsed: LinearWebhookPayload;
    try {
      parsed = JSON.parse(rawBody) as LinearWebhookPayload;
    } catch {
      return c.json({ error: "invalid json" }, 400);
    }

    const webhookId = typeof parsed.webhookId === "string" ? parsed.webhookId : null;
    if (!webhookId) return c.json({ error: "missing webhookId" }, 400);

    const install = await db.query.linearInstallations.findFirst({
      where: eq(schema.linearInstallations.webhookId, webhookId),
    });
    if (!install || !install.webhookSecret) {
      log.warn({ webhook_id: webhookId }, "linear webhook from unknown installation");
      return c.json({ error: "unknown webhook" }, 404);
    }
    if (!verifyLinearSignature(rawBody, sigHeader, install.webhookSecret)) {
      log.warn({ webhook_id: webhookId, delivery }, "linear webhook signature failed");
      return c.json({ error: "bad signature" }, 401);
    }

    try {
      await handleLinearWebhook(parsed, install, delivery);
    } catch (e) {
      log.error({ err: e, webhook_id: webhookId }, "linear webhook handler failed");
      return c.json({ error: "handler failed" }, 500);
    }
    return c.json({ ok: true });
  });
}

type LinearWebhookActor = { id?: string; name?: string; avatarUrl?: string | null } | null;
type LinearWebhookPayload = {
  action?: string; // create | update | remove
  type?: string; // Issue | Comment | ...
  webhookId?: string;
  webhookTimestamp?: number;
  createdAt?: string;
  updatedFrom?: Record<string, unknown> | null;
  data?: {
    id?: string;
    identifier?: string;
    title?: string;
    body?: string;
    url?: string;
    issueId?: string;
    issue?: { id?: string };
    state?: { id?: string; name?: string; type?: string };
    assignee?: LinearWebhookActor;
    user?: LinearWebhookActor;
  };
  actor?: LinearWebhookActor;
};

function verifyLinearSignature(body: string, header: string, secret: string): boolean {
  if (!header) return false;
  const expected = crypto.createHmac("sha256", secret).update(body).digest("hex");
  const expectedBuf = Buffer.from(expected, "hex");
  const provided = header.startsWith("sha256=") ? header.slice("sha256=".length) : header;
  let providedBuf: Buffer;
  try {
    providedBuf = Buffer.from(provided, "hex");
  } catch {
    return false;
  }
  if (providedBuf.length !== expectedBuf.length) return false;
  return crypto.timingSafeEqual(providedBuf, expectedBuf);
}

async function handleLinearWebhook(
  payload: LinearWebhookPayload,
  install: schema.LinearInstallation,
  delivery: string | null,
): Promise<void> {
  const type = payload.type;
  const action = payload.action;
  if (!type || !action) return;

  const issueId =
    type === "Issue"
      ? payload.data?.id
      : type === "Comment"
        ? (payload.data?.issueId ?? payload.data?.issue?.id)
        : null;
  if (!issueId) return;

  const ticket = await db.query.agentLinearTickets.findFirst({
    where: and(
      eq(schema.agentLinearTickets.workspaceId, install.workspaceId),
      eq(schema.agentLinearTickets.ticketId, issueId),
    ),
  });
  if (!ticket) return;

  const occurredAt = payload.createdAt ? new Date(payload.createdAt) : new Date();

  if (type === "Issue" && action === "update") {
    const data = payload.data ?? {};
    const updates: Partial<typeof schema.agentLinearTickets.$inferInsert> = {
      lastSyncedAt: new Date(),
      updatedAt: new Date(),
    };
    if (typeof data.title === "string") updates.title = data.title;
    if (typeof data.identifier === "string") updates.ticketIdentifier = data.identifier;
    if (typeof data.url === "string") updates.url = data.url;
    if (data.state?.name) updates.state = data.state.name;
    if (data.state?.type) {
      updates.stateType = data.state.type as schema.AgentLinearTicketState;
    }
    if (data.assignee) {
      updates.assigneeName = data.assignee.name ?? null;
      updates.assigneeLinearId = data.assignee.id ?? null;
    }
    await db
      .update(schema.agentLinearTickets)
      .set(updates)
      .where(eq(schema.agentLinearTickets.id, ticket.id));
  }

  const { kind, summary, actor } = describeLinearEvent(payload);
  if (!kind) return;

  await db
    .insert(schema.agentLinearTicketEvents)
    .values({
      agentLinearTicketId: ticket.id,
      kind,
      summary,
      actorName: actor?.name ?? null,
      actorLinearId: actor?.id ?? null,
      actorAvatarUrl: actor?.avatarUrl ?? null,
      payload: payload as unknown as Record<string, unknown>,
      providerEventId: delivery,
      occurredAt,
    })
    .onConflictDoNothing();
}

function describeLinearEvent(payload: LinearWebhookPayload): {
  kind: string | null;
  summary: string | null;
  actor: LinearWebhookActor;
} {
  const actor = payload.actor ?? null;
  const type = payload.type;
  const action = payload.action;
  if (type === "Issue") {
    if (action === "update") {
      const stateChanged =
        payload.updatedFrom && Object.prototype.hasOwnProperty.call(payload.updatedFrom, "stateId");
      if (stateChanged) {
        return {
          kind: "ticket_state_changed",
          summary: payload.data?.state?.name
            ? `State → ${payload.data.state.name}`
            : "Ticket state changed",
          actor,
        };
      }
      return { kind: "ticket_updated", summary: "Ticket updated", actor };
    }
    if (action === "remove") return { kind: "ticket_removed", summary: "Ticket deleted", actor };
    return { kind: null, summary: null, actor };
  }
  if (type === "Comment") {
    if (action === "create") {
      return {
        kind: "ticket_comment",
        summary: "Comment on ticket",
        actor: payload.data?.user ?? actor,
      };
    }
    return { kind: null, summary: null, actor };
  }
  return { kind: null, summary: null, actor };
}

// biome-ignore lint/suspicious/noExplicitAny: Hono Variables invariance.
export function mountLinearAuthed(app: Hono<any>): void {
  const clientId = process.env.LINEAR_CLIENT_ID;
  const redirectUrl =
    process.env.LINEAR_OAUTH_REDIRECT_URL ?? "http://localhost:4100/linear/oauth/callback";
  const stateSecret = process.env.STATE_SIGNING_SECRET;

  app.get("/api/linear/installation", async (c) => {
    const ctx = await resolveUserOrg(c);
    if (!ctx) return c.json({ installed: false });
    const row = await findCurrentInstallation(ctx.projectId);
    if (!row) return c.json({ installed: false });
    return c.json({
      installed: true,
      workspaceId: row.workspaceId,
      workspaceName: row.workspaceName,
      workspaceUrlKey: row.workspaceUrlKey,
      actorEmail: row.actorEmail,
      scope: row.scope,
      needsReauth: row.reauthRequiredAt !== null,
      reauthReason: row.reauthReason,
      reauthRequiredAt: row.reauthRequiredAt?.toISOString() ?? null,
    });
  });

  app.post("/api/linear/install-url", async (c) => {
    if (!clientId || !stateSecret) {
      return c.json({ error: "linear not configured" }, 503);
    }
    const ctx = await resolveUserOrg(c);
    if (!ctx) return c.json({ error: "no org for user" }, 404);

    const state = signState(
      { orgId: ctx.orgId, projectId: ctx.projectId, userId: ctx.userId },
      stateSecret,
    );
    return c.json({ url: buildLinearAuthorizeUrl({ clientId, redirectUrl, state }) });
  });

  app.post("/api/linear/uninstall", async (c) => {
    const ctx = await resolveUserOrg(c);
    if (!ctx) return c.json({ error: "no org for user" }, 404);
    const row = await findCurrentInstallation(ctx.projectId);
    if (!row) return c.json({ ok: true });

    if (row.webhookId) {
      await deleteLinearWebhook({ accessToken: row.accessToken, webhookId: row.webhookId });
    }
    await revokeLinearToken(row.accessToken);
    await db
      .update(schema.linearInstallations)
      .set({ revokedAt: new Date(), updatedAt: new Date() })
      .where(eq(schema.linearInstallations.id, row.id));
    log.info(
      { org_id: ctx.orgId, workspace_id: row.workspaceId, actor_user_id: ctx.userId },
      "linear uninstalled",
    );
    return c.json({ ok: true });
  });
}

async function findCurrentInstallation(projectId: string) {
  return db.query.linearInstallations.findFirst({
    where: and(
      eq(schema.linearInstallations.projectId, projectId),
      isNull(schema.linearInstallations.revokedAt),
    ),
  });
}

async function upsertInstallation(v: {
  projectId: string;
  actorUserId: string | null;
  workspaceId: string;
  workspaceName: string | null;
  workspaceUrlKey: string | null;
  actorEmail: string | null;
  accessToken: string;
  refreshToken: string | null;
  accessExpiresAt: Date | null;
  scope: string | null;
  webhookId: string | null;
  webhookSecret: string | null;
}): Promise<void> {
  // Per-project: revoke any existing active install in this project so the
  // partial unique index (project_id WHERE revoked_at IS NULL) stays satisfied.
  await db.transaction(async (tx) => {
    await tx
      .update(schema.linearInstallations)
      .set({ revokedAt: new Date(), updatedAt: new Date() })
      .where(
        and(
          eq(schema.linearInstallations.projectId, v.projectId),
          isNull(schema.linearInstallations.revokedAt),
        ),
      );
    await tx.insert(schema.linearInstallations).values({
      projectId: v.projectId,
      actorUserId: v.actorUserId,
      workspaceId: v.workspaceId,
      workspaceName: v.workspaceName,
      workspaceUrlKey: v.workspaceUrlKey,
      actorEmail: v.actorEmail,
      accessToken: v.accessToken,
      refreshToken: v.refreshToken,
      accessExpiresAt: v.accessExpiresAt,
      scope: v.scope,
      webhookId: v.webhookId,
      webhookSecret: v.webhookSecret,
    });
  });
}

function getApiBaseUrl(): string | null {
  const raw = process.env.API_BASE_URL;
  if (!raw) return null;
  return raw.replace(/\/$/, "");
}

async function registerLinearWebhookSafely(
  accessToken: string,
): Promise<{ id: string; secret: string } | null> {
  const apiBase = getApiBaseUrl();
  if (!apiBase || apiBase.includes("localhost") || apiBase.includes("127.0.0.1")) {
    log.info("API_BASE_URL not public — skipping Linear webhook registration");
    return null;
  }
  try {
    const webhook = await createLinearWebhook({
      accessToken,
      url: `${apiBase}/linear/webhook`,
      resourceTypes: ["Issue", "Comment"],
      label: "Superlog",
    });
    return webhook;
  } catch (e) {
    log.error({ err: e }, "linear webhookCreate failed — continuing without webhook");
    return null;
  }
}

async function resolveUserOrg(
  c: Context<{ Variables: Vars }>,
): Promise<{ userId: string; orgId: string; projectId: string } | null> {
  const userId = c.var.userId;
  if (!userId) return null;
  const ctx = await resolveActiveOrgContext({
    userId,
    preferredOrgId: c.var.orgId,
  }).catch(() => null);
  if (!ctx) return null;
  return { userId: ctx.user.id, orgId: ctx.org.id, projectId: ctx.project.id };
}

type StatePayload = { orgId: string; projectId: string; userId: string };

function signState(p: StatePayload, secret: string): string {
  const body = `${p.orgId}.${p.projectId}.${p.userId}.${Date.now()}`;
  const sig = crypto.createHmac("sha256", secret).update(body).digest("base64url");
  return `${Buffer.from(body, "utf8").toString("base64url")}.${sig}`;
}

function verifyState(state: string, secret: string): StatePayload | null {
  const [payloadB64, sig] = state.split(".");
  if (!payloadB64 || !sig) return null;
  const body = Buffer.from(payloadB64, "base64url").toString("utf8");
  const expected = crypto.createHmac("sha256", secret).update(body).digest("base64url");
  const provided = Buffer.from(sig);
  const expectedBuf = Buffer.from(expected);
  if (provided.length !== expectedBuf.length) return null;
  if (!crypto.timingSafeEqual(provided, expectedBuf)) return null;
  // Current format is `${orgId}.${projectId}.${userId}.${ts}` (4 parts). Old
  // 3-part states (no projectId) are rejected — they expire in 10 min so worst
  // case is a user mid-install during deploy seeing one error and retrying.
  const parts = body.split(".");
  if (parts.length !== 4) return null;
  const [orgId, projectId, userId, tsRaw] = parts as [string, string, string, string];
  if (!orgId || !projectId || !userId || !tsRaw) return null;
  const ts = Number(tsRaw);
  if (!Number.isFinite(ts) || Date.now() - ts > 10 * 60 * 1000) return null;
  return { orgId, projectId, userId };
}