/ opencodehub / src / lib / oauth-provider.ts
Swadhin Biswas Feature/ai code reviewer (#79) · 8/16/2026
cfd400d
194 lines · 5.2 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
/**
 * OAuth Provider core (WS4-02)
 *
 * Authorization-code flow for third-party apps:
 *   register app → authorize (user consent) → code → token → userinfo
 */
import { createHash, randomBytes } from "crypto";
import { SignJWT, jwtVerify } from "jose";
import { getDatabase, schema } from "@/db";
import { eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { generateId } from "@/lib/utils";
import { logger } from "@/lib/logger";

export const OAUTH_SCOPES = [
  "user:read",
  "repo:read",
  "repo:write",
  "notifications",
] as const;
export type OAuthScope = (typeof OAUTH_SCOPES)[number];

export function hashClientSecret(secret: string): string {
  return createHash("sha256").update(`och-oauth:${secret}`).digest("hex");
}

export function generateClientCredentials(): {
  clientId: string;
  clientSecret: string;
} {
  return {
    clientId: `och_oauth_${randomBytes(16).toString("hex")}`,
    clientSecret: randomBytes(32).toString("base64url"),
  };
}

export function generateAuthCode(): string {
  return randomBytes(32).toString("base64url");
}

function getJwtSecret(): Uint8Array {
  const raw = process.env.JWT_SECRET || (import.meta as any).env?.JWT_SECRET;
  if (!raw) throw new Error("JWT_SECRET environment variable is required");
  return new TextEncoder().encode(raw);
}

/**
 * Mint an OAuth access token (JWT) for a user + app.
 */
export async function issueAccessToken(options: {
  userId: string;
  appId: string;
  scopes: string[];
  expiresInSeconds?: number;
}): Promise<string> {
  const expiresIn = options.expiresInSeconds ?? 60 * 60; // 1h default
  return new SignJWT({
    sub: options.userId,
    type: "oauth_access",
    appId: options.appId,
    scopes: options.scopes,
  })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime(`${Math.floor(expiresIn / 60)}m`)
    .sign(getJwtSecret());
}

/**
 * Mint an OAuth refresh token (JWT, 30 days). Validated only by signature
 * + type; rotation is encouraged by issuing a new one on every refresh.
 */
export async function issueRefreshToken(options: {
  userId: string;
  appId: string;
  scopes: string[];
  expiresInSeconds?: number;
}): Promise<string> {
  const expiresIn = options.expiresInSeconds ?? 30 * 24 * 60 * 60; // 30d
  return new SignJWT({
    sub: options.userId,
    type: "oauth_refresh",
    appId: options.appId,
    scopes: options.scopes,
  })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime(`${Math.floor(expiresIn / 60)}m`)
    .sign(getJwtSecret());
}

export interface OAuthRefreshPayload {
  userId: string;
  appId: string;
  scopes: string[];
  valid: boolean;
}

/** Validate a refresh token and return its claims (no rotation here). */
export async function verifyRefreshToken(
  token: string,
): Promise<OAuthRefreshPayload | null> {
  try {
    const { payload } = await jwtVerify(token, getJwtSecret());
    if (payload.type !== "oauth_refresh" || !payload.sub || !payload.appId) {
      return null;
    }
    return {
      userId: payload.sub,
      appId: String(payload.appId),
      scopes: Array.isArray(payload.scopes) ? (payload.scopes as string[]) : [],
      valid: true,
    };
  } catch {
    return null;
  }
}

export interface OAuthAccessTokenPayload {
  userId: string;
  appId: string;
  scopes: string[];
  valid: boolean;
}

/**
 * Validate an OAuth access token (issued by issueAccessToken).
 */
export async function verifyAccessToken(
  token: string,
): Promise<OAuthAccessTokenPayload | null> {
  try {
    const { payload } = await jwtVerify(token, getJwtSecret());
    if (payload.type !== "oauth_access" || !payload.sub || !payload.appId) {
      return null;
    }
    return {
      userId: payload.sub,
      appId: String(payload.appId),
      scopes: Array.isArray(payload.scopes) ? (payload.scopes as string[]) : [],
      valid: true,
    };
  } catch {
    return null;
  }
}

/**
 * Validate an authorization code (one-time use, expiry-checked).
 */
export async function consumeAuthorizationCode(options: {
  code: string;
  clientId: string;
  clientSecret: string;
  redirectUri: string;
}): Promise<{ userId: string; appId: string; scopes: string[] } | null> {
  const db = getDatabase() as NodePgDatabase<typeof schema>;

  const app = await db.query.oauthApps.findFirst({
    where: eq(schema.oauthApps.clientId, options.clientId),
  });
  if (!app) return null;
  if (app.clientSecretHash !== hashClientSecret(options.clientSecret)) {
    return null;
  }

  const codeHash = createHash("sha256").update(options.code).digest("hex");
  const record = await db.query.oauthAuthorizationCodes.findFirst({
    where: eq(schema.oauthAuthorizationCodes.codeHash, codeHash),
  });
  if (!record) return null;
  if (record.appId !== app.id) return null;
  if (record.usedAt) return null;
  if (new Date(record.expiresAt) < new Date()) return null;
  if (record.redirectUri !== options.redirectUri) return null;

  // One-time use
  await db
    .update(schema.oauthAuthorizationCodes)
    .set({ usedAt: new Date() })
    .where(eq(schema.oauthAuthorizationCodes.id, record.id));

  let scopes: string[] = [];
  try {
    scopes = JSON.parse(record.scopes);
  } catch {
    scopes = [];
  }

  return { userId: record.userId, appId: app.id, scopes };
}

export { generateId, logger };