swadhinbiswas Initial commit of OpenCodeHub source · 12/11/2025
1110042
283 lines · 6.6 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
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
/**
 * Authentication utilities
 * JWT token management, password hashing, 2FA
 */

import bcrypt from "bcryptjs";
import { JWTPayload, SignJWT, jwtVerify } from "jose";
import { authenticator } from "otplib";
import { generateId, now } from "./utils";

// Types
export interface TokenPayload extends JWTPayload {
  userId: string;
  username: string;
  email: string;
  isAdmin?: boolean;
  sessionId?: string;
}

export interface SessionData {
  id: string;
  userId: string;
  token: string;
  userAgent?: string;
  ipAddress?: string;
  expiresAt: string;
  createdAt: string;
}

// JWT configuration
const JWT_SECRET = new TextEncoder().encode(
  process.env.JWT_SECRET || "dev-secret-change-in-production-minimum-32-chars"
);
const JWT_ISSUER = "opencodehub";
const JWT_AUDIENCE = "opencodehub-api";

/**
 * Create a JWT token
 */
export async function createToken(
  payload: Omit<TokenPayload, "iat" | "exp" | "iss" | "aud">
): Promise<string> {
  const expiresIn = process.env.JWT_EXPIRES_IN || "7d";
  const expirationTime = parseExpirationTime(expiresIn);

  return new SignJWT(payload)
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setIssuer(JWT_ISSUER)
    .setAudience(JWT_AUDIENCE)
    .setExpirationTime(expirationTime)
    .sign(JWT_SECRET);
}

/**
 * Verify and decode a JWT token
 */
export async function verifyToken(token: string): Promise<TokenPayload | null> {
  try {
    const { payload } = await jwtVerify(token, JWT_SECRET, {
      issuer: JWT_ISSUER,
      audience: JWT_AUDIENCE,
    });
    return payload as TokenPayload;
  } catch (error) {
    return null;
  }
}

/**
 * Hash a password
 */
export async function hashPassword(password: string): Promise<string> {
  const saltRounds = 12;
  return bcrypt.hash(password, saltRounds);
}

/**
 * Verify a password against a hash
 */
export async function verifyPassword(
  password: string,
  hash: string
): Promise<boolean> {
  return bcrypt.compare(password, hash);
}

/**
 * Generate a 2FA secret
 */
export function generate2FASecret(username: string): {
  secret: string;
  uri: string;
} {
  const secret = authenticator.generateSecret();
  const uri = authenticator.keyuri(username, "OpenCodeHub", secret);
  return { secret, uri };
}

/**
 * Verify a 2FA token
 */
export function verify2FAToken(token: string, secret: string): boolean {
  return authenticator.verify({ token, secret });
}

/**
 * Create a session
 */
export async function createSession(
  userId: string,
  userAgent?: string,
  ipAddress?: string
): Promise<SessionData> {
  const expiresIn = process.env.JWT_EXPIRES_IN || "7d";
  const expirationDate = calculateExpirationDate(expiresIn);

  const session: SessionData = {
    id: generateId("sess"),
    userId,
    token: generateId(), // Session token for reference
    userAgent,
    ipAddress,
    expiresAt: expirationDate.toISOString(),
    createdAt: now(),
  };

  return session;
}

/**
 * Generate SSH key fingerprint
 */
export function generateSSHFingerprint(publicKey: string): string {
  const crypto = require("crypto");
  // Extract the key data (ignore type and comment)
  const parts = publicKey.trim().split(" ");
  const keyData = parts.length >= 2 ? parts[1] : parts[0];
  const buffer = Buffer.from(keyData, "base64");
  const hash = crypto.createHash("sha256").update(buffer).digest("base64");
  return `SHA256:${hash.replace(/=+$/, "")}`;
}

/**
 * Extract SSH key type
 */
export function extractSSHKeyType(publicKey: string): string {
  const parts = publicKey.trim().split(" ");
  return parts[0] || "unknown";
}

/**
 * Validate password strength
 */
export function validatePasswordStrength(password: string): {
  valid: boolean;
  errors: string[];
} {
  const errors: string[] = [];

  if (password.length < 8) {
    errors.push("Password must be at least 8 characters long");
  }
  if (password.length > 128) {
    errors.push("Password must be at most 128 characters long");
  }
  if (!/[a-z]/.test(password)) {
    errors.push("Password must contain at least one lowercase letter");
  }
  if (!/[A-Z]/.test(password)) {
    errors.push("Password must contain at least one uppercase letter");
  }
  if (!/[0-9]/.test(password)) {
    errors.push("Password must contain at least one number");
  }

  return {
    valid: errors.length === 0,
    errors,
  };
}

/**
 * Generate a random token for email verification, password reset, etc.
 */
export function generateVerificationToken(): string {
  return generateId() + generateId();
}

/**
 * Calculate expiration date from string like "7d", "24h", "30m"
 */
function calculateExpirationDate(expiresIn: string): Date {
  const now = new Date();
  const match = expiresIn.match(/^(\d+)([dhms])$/);

  if (!match) {
    // Default to 7 days
    return new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
  }

  const value = parseInt(match[1], 10);
  const unit = match[2];

  const multipliers: Record<string, number> = {
    d: 24 * 60 * 60 * 1000,
    h: 60 * 60 * 1000,
    m: 60 * 1000,
    s: 1000,
  };

  return new Date(now.getTime() + value * multipliers[unit]);
}

/**
 * Parse expiration time for jose JWT
 */
function parseExpirationTime(expiresIn: string): string {
  // jose accepts formats like "7d", "24h", "30m"
  const match = expiresIn.match(/^(\d+)([dhms])$/);
  if (match) {
    return expiresIn;
  }
  return "7d";
}

/**
 * Extract token from Authorization header
 */
export function extractBearerToken(authHeader: string | null): string | null {
  if (!authHeader) return null;
  const parts = authHeader.split(" ");
  if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") {
    return null;
  }
  return parts[1];
}

/**
 * Get user from request
 */
export async function getUserFromRequest(
  request: Request
): Promise<TokenPayload | null> {
  const authHeader = request.headers.get("Authorization");
  const token = extractBearerToken(authHeader);

  if (!token) {
    // Check for cookie
    const cookieHeader = request.headers.get("Cookie");
    if (cookieHeader) {
      const cookies = parseCookies(cookieHeader);
      if (cookies.och_session) {
        return verifyToken(cookies.och_session);
      }
      // Fallback for legacy/dev
      if (cookies.auth_token) {
        return verifyToken(cookies.auth_token);
      }
    }
    return null;
  }

  return verifyToken(token);
}

/**
 * Parse cookies from header
 */
function parseCookies(cookieHeader: string): Record<string, string> {
  const cookies: Record<string, string> = {};
  const pairs = cookieHeader.split(";");

  for (const pair of pairs) {
    const [name, value] = pair.trim().split("=");
    if (name && value) {
      cookies[name] = decodeURIComponent(value);
    }
  }

  return cookies;
}