Swadhin Biswas Feature/ai code reviewer (#79) · 8/16/2026
cfd400d
96 lines · 3.1 KB
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
import type { APIRoute } from "astro";
import { getDatabase, schema } from "@/db";
import { eq, desc } from "drizzle-orm";
import { getUserFromRequest } from "@/lib/auth";
import { unauthorized, badRequest, success, notFound, forbidden } from "@/lib/api";
import { withErrorHandler } from "@/lib/errors";
import { logger } from "@/lib/logger";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { generateId } from "@/lib/utils";
import { z } from "zod";
import {
  generateClientCredentials,
  hashClientSecret,
  OAUTH_SCOPES,
} from "@/lib/oauth-provider";

const createAppSchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().max(500).optional(),
  redirectUris: z.array(z.string().url()).min(1).max(10),
  scopes: z.array(z.enum(OAUTH_SCOPES)).optional(),
  homepageUrl: z.string().url().optional(),
  iconUrl: z.string().url().optional(),
});

// GET: list the user's registered apps
export const GET: APIRoute = withErrorHandler(async ({ request }) => {
  const user = await getUserFromRequest(request);
  if (!user) return unauthorized();

  const db = getDatabase() as NodePgDatabase<typeof schema>;
  const apps = await db.query.oauthApps.findMany({
    where: eq(schema.oauthApps.ownerId, user.userId),
    orderBy: [desc(schema.oauthApps.createdAt)],
  });

  return success({
    apps: apps.map((a) => ({
      id: a.id,
      name: a.name,
      description: a.description,
      clientId: a.clientId,
      redirectUris: JSON.parse(a.redirectUris),
      scopes: a.scopes ? JSON.parse(a.scopes) : [],
      homepageUrl: a.homepageUrl,
      iconUrl: a.iconUrl,
      createdAt: a.createdAt,
    })),
  });
});

// POST: register a new OAuth app (client secret shown once)
export const POST: APIRoute = withErrorHandler(async ({ request }) => {
  const user = await getUserFromRequest(request);
  if (!user) return unauthorized();

  const body = await request.json();
  const parsed = createAppSchema.safeParse(body);
  if (!parsed.success) return badRequest("Invalid input", parsed.error);

  const { clientId, clientSecret } = generateClientCredentials();
  const db = getDatabase() as NodePgDatabase<typeof schema>;
  const id = generateId("oauth");

  await db.insert(schema.oauthApps).values({
    id,
    ownerId: user.userId,
    name: parsed.data.name,
    description: parsed.data.description,
    clientId,
    clientSecretHash: hashClientSecret(clientSecret),
    redirectUris: JSON.stringify(parsed.data.redirectUris),
    scopes: parsed.data.scopes ? JSON.stringify(parsed.data.scopes) : null,
    homepageUrl: parsed.data.homepageUrl,
    iconUrl: parsed.data.iconUrl,
  });

  logger.info({ userId: user.userId, appId: id }, "OAuth app registered");
  return new Response(
    JSON.stringify({
      success: true,
      data: {
        app: {
          id,
          name: parsed.data.name,
          clientId,
          clientSecret, // shown once
          redirectUris: parsed.data.redirectUris,
          scopes: parsed.data.scopes || [],
        },
      },
    }),
    { status: 201, headers: { "Content-Type": "application/json" } },
  );
});