Swadhin Biswas Feature/ai code reviewer (#79) · 8/16/2026
cfd400d
227 lines · 6.0 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
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
/**
 * Personal Access Tokens API
 * Create, list, and revoke tokens for CLI authentication
 */

import { getDatabase, schema } from "@/db";
import { personalAccessTokens } from "@/db/schema/users";
import {
  badRequest,
  notFound,
  parseBody,
  success,
  unauthorized,
} from "@/lib/api";
import { getUserFromRequest } from "@/lib/auth";
import {
  getTokenPrefixForDisplay,
  hashPersonalAccessToken,
} from "@/lib/personal-access-token";
import type { APIRoute } from "astro";
import crypto from "crypto";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { z } from "zod";

// Generate a secure token like GitHub's format: ochat_xxxxxxxxxxxx
function generateToken(): { token: string } {
  const prefix = "och_";
  const randomPart = crypto.randomBytes(32).toString("base64url");
  return {
    token: `${prefix}${randomPart}`,
  };
}

const createTokenSchema = z.object({
  name: z.string().min(1).max(100),
  expiresIn: z
    .enum(["7d", "30d", "90d", "1y", "never"])
    .optional()
    .default("30d"),
  // Fine-grained scopes (WS4-01): subset of
  // ["repo:read", "repo:write", "admin", "notifications"]
  scopes: z
    .array(
      z.enum(["repo:read", "repo:write", "admin", "notifications"]),
    )
    .optional(),
});

import { withErrorHandler } from "@/lib/errors";
import { logger } from "@/lib/logger";

// ... existing imports ...

// GET /api/user/tokens - List user's tokens
export const GET: APIRoute = withErrorHandler(async ({ request }) => {
  const tokenPayload = await getUserFromRequest(request);
  if (!tokenPayload) {
    return unauthorized();
  }

  const db = getDatabase() as NodePgDatabase<typeof schema>;

  const tokens = await db.query.personalAccessTokens.findMany({
    where: eq(personalAccessTokens.userId, tokenPayload.userId),
    orderBy: (t, { desc }) => [desc(t.createdAt)],
  });

  // Return tokens without the actual token value (only prefix stored after creation)
  return success({
    tokens: tokens.map((t) => ({
      id: t.id,
      name: t.name,
      tokenPrefix: getTokenPrefixForDisplay(t.token),
      expiresAt: t.expiresAt,
      lastUsedAt: t.lastUsedAt,
      createdAt: t.createdAt,
      scopes: t.scopes ? JSON.parse(t.scopes) : null,
    })),
  });
});

// POST /api/user/tokens - Create new token
export const POST: APIRoute = withErrorHandler(async ({ request }) => {
  const tokenPayload = await getUserFromRequest(request);
  if (!tokenPayload) {
    return unauthorized();
  }

  const parsed = await parseBody(request, createTokenSchema);
  if ("error" in parsed) return parsed.error;

  const { name, expiresIn, scopes } = parsed.data;

  // Empty scopes array means full access (legacy behavior); only restrict
  // when the user explicitly picked scopes.
  const scopesJson =
    scopes && scopes.length > 0 ? JSON.stringify([...new Set(scopes)]) : null;

  // Calculate expiry date
  let expiresAt: Date | null = null;
  if (expiresIn !== "never") {
    const now = new Date();
    switch (expiresIn) {
      case "7d":
        now.setDate(now.getDate() + 7);
        break;
      case "30d":
        now.setDate(now.getDate() + 30);
        break;
      case "90d":
        now.setDate(now.getDate() + 90);
        break;
      case "1y":
        now.setFullYear(now.getFullYear() + 1);
        break;
    }
    expiresAt = now;
  }

  // Generate token
  const { token } = generateToken();
  const tokenId = `pat_${crypto.randomBytes(8).toString("hex")}`;

  const db = getDatabase() as NodePgDatabase<typeof schema>;

  // Store the full token (we'll show it once, then never again)
  // In production, you'd hash this and only store the hash
  await db.insert(personalAccessTokens).values({
    id: tokenId,
    userId: tokenPayload.userId,
    name,
    token: hashPersonalAccessToken(token),
    expiresAt,
    scopes: scopesJson,
    createdAt: new Date(),
  });

  // Audit log
  const { logAudit, getRequestMeta } = await import("@/lib/audit");
  const { ip, userAgent } = getRequestMeta(request);
  await logAudit({
    userId: tokenPayload.userId,
    action: "pat.create",
    actorIp: ip,
    actorUserAgent: userAgent,
    targetType: "token",
    targetId: tokenId,
    targetName: name,
    data: { expiresAt },
  });

  logger.info(
    { userId: tokenPayload.userId, tokenId },
    "Personal Access Token created",
  );

  return success({
    message: "Token created successfully",
    token: {
      id: tokenId,
      name,
      // IMPORTANT: This is the only time the full token is shown
      token: token,
      expiresAt,
      createdAt: new Date(),
    },
    warning:
      "Make sure to copy your token now. You won't be able to see it again!",
  });
});

// DELETE /api/user/tokens - Delete a token
export const DELETE: APIRoute = withErrorHandler(async ({ request }) => {
  const tokenPayload = await getUserFromRequest(request);
  if (!tokenPayload) {
    return unauthorized();
  }

  const url = new URL(request.url);
  const tokenId = url.searchParams.get("id");

  if (!tokenId) {
    return badRequest("Token ID required");
  }

  const db = getDatabase() as NodePgDatabase<typeof schema>;

  // Verify token belongs to user
  const existingToken = await db.query.personalAccessTokens.findFirst({
    where: eq(personalAccessTokens.id, tokenId),
  });

  if (!existingToken) {
    return notFound("Token not found");
  }

  if (existingToken.userId !== tokenPayload.userId) {
    return unauthorized("Not your token");
  }

  await db
    .delete(personalAccessTokens)
    .where(eq(personalAccessTokens.id, tokenId));

  // Audit log
  const { logAudit: logAuditDel, getRequestMeta: getMetaDel } =
    await import("@/lib/audit");
  const { ip: delIp, userAgent: delUa } = getMetaDel(request);
  await logAuditDel({
    userId: tokenPayload.userId,
    action: "pat.delete",
    actorIp: delIp,
    actorUserAgent: delUa,
    targetType: "token",
    targetId: tokenId,
    targetName: existingToken.name,
  });

  logger.info(
    { userId: tokenPayload.userId, tokenId },
    "Personal Access Token revoked",
  );

  return success({ message: "Token deleted" });
});